Skip to content

Commit 4eb205c

Browse files
committed
rust: implement find_exported_function
1 parent 114c95b commit 4eb205c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

bindings/rust/src/lib.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
77
mod sys;
88

9+
use std::ffi::CString;
910
use std::ptr::NonNull;
1011

1112
/// Parse and validate the input according to WebAssembly 1.0 rules. Returns true if the supplied input is valid.
@@ -158,6 +159,21 @@ impl From<ExecutionResult> for sys::FizzyExecutionResult {
158159
}
159160

160161
impl Instance {
162+
/// Find index of exported function by name.
163+
pub fn find_exported_function_index(&self, name: &str) -> Option<u32> {
164+
let module = unsafe { sys::fizzy_get_instance_module(self.0.as_ptr()) };
165+
let name = CString::new(name).expect("CString::new failed");
166+
let mut func_idx: u32 = 0;
167+
let found = unsafe {
168+
sys::fizzy_find_exported_function_index(module, name.as_ptr(), &mut func_idx)
169+
};
170+
if found {
171+
Some(func_idx)
172+
} else {
173+
None
174+
}
175+
}
176+
161177
/// Unsafe execution of a given function index `func_idx` with the given values `args`.
162178
///
163179
/// An invalid index, invalid inputs, or invalid depth can cause undefined behaviour.
@@ -214,6 +230,35 @@ mod tests {
214230
assert!(instance.is_ok());
215231
}
216232

233+
#[test]
234+
fn find_exported_function_index() {
235+
/* wat2wasm
236+
(module
237+
(func $f (export "foo") (result i32) (i32.const 42))
238+
(global (export "g1") i32 (i32.const 0))
239+
(table (export "tab") 0 anyfunc)
240+
(memory (export "mem") 1 2)
241+
)
242+
*/
243+
let input = hex::decode(
244+
"0061736d010000000105016000017f030201000404017000000504010101020606017f0041000b07180403666f6f00000267310300037461620100036d656d02000a06010400412a0b").unwrap();
245+
246+
let module = parse(&input);
247+
assert!(module.is_ok());
248+
let instance = module.unwrap().instantiate();
249+
assert!(instance.is_ok());
250+
let mut instance = instance.unwrap();
251+
252+
let func_idx = instance.find_exported_function_index(&"foo");
253+
assert!(func_idx.is_some());
254+
assert_eq!(func_idx.unwrap(), 0);
255+
256+
assert!(instance.find_exported_function_index(&"bar").is_none());
257+
assert!(instance.find_exported_function_index(&"g1").is_none());
258+
assert!(instance.find_exported_function_index(&"tab").is_none());
259+
assert!(instance.find_exported_function_index(&"mem").is_none());
260+
}
261+
217262
#[test]
218263
fn unsafe_execute_wasm() {
219264
/* wat2wasm

0 commit comments

Comments
 (0)