Skip to content

Commit 9d05550

Browse files
committed
rust: implement find_exported_function
1 parent 5f2df00 commit 9d05550

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

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.
@@ -159,6 +160,21 @@ impl From<ExecutionResult> for sys::FizzyExecutionResult {
159160
}
160161

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

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

0 commit comments

Comments
 (0)