rustwebassemblywasmtime

Is there a way to inspect a wasm module for imports


Let me explain a little bit about what I'm doing. I have an application that I'm embedding a wasm engine (specifically wasmtime) and writing the wasm in Rust. The target is not a browser so I'm not using wasm-bindgen. I'm trying to import two functions from the host environment. I've gotten it to work but with a bit of a hack and I'd like to remove the hack. Here's the problem I'm having. I've been able to figure out how to get Rust to generate the import statements in the wasm output. The problem is that if those functions aren't used the import statements in the wasm aren't included. Wasmtime seem to require that the number of imports passed to the wasm instance match the number of import statements. Makes sense that if the wasm module is expecting imports it's a problem if you don't provide them. The problem is, it's also an error if you provide imports and they're not used.

So I see two ways to fix that, either I need to figure out how to get Rust to include the import statements even if they're not used (right now the hack is to call the functions but ignore the results and it's basically a no-op) or to find a way to introspect the wasm an figure out what kind of imports it's expecting and only pass what it's asking for.

My question is is that the correct approach and if so how do you do that?


Solution

  • You can convert between .wasm (binary format) and .wat (textual format) with the The WebAssembly Binary Toolkit. It is open source. Maybe it can help you to extract the needed imports programmatically.

    The proper way, should be that your host environment gives you the import requirements before you initialize the instance. The Module gives you the imports. See the "Instance variables". You get that in between the module loading and the creation of the instance that itself needs these imports.