Add a Module::deserialize_file method (#3266)

* Add a `Module::deserialize_file` method

This commit adds a new method to the `wasmtime::Module` type,
`deserialize_file`. This is intended to be the same as the `deserialize`
method except for the serialized module is present as an on-disk file.
This enables Wasmtime to internally use `mmap` to avoid copying bytes
around and generally makes loading a module much faster.

A C API is added in this commit as well for various bindings to use this
accelerated path now as well. Another option perhaps for a Rust-based
API is to have an API taking a `File` itself to allow for a custom file
descriptor in one way or another, but for now that's left for a possible
future refactoring if we find a use case.

* Fix compat with main - handle readdonly mmap

* wip

* Try to fix Windows support
This commit is contained in:
Alex Crichton
2021-08-31 13:05:51 -05:00
committed by GitHub
parent 4378ea8e01
commit 9e0c910023
9 changed files with 339 additions and 20 deletions

View File

@@ -1,7 +1,8 @@
use anyhow::{bail, Result};
use std::fs;
use wasmtime::*;
fn serialize(engine: &Engine, wat: &'static str) -> Result<Vec<u8>> {
fn serialize(engine: &Engine, wat: &str) -> Result<Vec<u8>> {
let module = Module::new(&engine, wat)?;
Ok(module.serialize()?)
}
@@ -68,3 +69,32 @@ fn test_module_serialize_fail() -> Result<()> {
}
Ok(())
}
#[test]
fn test_deserialize_from_file() -> Result<()> {
serialize_and_call("(module (func (export \"run\") (result i32) i32.const 42))")?;
serialize_and_call(
"(module
(func (export \"run\") (result i32)
call $answer)
(func $answer (result i32)
i32.const 42))
",
)?;
return Ok(());
fn serialize_and_call(wat: &str) -> Result<()> {
let mut store = Store::<()>::default();
let td = tempfile::TempDir::new()?;
let buffer = serialize(store.engine(), wat)?;
let path = td.path().join("module.bin");
fs::write(&path, &buffer)?;
let module = unsafe { Module::deserialize_file(store.engine(), &path)? };
let instance = Instance::new(&mut store, &module, &[])?;
let func = instance.get_typed_func::<(), i32, _>(&mut store, "run")?;
assert_eq!(func.call(&mut store, ())?, 42);
Ok(())
}
}