* Compute instance exports on demand. Instead having instances eagerly compute a Vec of Externs, and bumping the refcount for each Extern, compute Externs on demand. This also enables `Instance::get_export` to avoid doing a linear search. This also means that the closure returned by `get0` and friends now holds an `InstanceHandle` to dynamically hold the instance live rather than being scoped to a lifetime. * Compute module imports and exports on demand too. And compute Extern::ty on demand too. * Add a utility function for computing an ExternType. * Add a utility function for looking up a function's signature. * Add a utility function for computing the ValType of a Global. * Rename wasmtime_environ::Export to EntityIndex. This helps differentiate it from other Export types in the tree, and describes what it is. * Fix a typo in a comment. * Simplify module imports and exports. * Make `Instance::exports` return the export names. This significantly simplifies the public API, as it's relatively common to need the names, and this avoids the need to do a zip with `Module::exports`. This also changes `ImportType` and `ExportType` to have public members instead of private members and accessors, as I find that simplifies the usage particularly in cases where there are temporary instances. * Remove `Instance::module`. This doesn't quite remove `Instance`'s `module` member, it gets a step closer. * Use a InstanceHandle utility function. * Don't consume self in the `Func::get*` methods. Instead, just create a closure containing the instance handle and the export for them to call. * Use `ExactSizeIterator` to avoid needing separate `num_*` methods. * Rename `Extern::func()` etc. to `into_func()` etc. * Revise examples to avoid using `nth`. * Add convenience methods to instance for getting specific extern types. * Use the convenience functions in more tests and examples. * Avoid cloning strings for `ImportType` and `ExportType`. * Remove more obviated clone() calls. * Simplify `Func`'s closure state. * Make wasmtime::Export's fields private. This makes them more consistent with ExportType. * Fix compilation error. * Make a lifetime parameter explicit, and use better lifetime names. Instead of 'me, use 'instance and 'module to make it clear what the lifetime is. * More lifetime cleanups.
94 lines
3.0 KiB
Rust
94 lines
3.0 KiB
Rust
use anyhow::{bail, Context};
|
|
use std::fs::File;
|
|
use std::path::Path;
|
|
use wasi_common::VirtualDirEntry;
|
|
use wasmtime::{Instance, Module, Store};
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub enum PreopenType {
|
|
/// Preopens should be satisfied with real OS files.
|
|
OS,
|
|
/// Preopens should be satisfied with virtual files.
|
|
Virtual,
|
|
}
|
|
|
|
pub fn instantiate(
|
|
data: &[u8],
|
|
bin_name: &str,
|
|
workspace: Option<&Path>,
|
|
preopen_type: PreopenType,
|
|
) -> anyhow::Result<()> {
|
|
let store = Store::default();
|
|
|
|
// Create our wasi context with pretty standard arguments/inheritance/etc.
|
|
// Additionally register any preopened directories if we have them.
|
|
let mut builder = wasi_common::WasiCtxBuilder::new();
|
|
|
|
builder.arg(bin_name).arg(".").inherit_stdio();
|
|
|
|
if let Some(workspace) = workspace {
|
|
match preopen_type {
|
|
PreopenType::OS => {
|
|
let preopen_dir = wasi_common::preopen_dir(workspace)
|
|
.context(format!("error while preopening {:?}", workspace))?;
|
|
builder.preopened_dir(preopen_dir, ".");
|
|
}
|
|
PreopenType::Virtual => {
|
|
// we can ignore the workspace path for virtual preopens because virtual preopens
|
|
// don't exist in the filesystem anyway - no name conflict concerns.
|
|
builder.preopened_virt(VirtualDirEntry::empty_directory(), ".");
|
|
}
|
|
}
|
|
}
|
|
|
|
// The nonstandard thing we do with `WasiCtxBuilder` is to ensure that
|
|
// `stdin` is always an unreadable pipe. This is expected in the test suite
|
|
// where `stdin` is never ready to be read. In some CI systems, however,
|
|
// stdin is closed which causes tests to fail.
|
|
let (reader, _writer) = os_pipe::pipe()?;
|
|
builder.stdin(reader_to_file(reader));
|
|
let snapshot1 = wasmtime_wasi::Wasi::new(&store, builder.build()?);
|
|
let module = Module::new(&store, &data).context("failed to create wasm module")?;
|
|
let imports = module
|
|
.imports()
|
|
.map(|i| {
|
|
let field_name = i.name();
|
|
if let Some(export) = snapshot1.get_export(field_name) {
|
|
Ok(export.clone().into())
|
|
} else {
|
|
bail!(
|
|
"import {} was not found in module {}",
|
|
field_name,
|
|
i.module()
|
|
)
|
|
}
|
|
})
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
let instance = Instance::new(&module, &imports).context(format!(
|
|
"error while instantiating Wasm module '{}'",
|
|
bin_name,
|
|
))?;
|
|
|
|
instance
|
|
.get_export("_start")
|
|
.context("expected a _start export")?
|
|
.into_func()
|
|
.context("expected export to be a func")?
|
|
.call(&[])?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
fn reader_to_file(reader: os_pipe::PipeReader) -> File {
|
|
use std::os::unix::prelude::*;
|
|
unsafe { File::from_raw_fd(reader.into_raw_fd()) }
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
fn reader_to_file(reader: os_pipe::PipeReader) -> File {
|
|
use std::os::windows::prelude::*;
|
|
unsafe { File::from_raw_handle(reader.into_raw_handle()) }
|
|
}
|