|
6 | 6 |
|
7 | 7 | mod sys; |
8 | 8 |
|
| 9 | +use std::ffi::CString; |
9 | 10 | use std::ptr::NonNull; |
10 | 11 |
|
11 | 12 | /// 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 { |
158 | 159 | } |
159 | 160 |
|
160 | 161 | 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 | + |
161 | 177 | /// Unsafe execution of a given function index `func_idx` with the given values `args`. |
162 | 178 | /// |
163 | 179 | /// An invalid index, invalid inputs, or invalid depth can cause undefined behaviour. |
@@ -214,6 +230,35 @@ mod tests { |
214 | 230 | assert!(instance.is_ok()); |
215 | 231 | } |
216 | 232 |
|
| 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 | + |
217 | 262 | #[test] |
218 | 263 | fn unsafe_execute_wasm() { |
219 | 264 | /* wat2wasm |
|
0 commit comments