diff --git a/benches/static_and_dynamic_functions.rs b/benches/static_and_dynamic_functions.rs index bc61ab3c4e8..7199c68da38 100644 --- a/benches/static_and_dynamic_functions.rs +++ b/benches/static_and_dynamic_functions.rs @@ -149,14 +149,14 @@ pub fn run_basic_dynamic_function(store: &Store, compiler_name: &str, c: &mut Cr fn run_static_benchmarks(_c: &mut Criterion) { #[cfg(feature = "llvm")] { - let store = + let mut store = Store::new_with_engine(&Universal::new(wasmer_compiler_llvm::LLVM::new()).engine()); run_basic_static_function(&store, "llvm", c); } #[cfg(feature = "cranelift")] { - let store = Store::new_with_engine( + let mut store = Store::new_with_engine( &Universal::new(wasmer_compiler_cranelift::Cranelift::new()).engine(), ); run_basic_static_function(&store, "cranelift", c); @@ -164,7 +164,7 @@ fn run_static_benchmarks(_c: &mut Criterion) { #[cfg(feature = "singlepass")] { - let store = Store::new_with_engine( + let mut store = Store::new_with_engine( &Universal::new(wasmer_compiler_singlepass::Singlepass::new()).engine(), ); run_basic_static_function(&store, "singlepass", c); @@ -174,14 +174,14 @@ fn run_static_benchmarks(_c: &mut Criterion) { fn run_dynamic_benchmarks(_c: &mut Criterion) { #[cfg(feature = "llvm")] { - let store = + let mut store = Store::new_with_engine(&Universal::new(wasmer_compiler_llvm::LLVM::new()).engine()); run_basic_dynamic_function(&store, "llvm", c); } #[cfg(feature = "cranelift")] { - let store = Store::new_with_engine( + let mut store = Store::new_with_engine( &Universal::new(wasmer_compiler_cranelift::Cranelift::new()).engine(), ); run_basic_dynamic_function(&store, "cranelift", c); @@ -189,7 +189,7 @@ fn run_dynamic_benchmarks(_c: &mut Criterion) { #[cfg(feature = "singlepass")] { - let store = Store::new_with_engine( + let mut store = Store::new_with_engine( &Universal::new(wasmer_compiler_singlepass::Singlepass::new()).engine(), ); run_basic_dynamic_function(&store, "singlepass", c); diff --git a/docs/migration_to_3.0.0.md b/docs/migration_to_3.0.0.md index 3ed2175b898..fc4f2511530 100644 --- a/docs/migration_to_3.0.0.md +++ b/docs/migration_to_3.0.0.md @@ -49,7 +49,7 @@ TODO You need a Store to create a context. Simple context is created using: ```rust -let ctx = Context::new(&store, ()); +let ctx = FunctionEnv::new(&mut store, ()); ``` For a Context with a custom Env, it will be similar: @@ -59,7 +59,7 @@ For a Context with a custom Env, it will be similar: struct Env { counter: i32, } -let ctx = Context::new(&store, Env{counter: 0}); +let ctx = FunctionEnv::new(&mut store, Env{counter: 0}); ``` ### Managing imports @@ -72,7 +72,7 @@ let import_object: Imports = imports! { "host_function" => host_function, }, }; -let instance = Instance::new(&mut ctx, &module, &import_object).expect("Could not instantiate module."); +let instance = Instance::new(&mut store, &module, &import_object).expect("Could not instantiate module."); ``` You can also build the `Imports` object manually: @@ -80,18 +80,17 @@ You can also build the `Imports` object manually: ```rust let mut import_object: Imports = Imports::new(); import_object.define("env", "host_function", host_function); -let instance = Instance::new(&mut ctx, &module, &import_object).expect("Could not instantiate module."); +let instance = Instance::new(&mut store, &module, &import_object).expect("Could not instantiate module."); ``` For WASI, don't forget to import memory to `WasiEnv` ```rust let mut wasi_env = WasiState::new("hello").finalize()?; -let mut ctx = Context::new(&store, wasi_env.clone()); -let import_object = wasi_env.import_object(&mut ctx.as_context_mut(), &module)?; -let instance = Instance::new(&mut ctx, &module, &import_object).expect("Could not instantiate module."); +let import_object = wasi_env.import_object(&mut store, &module)?; +let instance = Instance::new(&mut store, &module, &import_object).expect("Could not instantiate module."); let memory = instance.exports.get_memory("memory")?; -ctx.data_mut().set_memory(memory.clone()); +wasi_env.data_mut(&mut store).set_memory(memory.clone()); ``` #### `ChainableNamedResolver` is removed @@ -122,7 +121,7 @@ let wasm_bytes = wat2wasm( let compiler_config = Cranelift::default(); let engine = Universal::new(compiler_config).engine(); -let store = Store::new(&engine); +let mut store = Store::new(&engine); let module = Module::new(&store, wasm_bytes)?; let instance = Instance::new(&module, &imports! {})?; ``` @@ -137,7 +136,7 @@ let wasm_bytes = wat2wasm( )?; let compiler_config = Cranelift::default(); -let store = Store::new(&compiler_config); +let mut store = Store::new(&compiler_config); let module = Module::new(&store, wasm_bytes)?; let instance = Instance::new(&module, &imports! {})?; ``` diff --git a/examples/compiler_cranelift.rs b/examples/compiler_cranelift.rs index 8c6aff08dfa..9fce7497f03 100644 --- a/examples/compiler_cranelift.rs +++ b/examples/compiler_cranelift.rs @@ -10,7 +10,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -33,8 +33,7 @@ fn main() -> Result<(), Box> { let compiler = Cranelift::default(); // Create the store - let store = Store::new_with_engine(&Universal::new(compiler).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -45,14 +44,14 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; let sum = instance.exports.get_function("sum")?; println!("Calling `sum` function..."); // Let's call the `sum` exported function. The parameters are a // slice of `Value`s. The results are a boxed slice of `Value`s. - let results = sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut store, &[Value::I32(1), Value::I32(2)])?; println!("Results: {:?}", results); assert_eq!(results.to_vec(), vec![Value::I32(3)]); diff --git a/examples/compiler_llvm.rs b/examples/compiler_llvm.rs index b762443c415..dc68f7e0a1b 100644 --- a/examples/compiler_llvm.rs +++ b/examples/compiler_llvm.rs @@ -10,7 +10,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_llvm::LLVM; @@ -33,8 +33,7 @@ fn main() -> Result<(), Box> { let compiler = LLVM::default(); // Create the store - let store = Store::new_with_engine(&Universal::new(compiler).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -45,14 +44,14 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; let sum = instance.exports.get_function("sum")?; println!("Calling `sum` function..."); // Let's call the `sum` exported function. The parameters are a // slice of `Value`s. The results are a boxed slice of `Value`s. - let results = sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut store, &[Value::I32(1), Value::I32(2)])?; println!("Results: {:?}", results); assert_eq!(results.to_vec(), vec![Value::I32(3)]); diff --git a/examples/compiler_singlepass.rs b/examples/compiler_singlepass.rs index 2b7f87bea99..d44d0331897 100644 --- a/examples/compiler_singlepass.rs +++ b/examples/compiler_singlepass.rs @@ -10,7 +10,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_singlepass::Singlepass; @@ -33,8 +33,7 @@ fn main() -> Result<(), Box> { let compiler = Singlepass::default(); // Create the store - let store = Store::new_with_engine(&Universal::new(compiler).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -45,14 +44,14 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; let sum = instance.exports.get_function("sum")?; println!("Calling `sum` function..."); // Let's call the `sum` exported function. The parameters are a // slice of `Value`s. The results are a boxed slice of `Value`s. - let results = sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut store, &[Value::I32(1), Value::I32(2)])?; println!("Results: {:?}", results); assert_eq!(results.to_vec(), vec![Value::I32(3)]); diff --git a/examples/early_exit.rs b/examples/early_exit.rs index 9e2181cfd9b..4bfbc6bad3e 100644 --- a/examples/early_exit.rs +++ b/examples/early_exit.rs @@ -17,7 +17,8 @@ use anyhow::bail; use std::fmt; use wasmer::{ - imports, wat2wasm, Context, ContextMut, Function, Instance, Module, Store, TypedFunction, + imports, wat2wasm, Function, FunctionEnv, FunctionEnvMut, Instance, Module, Store, + TypedFunction, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -57,15 +58,15 @@ fn main() -> anyhow::Result<()> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. let module = Module::new(&store, wasm_bytes)?; // We declare the host function that we'll use to terminate execution. - fn early_exit(_ctx: ContextMut<()>) -> Result<(), ExitCode> { + fn early_exit(_ctx: FunctionEnvMut<()>) -> Result<(), ExitCode> { // This is where it happens. Err(ExitCode(1)) } @@ -73,23 +74,23 @@ fn main() -> anyhow::Result<()> { // Create an import object. let import_object = imports! { "env" => { - "early_exit" => Function::new_native(&mut ctx, early_exit), + "early_exit" => Function::new_native(&mut store, &env, early_exit), } }; println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Here we go. // // Get the `run` function which we'll use as our entrypoint. println!("Calling `run` function..."); let run_func: TypedFunction<(i32, i32), i32> = - instance.exports.get_typed_function(&mut ctx, "run")?; + instance.exports.get_typed_function(&mut store, "run")?; // When we call a function it can either succeed or fail. We expect it to fail. - match run_func.call(&mut ctx, 1, 7) { + match run_func.call(&mut store, 1, 7) { Ok(result) => { bail!( "Expected early termination with `ExitCode`, found: {}", diff --git a/examples/engine_cross_compilation.rs b/examples/engine_cross_compilation.rs index 467cb3facd5..0aa5c97b04d 100644 --- a/examples/engine_cross_compilation.rs +++ b/examples/engine_cross_compilation.rs @@ -79,7 +79,7 @@ fn main() -> Result<(), Box> { .engine(); // Create a store, that holds the engine. - let store = Store::new_with_engine(&engine); + let mut store = Store::new_with_engine(&engine); println!("Compiling module..."); // Let's compile the Wasm module. diff --git a/examples/engine_dylib.rs b/examples/engine_dylib.rs index 53be3ee62f2..2b9c4d7a773 100644 --- a/examples/engine_dylib.rs +++ b/examples/engine_dylib.rs @@ -55,7 +55,7 @@ fn main() -> Result<(), Box> { let engine = Dylib::new(compiler_config).engine(); // Create a store, that holds the engine. - let store = Store::new_with_engine(&engine); + let mut store = Store::new_with_engine(&engine); println!("Compiling module..."); // Here we go. diff --git a/examples/engine_headless.rs b/examples/engine_headless.rs index 4d84f0e38ae..16aabfb5b9b 100644 --- a/examples/engine_headless.rs +++ b/examples/engine_headless.rs @@ -47,7 +47,7 @@ use tempfile::NamedTempFile; use wasmer::imports; use wasmer::wat2wasm; -use wasmer::Context; +use wasmer::FunctionEnv; use wasmer::Instance; use wasmer::Module; use wasmer::Store; @@ -85,7 +85,7 @@ fn main() -> Result<(), Box> { let engine = Universal::new(compiler_config).engine(); // Create a store, that holds the engine. - let store = Store::new_with_engine(&engine); + let mut store = Store::new_with_engine(&engine); println!("Compiling module..."); // Let's compile the Wasm module. @@ -106,8 +106,8 @@ fn main() -> Result<(), Box> { println!("Creating headless Universal engine..."); // We create a headless Universal engine. let engine = Universal::headless().engine(); - let store = Store::new_with_engine(&engine); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&engine); + let mut env = FunctionEnv::new(&mut store, ()); println!("Deserializing module..."); // Here we go. @@ -127,12 +127,12 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; println!("Calling `sum` function..."); // The Wasm module exports a function called `sum`. let sum = instance.exports.get_function("sum")?; - let results = sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut store, &[Value::I32(1), Value::I32(2)])?; println!("Results: {:?}", results); assert_eq!(results.to_vec(), vec![Value::I32(3)]); diff --git a/examples/engine_universal.rs b/examples/engine_universal.rs index 819879669cb..1b6f2398b84 100644 --- a/examples/engine_universal.rs +++ b/examples/engine_universal.rs @@ -18,7 +18,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -52,8 +52,7 @@ fn main() -> Result<(), Box> { let engine = Universal::new(compiler_config).engine(); // Create a store, that holds the engine. - let store = Store::new_with_engine(&engine); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&engine); println!("Compiling module..."); // Here we go. @@ -73,12 +72,12 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // And here we go again. Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; println!("Calling `sum` function..."); // The Wasm module exports a function called `sum`. let sum = instance.exports.get_function("sum")?; - let results = sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut store, &[Value::I32(1), Value::I32(2)])?; println!("Results: {:?}", results); assert_eq!(results.to_vec(), vec![Value::I32(3)]); diff --git a/examples/errors.rs b/examples/errors.rs index cf701dd1fb7..d28698f8051 100644 --- a/examples/errors.rs +++ b/examples/errors.rs @@ -13,7 +13,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction}; +use wasmer::{imports, wat2wasm, FunctionEnv, Instance, Module, Store, TypedFunction}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -39,8 +39,8 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -51,7 +51,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Here we go. // @@ -63,11 +63,11 @@ fn main() -> Result<(), Box> { let div_by_zero: TypedFunction<(), i32> = instance .exports .get_function("div_by_zero")? - .native(&mut ctx)?; + .native(&mut store)?; println!("Calling `div_by_zero` function..."); // Let's call the `div_by_zero` exported function. - let result = div_by_zero.call(&mut ctx); + let result = div_by_zero.call(&mut store); // When we call a function it can either succeed or fail. We expect it to fail. match result { diff --git a/examples/exports_function.rs b/examples/exports_function.rs index 4ab86beac7f..e703976a44c 100644 --- a/examples/exports_function.rs +++ b/examples/exports_function.rs @@ -17,7 +17,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction, Value}; +use wasmer::{imports, wat2wasm, FunctionEnv, Instance, Module, Store, TypedFunction, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -40,8 +40,8 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -52,7 +52,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Here we go. // @@ -74,7 +74,7 @@ fn main() -> Result<(), Box> { // Let's call the `sum` exported function. The parameters are a // slice of `Value`s. The results are a boxed slice of `Value`s. let args = [Value::I32(1), Value::I32(2)]; - let result = sum.call(&mut ctx, &args)?; + let result = sum.call(&mut store, &args)?; println!("Results: {:?}", result); assert_eq!(result.to_vec(), vec![Value::I32(3)]); @@ -87,13 +87,13 @@ fn main() -> Result<(), Box> { // `Rets`, respectively for the parameters and the results. If // those values don't match the exported function signature, an // error will be raised. - let sum_native: TypedFunction<(i32, i32), i32> = sum.native(&mut ctx)?; + let sum_native: TypedFunction<(i32, i32), i32> = sum.native(&mut store)?; println!("Calling `sum` function (natively)..."); // Let's call the `sum` exported function. The parameters are // statically typed Rust values of type `i32` and `i32`. The // result, in this case particular case, in a unit of type `i32`. - let result = sum_native.call(&mut ctx, 3, 4)?; + let result = sum_native.call(&mut store, 3, 4)?; println!("Results: {:?}", result); assert_eq!(result, 7); diff --git a/examples/exports_global.rs b/examples/exports_global.rs index 19687fb3209..4b8f765573e 100644 --- a/examples/exports_global.rs +++ b/examples/exports_global.rs @@ -16,7 +16,7 @@ //! Ready? use wasmer::{ - imports, wat2wasm, Context, Instance, Module, Mutability, Store, Type, TypedFunction, Value, + imports, wat2wasm, FunctionEnv, Instance, Module, Mutability, Store, Type, TypedFunction, Value, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -40,8 +40,8 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -52,7 +52,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Here we go. // @@ -73,8 +73,8 @@ fn main() -> Result<(), Box> { println!("Getting globals types information..."); // Let's get the globals types. The results are `GlobalType`s. - let one_type = one.ty(&mut ctx); - let some_type = some.ty(&mut ctx); + let one_type = one.ty(&store); + let some_type = some.ty(&store); println!("`one` type: {:?} {:?}", one_type.mutability, one_type.ty); assert_eq!(one_type.mutability, Mutability::Const); @@ -91,11 +91,13 @@ fn main() -> Result<(), Box> { // // We will use an exported function for the `one` global // and the Global API for `some`. - let get_one: TypedFunction<(), f32> = - instance.exports.get_function("get_one")?.native(&mut ctx)?; + let get_one: TypedFunction<(), f32> = instance + .exports + .get_function("get_one")? + .native(&mut store)?; - let one_value = get_one.call(&mut ctx)?; - let some_value = some.get(&mut ctx); + let one_value = get_one.call(&mut store)?; + let some_value = some.get(&mut store); println!("`one` value: {:?}", one_value); assert_eq!(one_value, 1.0); @@ -106,13 +108,13 @@ fn main() -> Result<(), Box> { println!("Setting global values..."); // Trying to set the value of a immutable global (`const`) // will result in a `RuntimeError`. - let result = one.set(&mut ctx, Value::F32(42.0)); + let result = one.set(&mut store, Value::F32(42.0)); assert_eq!( result.expect_err("Expected an error").message(), "Attempted to set an immutable global" ); - let one_result = one.get(&mut ctx); + let one_result = one.get(&mut store); println!("`one` value after `set`: {:?}", one_result); assert_eq!(one_result, Value::F32(1.0)); @@ -124,14 +126,14 @@ fn main() -> Result<(), Box> { let set_some: TypedFunction = instance .exports .get_function("set_some")? - .native(&mut ctx)?; - set_some.call(&mut ctx, 21.0)?; - let some_result = some.get(&mut ctx); + .native(&mut store)?; + set_some.call(&mut store, 21.0)?; + let some_result = some.get(&mut store); println!("`some` value after `set_some`: {:?}", some_result); assert_eq!(some_result, Value::F32(21.0)); - some.set(&mut ctx, Value::F32(42.0))?; - let some_result = some.get(&mut ctx); + some.set(&mut store, Value::F32(42.0))?; + let some_result = some.get(&mut store); println!("`some` value after `set`: {:?}", some_result); assert_eq!(some_result, Value::F32(42.0)); diff --git a/examples/exports_memory.rs b/examples/exports_memory.rs index f8f5b29feb7..9d0f74726da 100644 --- a/examples/exports_memory.rs +++ b/examples/exports_memory.rs @@ -11,7 +11,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction, WasmPtr}; +use wasmer::{imports, wat2wasm, FunctionEnv, Instance, Module, Store, TypedFunction, WasmPtr}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -37,8 +37,8 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -49,10 +49,10 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; let load: TypedFunction<(), (WasmPtr, i32)> = - instance.exports.get_typed_function(&mut ctx, "load")?; + instance.exports.get_typed_function(&mut store, "load")?; // Here we go. // @@ -64,15 +64,15 @@ fn main() -> Result<(), Box> { // // The first thing we might be intersted in is the size of the memory. // Let's get it! - println!("Memory size (pages) {:?}", memory.size(&mut ctx)); - println!("Memory size (bytes) {:?}", memory.data_size(&mut ctx)); + println!("Memory size (pages) {:?}", memory.size(&mut store)); + println!("Memory size (bytes) {:?}", memory.data_size(&mut store)); // Oh! Wait, before reading the contents, we need to know // where to find what we are looking for. // // Fortunately, the Wasm module exports a `load` function // which will tell us the offset and length of the string. - let (ptr, length) = load.call(&mut ctx)?; + let (ptr, length) = load.call(&mut store)?; println!("String offset: {:?}", ptr.offset()); println!("String length: {:?}", length); @@ -81,7 +81,7 @@ fn main() -> Result<(), Box> { // We will get bytes out of the memory so we need to // decode them into a string. let str = ptr - .read_utf8_string(&mut ctx, memory, length as u32) + .read_utf8_string(&mut store, memory, length as u32) .unwrap(); println!("Memory contents: {:?}", str); @@ -91,7 +91,7 @@ fn main() -> Result<(), Box> { // To do that, we'll make a slice from our pointer and change the content // of each element. let new_str = b"Hello, Wasmer!"; - let values = ptr.slice(&mut ctx, memory, new_str.len() as u32).unwrap(); + let values = ptr.slice(&mut store, memory, new_str.len() as u32).unwrap(); for i in 0..new_str.len() { values.index(i as u64).write(new_str[i]).unwrap(); } @@ -104,7 +104,7 @@ fn main() -> Result<(), Box> { println!("New string length: {:?}", new_str.len()); let str = ptr - .read_utf8_string(&mut ctx, memory, new_str.len() as u32) + .read_utf8_string(&mut store, memory, new_str.len() as u32) .unwrap(); println!("New memory contents: {:?}", str); diff --git a/examples/features.rs b/examples/features.rs index d4f8058ce60..292c5c2cebc 100644 --- a/examples/features.rs +++ b/examples/features.rs @@ -10,7 +10,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Features, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Features, FunctionEnv, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -39,17 +39,17 @@ fn main() -> anyhow::Result<()> { let engine = Universal::new(compiler).features(features); // Now, let's define the store, and compile the module. - let store = Store::new_with_engine(&engine.engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&engine.engine()); + let mut env = FunctionEnv::new(&mut store, ()); let module = Module::new(&store, wasm_bytes)?; // Finally, let's instantiate the module, and execute something // :-). let import_object = imports! {}; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; let swap = instance.exports.get_function("swap")?; - let results = swap.call(&mut ctx, &[Value::I32(1), Value::I64(2)])?; + let results = swap.call(&mut store, &[Value::I32(1), Value::I64(2)])?; assert_eq!(results.to_vec(), vec![Value::I64(2), Value::I32(1)]); diff --git a/examples/hello_world.rs b/examples/hello_world.rs index 39ea01df73b..28887d618bc 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -7,7 +7,8 @@ //! ``` use wasmer::{ - imports, wat2wasm, Context, ContextMut, Function, Instance, Module, Store, TypedFunction, + imports, wat2wasm, Function, FunctionEnv, FunctionEnvMut, Instance, Module, Store, + TypedFunction, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -46,19 +47,19 @@ fn main() -> anyhow::Result<()> { // However for the purposes of showing what's happening, we create a compiler // (`Cranelift`) and pass it to an engine (`Universal`). We then pass the engine to // the store and are now ready to compile and run WebAssembly! - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); // We then use our store and Wasm bytes to compile a `Module`. // A `Module` is a compiled WebAssembly module that isn't ready to execute yet. let module = Module::new(&store, wasm_bytes)?; // Next we'll set up our `Module` so that we can execute it. First, create - // a `Context` in which to instantiate our `Module`. - let mut context = Context::new(&store, ()); + // a `FunctionEnv` in which to instantiate our `Module`. + let mut context = FunctionEnv::new(&mut store, ()); // We define a function to act as our "env" "say_hello" function imported in the // Wasm program above. - fn say_hello_world(_ctx: ContextMut<'_, ()>) { + fn say_hello_world(_ctx: FunctionEnvMut<'_, ()>) { println!("Hello, world!") } @@ -67,7 +68,7 @@ fn main() -> anyhow::Result<()> { // We use the default namespace "env". "env" => { // And call our function "say_hello". - "say_hello" => Function::new_native(&mut context, say_hello_world), + "say_hello" => Function::new_native(&mut store, &context, say_hello_world), } }; @@ -75,18 +76,17 @@ fn main() -> anyhow::Result<()> { // // An `Instance` is a compiled WebAssembly module that has been set up // and is ready to execute. - let instance = Instance::new(&mut context, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // We get the `TypedFunction` with no parameters and no results from the instance. // // Recall that the Wasm module exported a function named "run", this is getting // that exported function from the `Instance`. - let run_func: TypedFunction<(), ()> = - instance.exports.get_typed_function(&mut context, "run")?; + let run_func: TypedFunction<(), ()> = instance.exports.get_typed_function(&mut store, "run")?; // Finally, we call our exported Wasm function which will call our "say_hello" // function and return. - run_func.call(&mut context)?; + run_func.call(&mut store)?; Ok(()) } diff --git a/examples/imports_exports.rs b/examples/imports_exports.rs index fc07e22a1eb..eb154317e3d 100644 --- a/examples/imports_exports.rs +++ b/examples/imports_exports.rs @@ -16,8 +16,8 @@ //! Ready? use wasmer::{ - imports, wat2wasm, Context, Function, FunctionType, Global, Instance, Memory, Module, Store, - Table, Type, Value, + imports, wat2wasm, Function, FunctionEnv, FunctionType, Global, Instance, Memory, Module, + Store, Table, Type, Value, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -44,8 +44,8 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -60,12 +60,12 @@ fn main() -> Result<(), Box> { // covered in more detail in other examples. println!("Creating the imported function..."); let host_function_signature = FunctionType::new(vec![], vec![Type::I32]); - let host_function = Function::new(&mut ctx, &host_function_signature, |_ctx, _args| { + let host_function = Function::new(&mut store, &env, &host_function_signature, |_ctx, _args| { Ok(vec![Value::I32(42)]) }); println!("Creating the imported global..."); - let host_global = Global::new(&mut ctx, Value::I32(42)); + let host_global = Global::new(&mut store, Value::I32(42)); // Create an import object. // @@ -90,7 +90,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Here we go. // @@ -103,19 +103,19 @@ fn main() -> Result<(), Box> { // Let's get them. println!("Getting the exported function..."); let function = instance.exports.get::("guest_function")?; - println!("Got exported function of type: {:?}", function.ty(&mut ctx)); + println!("Got exported function of type: {:?}", function.ty(&store)); println!("Getting the exported global..."); let global = instance.exports.get::("guest_global")?; - println!("Got exported global of type: {:?}", global.ty(&mut ctx)); + println!("Got exported global of type: {:?}", global.ty(&store)); println!("Getting the exported memory..."); let memory = instance.exports.get::("guest_memory")?; - println!("Got exported memory of type: {:?}", memory.ty(&mut ctx)); + println!("Got exported memory of type: {:?}", memory.ty(&store)); println!("Getting the exported table..."); let table = instance.exports.get::("guest_table")?; - println!("Got exported table of type: {:?}", table.ty(&mut ctx)); + println!("Got exported table of type: {:?}", table.ty(&store)); Ok(()) } diff --git a/examples/imports_function.rs b/examples/imports_function.rs index ca1bdebf39d..0e08360e94d 100644 --- a/examples/imports_function.rs +++ b/examples/imports_function.rs @@ -18,8 +18,8 @@ //! Ready? use wasmer::{ - imports, wat2wasm, Context, ContextMut, Function, FunctionType, Instance, Module, Store, Type, - TypedFunction, Value, + imports, wat2wasm, Function, FunctionEnv, FunctionEnvMut, FunctionType, Instance, Module, + Store, Type, TypedFunction, Value, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -45,8 +45,10 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut ctx1 = FunctionEnv::new(&mut store, ()); + struct MyEnv; + let mut ctx2 = FunctionEnv::new(&mut store, MyEnv {}); println!("Compiling module..."); // Let's compile the Wasm module. @@ -54,17 +56,22 @@ fn main() -> Result<(), Box> { // Create the functions let multiply_dynamic_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); - let multiply_dynamic = Function::new(&mut ctx, &multiply_dynamic_signature, |_ctx, args| { - println!("Calling `multiply_dynamic`..."); + let multiply_dynamic = Function::new( + &mut store, + &ctx1, + &multiply_dynamic_signature, + |_ctx, args| { + println!("Calling `multiply_dynamic`..."); - let result = args[0].unwrap_i32() * 2; + let result = args[0].unwrap_i32() * 2; - println!("Result of `multiply_dynamic`: {:?}", result); + println!("Result of `multiply_dynamic`: {:?}", result); - Ok(vec![Value::I32(result)]) - }); + Ok(vec![Value::I32(result)]) + }, + ); - fn multiply(_ctx: ContextMut<()>, a: i32) -> i32 { + fn multiply(_ctx: FunctionEnvMut, a: i32) -> i32 { println!("Calling `multiply_native`..."); let result = a * 3; @@ -72,7 +79,7 @@ fn main() -> Result<(), Box> { result } - let multiply_native = Function::new_native(&mut ctx, multiply); + let multiply_native = Function::new_native(&mut store, &ctx2, multiply); // Create an import object. let import_object = imports! { @@ -84,18 +91,18 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Here we go. // // The Wasm module exports a function called `sum`. Let's get it. let sum: TypedFunction<(i32, i32), i32> = - instance.exports.get_function("sum")?.native(&mut ctx)?; + instance.exports.get_function("sum")?.native(&mut store)?; println!("Calling `sum` function..."); // Let's call the `sum` exported function. It will call each // of the imported functions. - let result = sum.call(&mut ctx, 1, 2)?; + let result = sum.call(&mut store, 1, 2)?; println!("Results of `sum`: {:?}", result); assert_eq!(result, 8); diff --git a/examples/imports_function_env.rs b/examples/imports_function_env.rs index 9f0fcafda96..7eee4b02245 100644 --- a/examples/imports_function_env.rs +++ b/examples/imports_function_env.rs @@ -21,7 +21,8 @@ use std::sync::{Arc, Mutex}; use wasmer::{ - imports, wat2wasm, Context, ContextMut, Function, Instance, Module, Store, TypedFunction, + imports, wat2wasm, Function, FunctionEnv, FunctionEnvMut, Instance, Module, Store, + TypedFunction, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -51,7 +52,7 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -65,7 +66,7 @@ fn main() -> Result<(), Box> { let shared_counter: Arc> = Arc::new(Mutex::new(0)); // Once we have our counter we'll wrap it inside en `Env` which we'll pass - // to our imported functionsvia the Context. + // to our imported functionsvia the FunctionEnv. // // This struct may have been anything. The only constraint is it must be // possible to know the size of the `Env` at compile time (i.e it has to @@ -77,18 +78,18 @@ fn main() -> Result<(), Box> { } // Create the functions - fn get_counter(ctx: ContextMut) -> i32 { + fn get_counter(ctx: FunctionEnvMut) -> i32 { *ctx.data().counter.lock().unwrap() } - fn add_to_counter(mut ctx: ContextMut, add: i32) -> i32 { + fn add_to_counter(mut ctx: FunctionEnvMut, add: i32) -> i32 { let mut counter_ref = ctx.data_mut().counter.lock().unwrap(); *counter_ref += add; *counter_ref } - let mut ctx = Context::new( - &store, + let mut env = FunctionEnv::new( + &mut store, Env { counter: shared_counter.clone(), }, @@ -97,14 +98,14 @@ fn main() -> Result<(), Box> { // Create an import object. let import_object = imports! { "env" => { - "get_counter" => Function::new_native(&mut ctx, get_counter), - "add_to_counter" => Function::new_native(&mut ctx, add_to_counter), + "get_counter" => Function::new_native(&mut store, &env, get_counter), + "add_to_counter" => Function::new_native(&mut store, &env, add_to_counter), } }; println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Here we go. // @@ -112,7 +113,7 @@ fn main() -> Result<(), Box> { let increment_counter_loop: TypedFunction = instance .exports .get_function("increment_counter_loop")? - .native(&mut ctx)?; + .native(&mut store)?; let counter_value: i32 = *shared_counter.lock().unwrap(); println!("Initial ounter value: {:?}", counter_value); @@ -121,7 +122,7 @@ fn main() -> Result<(), Box> { // Let's call the `increment_counter_loop` exported function. // // It will loop five times thus incrementing our counter five times. - let result = increment_counter_loop.call(&mut ctx, 5)?; + let result = increment_counter_loop.call(&mut store, 5)?; let counter_value: i32 = *shared_counter.lock().unwrap(); println!("New counter value (host): {:?}", counter_value); diff --git a/examples/imports_global.rs b/examples/imports_global.rs index 7e6eaaddb5f..87e9318b711 100644 --- a/examples/imports_global.rs +++ b/examples/imports_global.rs @@ -15,7 +15,9 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Global, Instance, Module, Store, TypedFunction, Value}; +use wasmer::{ + imports, wat2wasm, FunctionEnv, Global, Instance, Module, Store, TypedFunction, Value, +}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -38,16 +40,16 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. let module = Module::new(&store, wasm_bytes)?; // Create the globals - let some = Global::new(&mut ctx, Value::F32(1.0)); - let other = Global::new_mut(&mut ctx, Value::F32(2.0)); + let some = Global::new(&mut store, Value::F32(1.0)); + let other = Global::new_mut(&mut store, Value::F32(2.0)); // Create an import object. // We add the two required globals in the `env` namespace. @@ -60,7 +62,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Here we go. // @@ -69,34 +71,34 @@ fn main() -> Result<(), Box> { let get_some: TypedFunction<(), f32> = instance .exports .get_function("get_some")? - .native(&mut ctx)?; + .native(&mut store)?; let get_other: TypedFunction<(), f32> = instance .exports .get_function("get_other")? - .native(&mut ctx)?; + .native(&mut store)?; - let some_result = get_some.call(&mut ctx)?; - let other_result = get_other.call(&mut ctx)?; + let some_result = get_some.call(&mut store)?; + let other_result = get_other.call(&mut store)?; println!("some value (via `get_some`): {:?}", some_result); - println!("some value (via Global API): {:?}", some.get(&mut ctx)); + println!("some value (via Global API): {:?}", some.get(&mut store)); println!("other value (via `get_other`): {:?}", other_result); - println!("other value (via Global API): {:?}", other.get(&mut ctx)); + println!("other value (via Global API): {:?}", other.get(&mut store)); - assert_eq!(some_result, some.get(&mut ctx).f32().unwrap()); - assert_eq!(other_result, other.get(&mut ctx).f32().unwrap()); + assert_eq!(some_result, some.get(&mut store).f32().unwrap()); + assert_eq!(other_result, other.get(&mut store).f32().unwrap()); println!("Setting global values..."); // Trying to set the value of a immutable global (`const`) // will result in a `RuntimeError`. - let result = some.set(&mut ctx, Value::F32(42.0)); + let result = some.set(&mut store, Value::F32(42.0)); assert_eq!( result.expect_err("Expected an error").message(), "Attempted to set an immutable global" ); - other.set(&mut ctx, Value::F32(21.0))?; - let other_result = other.get(&mut ctx); + other.set(&mut store, Value::F32(21.0))?; + let other_result = other.get(&mut store); println!("other value after `set`: {:?}", other_result); assert_eq!(other_result, Value::F32(21.0)); @@ -106,11 +108,11 @@ fn main() -> Result<(), Box> { let set_other: TypedFunction = instance .exports .get_function("set_other")? - .native(&mut ctx)?; - set_other.call(&mut ctx, 42.0)?; + .native(&mut store)?; + set_other.call(&mut store, 42.0)?; - println!("other value (via Global API): {:?}", other.get(&mut ctx)); - assert_eq!(other.get(&mut ctx), Value::F32(42.0)); + println!("other value (via Global API): {:?}", other.get(&mut store)); + assert_eq!(other.get(&mut store), Value::F32(42.0)); Ok(()) } diff --git a/examples/instance.rs b/examples/instance.rs index 5e8a9de09ac..2e102ea65bd 100644 --- a/examples/instance.rs +++ b/examples/instance.rs @@ -14,7 +14,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction}; +use wasmer::{imports, wat2wasm, FunctionEnv, Instance, Module, Store, TypedFunction}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -39,8 +39,8 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -51,7 +51,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // We now have an instance ready to be used. // @@ -61,11 +61,13 @@ fn main() -> Result<(), Box> { // Here we are retrieving the exported function. We won't go into details here // as the main focus of this example is to show how to create an instance out // of a Wasm module and have basic interactions with it. - let add_one: TypedFunction = - instance.exports.get_function("add_one")?.native(&mut ctx)?; + let add_one: TypedFunction = instance + .exports + .get_function("add_one")? + .native(&mut store)?; println!("Calling `add_one` function..."); - let result = add_one.call(&mut ctx, 1)?; + let result = add_one.call(&mut store, 1)?; println!("Results of `add_one`: {:?}", result); assert_eq!(result, 2); diff --git a/examples/memory.rs b/examples/memory.rs index 66fa88f8e77..1d2b6b7a82d 100644 --- a/examples/memory.rs +++ b/examples/memory.rs @@ -15,7 +15,9 @@ //! Ready? use std::mem; -use wasmer::{imports, wat2wasm, Bytes, Context, Instance, Module, Pages, Store, TypedFunction}; +use wasmer::{ + imports, wat2wasm, Bytes, FunctionEnv, Instance, Module, Pages, Store, TypedFunction, +}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -57,8 +59,8 @@ fn main() -> anyhow::Result<()> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -69,17 +71,18 @@ fn main() -> anyhow::Result<()> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // The module exports some utility functions, let's get them. // // These function will be used later in this example. - let mem_size: TypedFunction<(), i32> = - instance.exports.get_typed_function(&mut ctx, "mem_size")?; + let mem_size: TypedFunction<(), i32> = instance + .exports + .get_typed_function(&mut store, "mem_size")?; let get_at: TypedFunction = - instance.exports.get_typed_function(&mut ctx, "get_at")?; + instance.exports.get_typed_function(&mut store, "get_at")?; let set_at: TypedFunction<(i32, i32), ()> = - instance.exports.get_typed_function(&mut ctx, "set_at")?; + instance.exports.get_typed_function(&mut store, "set_at")?; let memory = instance.exports.get_memory("memory")?; // We now have an instance ready to be used. @@ -93,15 +96,15 @@ fn main() -> anyhow::Result<()> { // The size in bytes can be found either by querying its pages or by // querying the memory directly. println!("Querying memory size..."); - assert_eq!(memory.size(&mut ctx), Pages::from(1)); - assert_eq!(memory.size(&mut ctx).bytes(), Bytes::from(65536 as usize)); - assert_eq!(memory.data_size(&mut ctx), 65536); + assert_eq!(memory.size(&mut store), Pages::from(1)); + assert_eq!(memory.size(&mut store).bytes(), Bytes::from(65536 as usize)); + assert_eq!(memory.data_size(&mut store), 65536); // Sometimes, the guest module may also export a function to let you // query the memory. Here we have a `mem_size` function, let's try it: - let result = mem_size.call(&mut ctx)?; + let result = mem_size.call(&mut store)?; println!("Memory size: {:?}", result); - assert_eq!(Pages::from(result as u32), memory.size(&mut ctx)); + assert_eq!(Pages::from(result as u32), memory.size(&mut store)); // Now that we know the size of our memory, it's time to see how wa // can change this. @@ -110,9 +113,9 @@ fn main() -> anyhow::Result<()> { // see how we can do that: println!("Growing memory..."); // Here we are requesting two more pages for our memory. - memory.grow(&mut ctx, 2)?; - assert_eq!(memory.size(&mut ctx), Pages::from(3)); - assert_eq!(memory.data_size(&mut ctx), 65536 * 3); + memory.grow(&mut store, 2)?; + assert_eq!(memory.size(&mut store), Pages::from(3)); + assert_eq!(memory.data_size(&mut store), 65536 * 3); // Now that we know how to query and adjust the size of the memory, // let's see how wa can write to it or read from it. @@ -122,9 +125,9 @@ fn main() -> anyhow::Result<()> { // addresses to write and read a value. let mem_addr = 0x2220; let val = 0xFEFEFFE; - set_at.call(&mut ctx, mem_addr, val)?; + set_at.call(&mut store, mem_addr, val)?; - let result = get_at.call(&mut ctx, mem_addr)?; + let result = get_at.call(&mut store, mem_addr)?; println!("Value at {:#x?}: {:?}", mem_addr, result); assert_eq!(result, val); @@ -133,9 +136,9 @@ fn main() -> anyhow::Result<()> { let page_size = 0x1_0000; let mem_addr = (page_size * 2) - mem::size_of_val(&val) as i32; let val = 0xFEA09; - set_at.call(&mut ctx, mem_addr, val)?; + set_at.call(&mut store, mem_addr, val)?; - let result = get_at.call(&mut ctx, mem_addr)?; + let result = get_at.call(&mut store, mem_addr)?; println!("Value at {:#x?}: {:?}", mem_addr, result); assert_eq!(result, val); diff --git a/examples/metering.rs b/examples/metering.rs index 613e2cab446..8f16e7adeec 100644 --- a/examples/metering.rs +++ b/examples/metering.rs @@ -18,7 +18,7 @@ use anyhow::bail; use std::sync::Arc; use wasmer::wasmparser::Operator; use wasmer::CompilerConfig; -use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction}; +use wasmer::{imports, wat2wasm, FunctionEnv, Instance, Module, Store, TypedFunction}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; use wasmer_middlewares::{ @@ -70,8 +70,8 @@ fn main() -> anyhow::Result<()> { // // We use our previously create compiler configuration // with the Universal engine. - let store = Store::new_with_engine(&Universal::new(compiler_config).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(compiler_config).engine()); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -82,17 +82,19 @@ fn main() -> anyhow::Result<()> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // We now have an instance ready to be used. // // Our module exports a single `add_one` function. We want to // measure the cost of executing this function. - let add_one: TypedFunction = - instance.exports.get_function("add_one")?.native(&mut ctx)?; + let add_one: TypedFunction = instance + .exports + .get_function("add_one")? + .native(&mut store)?; println!("Calling `add_one` function once..."); - add_one.call(&mut ctx, 1)?; + add_one.call(&mut store, 1)?; // As you can see here, after the first call we have 6 remaining points. // @@ -100,7 +102,7 @@ fn main() -> anyhow::Result<()> { // * `local.get $value` is a `Operator::LocalGet` which costs 1 point; // * `i32.const` is a `Operator::I32Const` which costs 1 point; // * `i32.add` is a `Operator::I32Add` which costs 2 points. - let remaining_points_after_first_call = get_remaining_points(&mut ctx, &instance); + let remaining_points_after_first_call = get_remaining_points(&mut store, &instance); assert_eq!( remaining_points_after_first_call, MeteringPoints::Remaining(6) @@ -112,11 +114,11 @@ fn main() -> anyhow::Result<()> { ); println!("Calling `add_one` function twice..."); - add_one.call(&mut ctx, 1)?; + add_one.call(&mut store, 1)?; // We spent 4 more points with the second call. // We have 2 remaining points. - let remaining_points_after_second_call = get_remaining_points(&mut ctx, &instance); + let remaining_points_after_second_call = get_remaining_points(&mut store, &instance); assert_eq!( remaining_points_after_second_call, MeteringPoints::Remaining(2) @@ -131,7 +133,7 @@ fn main() -> anyhow::Result<()> { // calling it a third time will fail: we already consume 8 // points, there are only two remaining. println!("Calling `add_one` function a third time..."); - match add_one.call(&mut ctx, 1) { + match add_one.call(&mut store, 1) { Ok(result) => { bail!( "Expected failure while calling `add_one`, found: {}", @@ -142,7 +144,7 @@ fn main() -> anyhow::Result<()> { println!("Calling `add_one` failed."); // Because the last needed more than the remaining points, we should have an error. - let remaining_points = get_remaining_points(&mut ctx, &instance); + let remaining_points = get_remaining_points(&mut store, &instance); match remaining_points { MeteringPoints::Remaining(..) => { @@ -156,9 +158,9 @@ fn main() -> anyhow::Result<()> { // Now let's see how we can set a new limit... println!("Set new remaining points to 10"); let new_limit = 10; - set_remaining_points(&mut ctx, &instance, new_limit); + set_remaining_points(&mut store, &instance, new_limit); - let remaining_points = get_remaining_points(&mut ctx, &instance); + let remaining_points = get_remaining_points(&mut store, &instance); assert_eq!(remaining_points, MeteringPoints::Remaining(new_limit)); println!("Remaining points: {:?}", remaining_points); diff --git a/examples/platform_ios_headless.rs b/examples/platform_ios_headless.rs index c7b67adfdd6..72ab854de77 100644 --- a/examples/platform_ios_headless.rs +++ b/examples/platform_ios_headless.rs @@ -53,7 +53,7 @@ fn main() -> Result<(), Box> { let engine = Dylib::new(compiler_config).target(target).engine(); // Create a store, that holds the engine. - let store = Store::new_with_engine(&engine); + let mut store = Store::new_with_engine(&engine); println!("Compiling module..."); // Let's compile the Wasm module. diff --git a/examples/table.rs b/examples/table.rs index 70e365a5069..2250ba1a194 100644 --- a/examples/table.rs +++ b/examples/table.rs @@ -1,12 +1,12 @@ use wasmer::{ - imports, wat2wasm, Context, ContextMut, Function, Instance, Module, Store, TableType, Type, - TypedFunction, Value, + imports, wat2wasm, Function, FunctionEnv, FunctionEnvMut, Instance, Module, Store, TableType, + Type, TypedFunction, Value, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; /// A function we'll call through a table. -fn host_callback(_ctx: ContextMut<()>, arg1: i32, arg2: i32) -> i32 { +fn host_callback(_ctx: FunctionEnvMut<()>, arg1: i32, arg2: i32) -> i32 { arg1 + arg2 } @@ -52,23 +52,23 @@ fn main() -> anyhow::Result<()> { )?; // We set up our store with an engine and a compiler. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut env = FunctionEnv::new(&mut store, ()); // Then compile our Wasm. let module = Module::new(&store, wasm_bytes)?; let import_object = imports! {}; // And instantiate it with no imports. - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // We get our function that calls (i32, i32) -> i32 functions via table. // The first argument is the table index and the next 2 are the 2 arguments // to be passed to the function found in the table. let call_via_table: TypedFunction<(i32, i32, i32), i32> = instance .exports - .get_typed_function(&mut ctx, "call_callback")?; + .get_typed_function(&mut store, "call_callback")?; // And then call it with table index 1 and arguments 2 and 7. - let result = call_via_table.call(&mut ctx, 1, 2, 7)?; + let result = call_via_table.call(&mut store, 1, 2, 7)?; // Because it's the default function, we expect it to double each number and // then sum it, giving us 18. assert_eq!(result, 18); @@ -76,9 +76,9 @@ fn main() -> anyhow::Result<()> { // We then get the table from the instance. let guest_table = instance.exports.get_table("__indirect_function_table")?; // And demonstrate that it has the properties that we set in the Wasm. - assert_eq!(guest_table.size(&mut ctx), 3); + assert_eq!(guest_table.size(&mut store), 3); assert_eq!( - guest_table.ty(&mut ctx), + guest_table.ty(&store), TableType { ty: Type::FuncRef, minimum: 3, @@ -89,30 +89,30 @@ fn main() -> anyhow::Result<()> { // == Setting elements in a table == // We first construct a `Function` over our host_callback. - let func = Function::new_native(&mut ctx, host_callback); + let func = Function::new_native(&mut store, &env, host_callback); // And set table index 1 of that table to the host_callback `Function`. - guest_table.set(&mut ctx, 1, func.into())?; + guest_table.set(&mut store, 1, func.into())?; // We then repeat the call from before but this time it will find the host function // that we put at table index 1. - let result = call_via_table.call(&mut ctx, 1, 2, 7)?; + let result = call_via_table.call(&mut store, 1, 2, 7)?; // And because our host function simply sums the numbers, we expect 9. assert_eq!(result, 9); // == Growing a table == // We again construct a `Function` over our host_callback. - let func = Function::new_native(&mut ctx, host_callback); + let func = Function::new_native(&mut store, &env, host_callback); // And grow the table by 3 elements, filling in our host_callback in all the // new elements of the table. - let previous_size = guest_table.grow(&mut ctx, 3, func.into())?; + let previous_size = guest_table.grow(&mut store, 3, func.into())?; assert_eq!(previous_size, 3); - assert_eq!(guest_table.size(&mut ctx), 6); + assert_eq!(guest_table.size(&mut store), 6); assert_eq!( - guest_table.ty(&mut ctx), + guest_table.ty(&store), TableType { ty: Type::FuncRef, minimum: 3, @@ -121,8 +121,8 @@ fn main() -> anyhow::Result<()> { ); // Now demonstrate that the function we grew the table with is actually in the table. for table_index in 3..6 { - if let Value::FuncRef(Some(f)) = guest_table.get(&mut ctx, table_index as _).unwrap() { - let result = f.call(&mut ctx, &[Value::I32(1), Value::I32(9)])?; + if let Value::FuncRef(Some(f)) = guest_table.get(&mut store, table_index as _).unwrap() { + let result = f.call(&mut store, &[Value::I32(1), Value::I32(9)])?; assert_eq!(result[0], Value::I32(10)); } else { panic!("expected to find funcref in table!"); @@ -130,26 +130,26 @@ fn main() -> anyhow::Result<()> { } // Call function at index 0 to show that it's still the same. - let result = call_via_table.call(&mut ctx, 0, 2, 7)?; + let result = call_via_table.call(&mut store, 0, 2, 7)?; assert_eq!(result, 18); // Now overwrite index 0 with our host_callback. - let func = Function::new_native(&mut ctx, host_callback); - guest_table.set(&mut ctx, 0, func.into())?; + let func = Function::new_native(&mut store, &env, host_callback); + guest_table.set(&mut store, 0, func.into())?; // And verify that it does what we expect. - let result = call_via_table.call(&mut ctx, 0, 2, 7)?; + let result = call_via_table.call(&mut store, 0, 2, 7)?; assert_eq!(result, 9); // Now demonstrate that the host and guest see the same table and that both // get the same result. for table_index in 3..6 { - if let Value::FuncRef(Some(f)) = guest_table.get(&mut ctx, table_index as _).unwrap() { - let result = f.call(&mut ctx, &[Value::I32(1), Value::I32(9)])?; + if let Value::FuncRef(Some(f)) = guest_table.get(&mut store, table_index as _).unwrap() { + let result = f.call(&mut store, &[Value::I32(1), Value::I32(9)])?; assert_eq!(result[0], Value::I32(10)); } else { panic!("expected to find funcref in table!"); } - let result = call_via_table.call(&mut ctx, table_index, 1, 9)?; + let result = call_via_table.call(&mut store, table_index, 1, 9)?; assert_eq!(result, 10); } diff --git a/examples/tunables_limit_memory.rs b/examples/tunables_limit_memory.rs index 9b4f4e1ebd7..10e7c25bd92 100644 --- a/examples/tunables_limit_memory.rs +++ b/examples/tunables_limit_memory.rs @@ -3,8 +3,8 @@ use std::ptr::NonNull; use wasmer::{ imports, vm::{self, MemoryError, MemoryStyle, TableStyle, VMMemoryDefinition, VMTableDefinition}, - wat2wasm, BaseTunables, Context, Instance, Memory, MemoryType, Module, Pages, Store, TableType, - Target, Tunables, + wat2wasm, BaseTunables, FunctionEnv, Instance, Memory, MemoryType, Module, Pages, Store, + TableType, Target, Tunables, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -145,8 +145,8 @@ fn main() -> Result<(), Box> { let tunables = LimitingTunables::new(base, Pages(24)); // Create a store, that holds the engine and our custom tunables - let store = Store::new_with_tunables(&engine, tunables); - let mut ctx = Context::new(&store, ()); + let mut store = Store::new_with_tunables(&engine, tunables); + let mut env = FunctionEnv::new(&mut store, ()); println!("Compiling module..."); let module = Module::new(&store, wasm_bytes)?; @@ -155,7 +155,7 @@ fn main() -> Result<(), Box> { let import_object = imports! {}; // Now at this point, our custom tunables are used - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; // Check what happened let mut memories: Vec = instance @@ -168,7 +168,7 @@ fn main() -> Result<(), Box> { let first_memory = memories.pop().unwrap(); println!("Memory of this instance: {:?}", first_memory); - assert_eq!(first_memory.ty(&mut ctx).maximum.unwrap(), Pages(24)); + assert_eq!(first_memory.ty(&store).maximum.unwrap(), Pages(24)); Ok(()) } diff --git a/examples/wasi.rs b/examples/wasi.rs index 2eb77075e55..0c47100c386 100644 --- a/examples/wasi.rs +++ b/examples/wasi.rs @@ -15,7 +15,7 @@ //! //! Ready? -use wasmer::{AsContextMut, Context, Instance, Module, Store}; +use wasmer::{FunctionEnv, Instance, Module, Store}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; use wasmer_wasi::WasiState; @@ -32,7 +32,7 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -43,25 +43,23 @@ fn main() -> Result<(), Box> { let mut wasi_env = WasiState::new("hello") // .args(&["world"]) // .env("KEY", "Value") - .finalize()?; - // And now the context,using the newly created WasiEnv - let mut ctx = Context::new(&store, wasi_env.clone()); + .finalize(&mut store)?; println!("Instantiating module with WASI imports..."); // Then, we get the import object related to our WASI // and attach it to the Wasm instance. - let import_object = wasi_env.import_object(&mut ctx.as_context_mut(), &module)?; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let import_object = wasi_env.import_object(&mut store, &module)?; + let instance = Instance::new(&mut store, &module, &import_object)?; println!("Attach WASI memory..."); // Attach the memory export let memory = instance.exports.get_memory("memory")?; - ctx.data_mut().set_memory(memory.clone()); + wasi_env.data_mut(&mut store).set_memory(memory.clone()); println!("Call WASI `_start` function..."); // And we just call the `_start` function! let start = instance.exports.get_function("_start")?; - start.call(&mut ctx, &[])?; + start.call(&mut store, &[])?; Ok(()) } diff --git a/examples/wasi_pipes.rs b/examples/wasi_pipes.rs index b5b8a750459..1c8a2536046 100644 --- a/examples/wasi_pipes.rs +++ b/examples/wasi_pipes.rs @@ -12,7 +12,7 @@ //! Ready? use std::io::{Read, Write}; -use wasmer::{AsContextMut, Context, Instance, Module, Store}; +use wasmer::{FunctionEnv, Instance, Module, Store}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; use wasmer_wasi::{Pipe, WasiState}; @@ -29,7 +29,7 @@ fn main() -> Result<(), Box> { // Note that we don't need to specify the engine/compiler if we want to use // the default provided by Wasmer. // You can use `Store::default()` for that. - let store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); + let mut store = Store::new_with_engine(&Universal::new(Cranelift::default()).engine()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -42,19 +42,18 @@ fn main() -> Result<(), Box> { let mut wasi_env = WasiState::new("hello") .stdin(Box::new(input.clone())) .stdout(Box::new(output.clone())) - .finalize()?; - let mut ctx = Context::new(&store, wasi_env.clone()); + .finalize(&mut store)?; println!("Instantiating module with WASI imports..."); // Then, we get the import object related to our WASI // and attach it to the Wasm instance. - let import_object = wasi_env.import_object(&mut ctx.as_context_mut(), &module)?; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let import_object = wasi_env.import_object(&mut store, &module)?; + let instance = Instance::new(&mut store, &module, &import_object)?; println!("Attach WASI memory..."); // Attach the memory export let memory = instance.exports.get_memory("memory")?; - ctx.data_mut().set_memory(memory.clone()); + wasi_env.data_mut(&mut store).set_memory(memory.clone()); let msg = "racecar go zoom"; println!("Writing \"{}\" to the WASI stdin...", msg); @@ -64,7 +63,7 @@ fn main() -> Result<(), Box> { println!("Call WASI `_start` function..."); // And we just call the `_start` function! let start = instance.exports.get_function("_start")?; - start.call(&mut ctx, &[])?; + start.call(&mut store, &[])?; println!("Reading from the WASI stdout..."); diff --git a/fuzz/fuzz_targets/deterministic.rs b/fuzz/fuzz_targets/deterministic.rs index ef550804599..b56da4d9006 100644 --- a/fuzz/fuzz_targets/deterministic.rs +++ b/fuzz/fuzz_targets/deterministic.rs @@ -24,7 +24,7 @@ impl Config for NoImportsConfig { } fn compile_and_compare(name: &str, engine: impl Engine, wasm: &[u8]) { - let store = Store::new_with_engine(&engine); + let mut store = Store::new_with_engine(&engine); // compile for first time let module = Module::new(&store, wasm).unwrap(); diff --git a/fuzz/fuzz_targets/equivalence_universal.rs b/fuzz/fuzz_targets/equivalence_universal.rs index 414f78adab2..be4edd3e463 100644 --- a/fuzz/fuzz_targets/equivalence_universal.rs +++ b/fuzz/fuzz_targets/equivalence_universal.rs @@ -48,7 +48,7 @@ impl std::fmt::Debug for WasmSmithModule { #[cfg(feature = "singlepass")] fn maybe_instantiate_singlepass(wasm_bytes: &[u8]) -> Result> { let compiler = Singlepass::default(); - let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); let module = Module::new(&store, &wasm_bytes); let module = match module { Ok(m) => m, @@ -69,7 +69,7 @@ fn maybe_instantiate_cranelift(wasm_bytes: &[u8]) -> Result> { let mut compiler = Cranelift::default(); compiler.canonicalize_nans(true); compiler.enable_verifier(); - let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); let module = Module::new(&store, &wasm_bytes)?; let instance = Instance::new(&module, &imports! {})?; Ok(Some(instance)) @@ -80,7 +80,7 @@ fn maybe_instantiate_llvm(wasm_bytes: &[u8]) -> Result> { let mut compiler = LLVM::default(); compiler.canonicalize_nans(true); compiler.enable_verifier(); - let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); let module = Module::new(&store, &wasm_bytes)?; let instance = Instance::new(&module, &imports! {})?; Ok(Some(instance)) diff --git a/fuzz/fuzz_targets/metering.rs b/fuzz/fuzz_targets/metering.rs index 4f53c207cee..cb91ee01874 100644 --- a/fuzz/fuzz_targets/metering.rs +++ b/fuzz/fuzz_targets/metering.rs @@ -56,7 +56,7 @@ fuzz_target!(|module: WasmSmithModule| { compiler.enable_verifier(); let metering = Arc::new(Metering::new(10, cost)); compiler.push_middleware(metering); - let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); let module = Module::new(&store, &wasm_bytes).unwrap(); match Instance::new(&module, &imports! {}) { Ok(_) => {} diff --git a/fuzz/fuzz_targets/universal_cranelift.rs b/fuzz/fuzz_targets/universal_cranelift.rs index a3642f55ed8..05fd7a3bcbc 100644 --- a/fuzz/fuzz_targets/universal_cranelift.rs +++ b/fuzz/fuzz_targets/universal_cranelift.rs @@ -42,7 +42,7 @@ fuzz_target!(|module: WasmSmithModule| { let mut compiler = Cranelift::default(); compiler.canonicalize_nans(true); compiler.enable_verifier(); - let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); let module = Module::new(&store, &wasm_bytes).unwrap(); match Instance::new(&module, &imports! {}) { Ok(_) => {} diff --git a/fuzz/fuzz_targets/universal_llvm.rs b/fuzz/fuzz_targets/universal_llvm.rs index 6b7d5fd127b..67cdc028894 100644 --- a/fuzz/fuzz_targets/universal_llvm.rs +++ b/fuzz/fuzz_targets/universal_llvm.rs @@ -42,7 +42,7 @@ fuzz_target!(|module: WasmSmithModule| { let mut compiler = LLVM::default(); compiler.canonicalize_nans(true); compiler.enable_verifier(); - let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); let module = Module::new(&store, &wasm_bytes).unwrap(); match Instance::new(&module, &imports! {}) { Ok(_) => {} diff --git a/fuzz/fuzz_targets/universal_singlepass.rs b/fuzz/fuzz_targets/universal_singlepass.rs index fe39c9d889c..e815bd1d797 100644 --- a/fuzz/fuzz_targets/universal_singlepass.rs +++ b/fuzz/fuzz_targets/universal_singlepass.rs @@ -40,7 +40,7 @@ fuzz_target!(|module: WasmSmithModule| { } let compiler = Singlepass::default(); - let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); let module = Module::new(&store, &wasm_bytes); let module = match module { Ok(m) => m, diff --git a/lib/api/Cargo.toml b/lib/api/Cargo.toml index 2ff837c00f9..db2916ebe03 100644 --- a/lib/api/Cargo.toml +++ b/lib/api/Cargo.toml @@ -41,6 +41,10 @@ target-lexicon = { version = "0.12.2", default-features = false } wasmer-compiler-singlepass = { path = "../compiler-singlepass", version = "=2.3.0", optional = true } wasmer-compiler-cranelift = { path = "../compiler-cranelift", version = "=2.3.0", optional = true } wasmer-compiler-llvm = { path = "../compiler-llvm", version = "=2.3.0", optional = true } + +wasm-bindgen = { version = "0.2.74", optional = true } +js-sys = { version = "0.3.51", optional = true } + # - Mandatory dependencies for `sys` on Windows. [target.'cfg(all(not(target_arch = "wasm32"), target_os = "windows"))'.dependencies] winapi = "0.3" @@ -79,6 +83,7 @@ maintenance = { status = "actively-developed" } [features] default = ["sys-default"] +# default = ["js-default"] std = [] core = ["hashbrown"] @@ -100,7 +105,7 @@ default-llvm = ["default-compiler", "llvm"] # - Engines. engine = ["sys"] universal = [ - "engine", + "engine", "wasmer-compiler/universal_engine" ] default-engine = [] default-universal = [ @@ -111,7 +116,7 @@ default-universal = [ jit = ["universal"] # Features for `js`. -js = [] +js = ["wasm-bindgen", "js-sys"] js-default = ["js", "std", "wasm-types-polyfill"] wasm-types-polyfill = ["js", "wasmparser"] diff --git a/lib/api/README.md b/lib/api/README.md index 07e476d9930..51b209344ad 100644 --- a/lib/api/README.md +++ b/lib/api/README.md @@ -25,7 +25,7 @@ fn main() -> anyhow::Result<()> { i32.add)) "#; - let store = Store::default(); + let mut store = Store::default(); let module = Module::new(&store, &module_wat)?; // The module doesn't import anything, so we create an empty import object. let import_object = imports! {}; diff --git a/lib/api/src/js/context.rs b/lib/api/src/js/context.rs deleted file mode 100644 index 9823abbe7cb..00000000000 --- a/lib/api/src/js/context.rs +++ /dev/null @@ -1,449 +0,0 @@ -#![allow(dead_code)] -use crate::Store; - -/// We require the context to have a fixed memory address for its lifetime since -/// various bits of the VM have raw pointers that point back to it. Hence we -/// wrap the actual context in a box. -pub(crate) struct ContextInner { - pub(crate) objects: ContextObjects, - pub(crate) store: Store, - pub(crate) data: T, -} - -/// A context containing a set of WebAssembly instances, along with host state. -/// -/// All WebAssembly instances must exist within a context. In the majority of -/// cases each instance will have its own context, but it is possible to have -/// multiple instances in a context when these instances need to interact with -/// each other, for example sharing a memory between instances or calling -/// functions in another instance. -/// -/// The lifetimes of run-time WebAssembly objects, notably [`Instance`], -/// [`Memory`], [`Global`], [`Table`] and [`Function`] is tied to a context: -/// the backing memory for these objects is only freed when the context is -/// freed. -/// -/// The `T` generic parameter allows arbitrary data to be attached to a context. -/// This data can be accessed using the [`Context::data`] and -/// [`Context::data_mut`] methods. Host functions defined using -/// [`Function::new`] and [`Function::new_native`] receive -/// a reference to the context when they are called. -pub struct Context { - pub(crate) inner: Box>, -} - -impl Context { - /// Creates a new context with the given host state. - // TODO: Eliminate the Store type and move its functionality into Engine. - pub fn new(store: &Store, data: T) -> Self { - Self { - inner: Box::new(ContextInner { - objects: Default::default(), - store: store.clone(), - data, - }), - } - } - - /// Returns a reference to the host state in this context. - pub fn data(&self) -> &T { - &self.inner.data - } - - /// Returns a mutable- reference to the host state in this context. - pub fn data_mut(&mut self) -> &mut T { - &mut self.inner.data - } - - /// Drops the context and returns the host state that was stored in it. - pub fn into_data(self) -> T { - self.inner.data - } - - /// Returns a reference to the `Store` of this context. - pub fn store(&self) -> &Store { - &self.inner.store - } -} - -/// A temporary handle to a [`Context`]. -pub struct ContextRef<'a, T: 'a> { - inner: &'a ContextInner, -} - -impl<'a, T> ContextRef<'a, T> { - /// Returns a reference to the host state in this context. - pub fn data(&self) -> &'a T { - &self.inner.data - } - - /// Returns a reference to the `Store` of this context. - pub fn store(&self) -> &Store { - &self.inner.store - } - - pub(crate) fn objects(&self) -> &'a ContextObjects { - &self.inner.objects - } -} - -/// A temporary handle to a [`Context`]. -pub struct ContextMut<'a, T: 'a> { - inner: &'a mut ContextInner, -} - -impl ContextMut<'_, T> { - /// Returns a reference to the host state in this context. - pub fn data(&self) -> &T { - &self.inner.data - } - - /// Returns a mutable- reference to the host state in this context. - pub fn data_mut(&mut self) -> &mut T { - &mut self.inner.data - } - - pub(crate) fn objects_mut(&mut self) -> &mut ContextObjects { - &mut self.inner.objects - } - - /// Returns a reference to the `Store` of this context. - pub fn store(&self) -> &Store { - &self.inner.store - } - - /// Returns the raw pointer of the context - pub(crate) fn as_raw(&self) -> *mut ContextInner { - self.inner as *const ContextInner as *mut ContextInner - } - - /// Constructs the context from the raw pointer - pub(crate) unsafe fn from_raw(raw: *mut ContextInner) -> Self { - Self { inner: &mut *raw } - } -} - -/// Helper trait for a value that is convertible to a [`ContextRef`]. -pub trait AsContextRef { - /// Host state associated with the [`Context`]. - type Data; - - /// Returns a `ContextRef` pointing to the underlying context. - fn as_context_ref(&self) -> ContextRef<'_, Self::Data>; -} - -/// Helper trait for a value that is convertible to a [`ContextMut`]. -pub trait AsContextMut: AsContextRef { - /// Returns a `ContextMut` pointing to the underlying context. - fn as_context_mut(&mut self) -> ContextMut<'_, Self::Data>; -} - -impl AsContextRef for Context { - type Data = T; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - ContextRef { inner: &self.inner } - } -} -impl AsContextMut for Context { - fn as_context_mut(&mut self) -> ContextMut<'_, Self::Data> { - ContextMut { - inner: &mut self.inner, - } - } -} -impl AsContextRef for ContextRef<'_, T> { - type Data = T; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - ContextRef { inner: self.inner } - } -} -impl AsContextRef for ContextMut<'_, T> { - type Data = T; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - ContextRef { inner: self.inner } - } -} -impl AsContextMut for ContextMut<'_, T> { - fn as_context_mut(&mut self) -> ContextMut<'_, Self::Data> { - ContextMut { inner: self.inner } - } -} -impl AsContextRef for &'_ T { - type Data = T::Data; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - T::as_context_ref(*self) - } -} -impl AsContextRef for &'_ mut T { - type Data = T::Data; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - T::as_context_ref(*self) - } -} -impl AsContextMut for &'_ mut T { - fn as_context_mut(&mut self) -> ContextMut<'_, Self::Data> { - T::as_context_mut(*self) - } -} - -pub use objects::*; -mod objects { - use crate::js::export::{VMFunction, VMGlobal, VMMemory, VMTable}; - use std::{ - cell::UnsafeCell, - fmt, - marker::PhantomData, - num::{NonZeroU64, NonZeroUsize}, - ptr::NonNull, - sync::atomic::{AtomicU64, Ordering}, - }; - - /// Unique ID to identify a context. - /// - /// Every handle to an object managed by a context also contains the ID of the - /// context. This is used to check that a handle is always used with the - /// correct context. - #[derive(Debug, Copy, Clone, Eq, PartialEq)] - pub struct ContextId(NonZeroU64); - - impl Default for ContextId { - // Allocates a unique ID for a new context. - fn default() -> Self { - // No overflow checking is needed here: overflowing this would take - // thousands of years. - static NEXT_ID: AtomicU64 = AtomicU64::new(1); - Self(NonZeroU64::new(NEXT_ID.fetch_add(1, Ordering::Relaxed)).unwrap()) - } - } - - /// Trait to represent an object managed by a context. This is implemented on - /// the VM types managed by the context. - pub trait ContextObject: Sized { - fn list(ctx: &ContextObjects) -> &Vec; - fn list_mut(ctx: &mut ContextObjects) -> &mut Vec; - } - - macro_rules! impl_context_object { - ($($field:ident => $ty:ty,)*) => { - $( - impl ContextObject for $ty { - fn list(ctx: &ContextObjects) -> &Vec { - &ctx.$field - } - fn list_mut(ctx: &mut ContextObjects) -> &mut Vec { - &mut ctx.$field - } - } - )* - }; -} - - impl_context_object! { - functions => VMFunction, - tables => VMTable, - globals => VMGlobal, - memories => VMMemory, - instances => js_sys::WebAssembly::Instance, - } - - /// Set of objects managed by a context. - #[derive(Default)] - pub struct ContextObjects { - id: ContextId, - memories: Vec, - tables: Vec, - globals: Vec, - functions: Vec, - instances: Vec, - } - - impl ContextObjects { - /// Returns the ID of this context. - pub fn id(&self) -> ContextId { - self.id - } - - /// Returns a pair of mutable references from two handles. - /// - /// Panics if both handles point to the same object. - pub fn get_2_mut( - &mut self, - a: InternalContextHandle, - b: InternalContextHandle, - ) -> (&mut T, &mut T) { - assert_ne!(a.index(), b.index()); - let list = T::list_mut(self); - if a.index() < b.index() { - let (low, high) = list.split_at_mut(b.index()); - (&mut low[a.index()], &mut high[0]) - } else { - let (low, high) = list.split_at_mut(a.index()); - (&mut high[0], &mut low[a.index()]) - } - } - } - - /// Handle to an object managed by a context. - /// - /// Internally this is just an integer index into a context. A reference to the - /// context must be passed in separately to access the actual object. - pub struct ContextHandle { - id: ContextId, - internal: InternalContextHandle, - } - - impl core::cmp::PartialEq for ContextHandle { - fn eq(&self, other: &Self) -> bool { - self.id == other.id - } - } - impl Clone for ContextHandle { - fn clone(&self) -> Self { - Self { - id: self.id, - internal: self.internal, - } - } - } - - impl fmt::Debug for ContextHandle { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ContextHandle") - .field("id", &self.id) - .field("internal", &self.internal.index()) - .finish() - } - } - - impl ContextHandle { - /// Moves the given object into a context and returns a handle to it. - pub fn new(ctx: &mut ContextObjects, val: T) -> Self { - Self { - id: ctx.id, - internal: InternalContextHandle::new(ctx, val), - } - } - - /// Returns a reference to the object that this handle points to. - pub fn get<'a>(&self, ctx: &'a ContextObjects) -> &'a T { - assert_eq!(self.id, ctx.id, "object used with the wrong context"); - self.internal.get(ctx) - } - - /// Returns a mutable reference to the object that this handle points to. - pub fn get_mut<'a>(&self, ctx: &'a mut ContextObjects) -> &'a mut T { - assert_eq!(self.id, ctx.id, "object used with the wrong context"); - self.internal.get_mut(ctx) - } - - /// Returns the internal handle contains within this handle. - pub fn internal_handle(&self) -> InternalContextHandle { - self.internal - } - - /// Returns the ID of the context associated with the handle. - pub fn context_id(&self) -> ContextId { - self.id - } - - /// Constructs a `ContextHandle` from a `ContextId` and an `InternalContextHandle`. - /// - /// # Safety - /// Handling `InternalContextHandle` values is unsafe because they do not track context ID. - pub unsafe fn from_internal(id: ContextId, internal: InternalContextHandle) -> Self { - Self { id, internal } - } - } - - /// Internal handle to an object owned by the current context. - /// - /// Unlike `ContextHandle` this does not track the context ID: it is only - /// intended to be used within objects already owned by a context. - #[repr(transparent)] - pub struct InternalContextHandle { - // Use a NonZero here to reduce the size of Option. - idx: NonZeroUsize, - marker: PhantomData T>, - } - - impl Clone for InternalContextHandle { - fn clone(&self) -> Self { - *self - } - } - impl Copy for InternalContextHandle {} - - impl fmt::Debug for InternalContextHandle { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("InternalContextHandle") - .field("idx", &self.idx) - .finish() - } - } - impl PartialEq for InternalContextHandle { - fn eq(&self, other: &Self) -> bool { - self.idx == other.idx - } - } - impl Eq for InternalContextHandle {} - - impl InternalContextHandle { - /// Moves the given object into a context and returns a handle to it. - pub fn new(ctx: &mut ContextObjects, val: T) -> Self { - let list = T::list_mut(ctx); - let idx = NonZeroUsize::new(list.len() + 1).unwrap(); - list.push(val); - Self { - idx, - marker: PhantomData, - } - } - - /// Returns a reference to the object that this handle points to. - pub fn get<'a>(&self, ctx: &'a ContextObjects) -> &'a T { - &T::list(ctx)[self.idx.get() - 1] - } - - /// Returns a mutable reference to the object that this handle points to. - pub fn get_mut<'a>(&self, ctx: &'a mut ContextObjects) -> &'a mut T { - &mut T::list_mut(ctx)[self.idx.get() - 1] - } - - pub(crate) fn index(&self) -> usize { - self.idx.get() - } - - pub(crate) fn from_index(idx: usize) -> Option { - NonZeroUsize::new(idx).map(|idx| Self { - idx, - marker: PhantomData, - }) - } - } - - /// Data used by the generated code is generally located inline within the - /// `VMContext` for items defined in an instance. Host-defined objects are - /// allocated separately and owned directly by the context. - pub enum MaybeInstanceOwned { - /// The data is owned here. - Host(Box>), - - /// The data is stored inline in the `VMContext` of an instance. - Instance(NonNull), - } - - impl MaybeInstanceOwned { - /// Returns underlying pointer to the VM data. - pub fn as_ptr(&self) -> NonNull { - match self { - MaybeInstanceOwned::Host(p) => unsafe { NonNull::new_unchecked(p.get()) }, - MaybeInstanceOwned::Instance(p) => *p, - } - } - } -} diff --git a/lib/api/src/js/error.rs b/lib/api/src/js/error.rs index 5a25c99d88e..f334b4a1cec 100644 --- a/lib/api/src/js/error.rs +++ b/lib/api/src/js/error.rs @@ -163,10 +163,10 @@ pub enum InstantiationError { #[cfg_attr(feature = "std", error(transparent))] Start(RuntimeError), - /// Import from a different [`Context`]. - /// This error occurs when an import from a different context is used. - #[cfg_attr(feature = "std", error("cannot mix imports from different contexts"))] - BadContext, + /// Import from a different [`Store`]. + /// This error occurs when an import from a different store is used. + #[cfg_attr(feature = "std", error("cannot mix imports from different stores"))] + DifferentStores, /// A generic error occured while invoking API functions #[cfg_attr(feature = "std", error(transparent))] diff --git a/lib/api/src/js/export.rs b/lib/api/src/js/export.rs index 41d72145d01..4899443ce4d 100644 --- a/lib/api/src/js/export.rs +++ b/lib/api/src/js/export.rs @@ -1,5 +1,5 @@ -use crate::js::context::{AsContextMut, AsContextRef, InternalContextHandle}; use crate::js::error::WasmError; +use crate::js::store::{AsStoreMut, AsStoreRef, InternalStoreHandle}; use crate::js::wasm_bindgen_polyfill::Global; use js_sys::Function; use js_sys::WebAssembly::{Memory, Table}; @@ -85,36 +85,33 @@ impl fmt::Debug for VMFunction { #[derive(Debug, Clone)] pub enum Export { /// A function export value. - Function(InternalContextHandle), + Function(InternalStoreHandle), /// A table export value. - Table(InternalContextHandle), + Table(InternalStoreHandle), /// A memory export value. - Memory(InternalContextHandle), + Memory(InternalStoreHandle), /// A global export value. - Global(InternalContextHandle), + Global(InternalStoreHandle), } impl Export { /// Return the export as a `JSValue`. - pub fn as_jsvalue<'context>(&self, ctx: &'context impl AsContextRef) -> &'context JsValue { + pub fn as_jsvalue<'context>(&self, ctx: &'context impl AsStoreRef) -> &'context JsValue { match self { Self::Memory(js_wasm_memory) => js_wasm_memory - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .memory .as_ref(), - Self::Function(js_func) => js_func - .get(ctx.as_context_ref().objects()) - .function - .as_ref(), + Self::Function(js_func) => js_func.get(ctx.as_store_ref().objects()).function.as_ref(), Self::Table(js_wasm_table) => js_wasm_table - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .table .as_ref(), Self::Global(js_wasm_global) => js_wasm_global - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .global .as_ref(), } @@ -123,14 +120,14 @@ impl Export { /// Convert a `JsValue` into an `Export` within a given `Context`. pub fn from_js_value( val: JsValue, - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, extern_type: ExternType, ) -> Result { match extern_type { ExternType::Memory(memory_type) => { if val.is_instance_of::() { - Ok(Self::Memory(InternalContextHandle::new( - &mut ctx.as_context_mut().objects_mut(), + Ok(Self::Memory(InternalStoreHandle::new( + &mut ctx.objects_mut(), VMMemory::new(val.unchecked_into::(), memory_type), ))) } else { @@ -145,8 +142,8 @@ impl Export { } ExternType::Global(global_type) => { if val.is_instance_of::() { - Ok(Self::Global(InternalContextHandle::new( - &mut ctx.as_context_mut().objects_mut(), + Ok(Self::Global(InternalStoreHandle::new( + &mut ctx.objects_mut(), VMGlobal::new(val.unchecked_into::(), global_type), ))) } else { @@ -155,8 +152,8 @@ impl Export { } ExternType::Function(function_type) => { if val.is_instance_of::() { - Ok(Self::Function(InternalContextHandle::new( - &mut ctx.as_context_mut().objects_mut(), + Ok(Self::Function(InternalStoreHandle::new( + &mut ctx.objects_mut(), VMFunction::new(val.unchecked_into::(), function_type), ))) } else { @@ -165,8 +162,8 @@ impl Export { } ExternType::Table(table_type) => { if val.is_instance_of::
() { - Ok(Self::Table(InternalContextHandle::new( - &mut ctx.as_context_mut().objects_mut(), + Ok(Self::Table(InternalStoreHandle::new( + &mut ctx.objects_mut(), VMTable::new(val.unchecked_into::
(), table_type), ))) } else { diff --git a/lib/api/src/js/exports.rs b/lib/api/src/js/exports.rs index c25e947eb91..90b5116729b 100644 --- a/lib/api/src/js/exports.rs +++ b/lib/api/src/js/exports.rs @@ -1,6 +1,6 @@ -use crate::js::context::AsContextRef; use crate::js::externals::{Extern, Function, Global, Memory, Table}; use crate::js::native::TypedFunction; +use crate::js::store::AsStoreRef; use crate::js::WasmTypeList; use indexmap::IndexMap; use std::fmt; @@ -18,7 +18,7 @@ use thiserror::Error; /// /// ```should_panic /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError}; -/// # let store = Store::default(); +/// # let mut store = Store::default(); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (global $one (export "glob") f32 (f32.const 1))) @@ -35,7 +35,7 @@ use thiserror::Error; /// /// ```should_panic /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError}; -/// # let store = Store::default(); +/// # let mut store = Store::default(); /// # let wasm_bytes = wat2wasm("(module)".as_bytes()).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let import_object = imports! {}; @@ -141,7 +141,7 @@ impl Exports { /// Get an export as a `TypedFunction`. pub fn get_native_function( &self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, name: &str, ) -> Result, ExportError> where @@ -154,7 +154,7 @@ impl Exports { /// Get an export as a `TypedFunction`. pub fn get_typed_function( &self, - ctx: &impl AsContextRef, + store: &impl AsStoreRef, name: &str, ) -> Result, ExportError> where @@ -162,14 +162,14 @@ impl Exports { Rets: WasmTypeList, { self.get_function(name)? - .native(ctx) + .native(store) .map_err(|_| ExportError::IncompatibleType) } /// Hack to get this working with nativefunc too pub fn get_with_generics<'a, T, Args, Rets>( &'a self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, name: &str, ) -> Result where @@ -187,7 +187,7 @@ impl Exports { /// This is useful for passing data into Context data, for example. pub fn get_with_generics_weak<'a, T, Args, Rets>( &'a self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, name: &str, ) -> Result where @@ -334,7 +334,7 @@ pub trait Exportable<'a>: Sized { pub trait ExportableWithGenerics<'a, Args: WasmTypeList, Rets: WasmTypeList>: Sized { /// Get an export with the given generics. fn get_self_from_extern_with_generics( - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, _extern: &'a Extern, ) -> Result; } @@ -343,7 +343,7 @@ pub trait ExportableWithGenerics<'a, Args: WasmTypeList, Rets: WasmTypeList>: Si /// with empty `Args` and `Rets`. impl<'a, T: Exportable<'a> + Clone + 'static> ExportableWithGenerics<'a, (), ()> for T { fn get_self_from_extern_with_generics( - _ctx: &impl AsContextRef, + _ctx: &impl AsStoreRef, _extern: &'a Extern, ) -> Result { T::get_self_from_extern(_extern).map(|i| i.clone()) diff --git a/lib/api/src/js/externals/function.rs b/lib/api/src/js/externals/function.rs index 17d6cd56b7a..232f1ad1bb8 100644 --- a/lib/api/src/js/externals/function.rs +++ b/lib/api/src/js/externals/function.rs @@ -1,14 +1,13 @@ pub use self::inner::{FromToNativeWasmType, HostFunction, WasmTypeList}; -use crate::js::context::{ - AsContextMut, AsContextRef, ContextHandle, ContextMut, InternalContextHandle, -}; use crate::js::exports::{ExportError, Exportable}; use crate::js::externals::Extern; +use crate::js::function_env::FunctionEnvMut; +use crate::js::store::{AsStoreMut, AsStoreRef, InternalStoreHandle, StoreHandle, StoreMut}; use crate::js::types::{param_from_js, AsJs}; /* ValFuncRef */ -use crate::js::FunctionType; use crate::js::RuntimeError; use crate::js::TypedFunction; use crate::js::Value; +use crate::js::{FunctionEnv, FunctionType}; use js_sys::{Array, Function as JSFunction}; use std::iter::FromIterator; use wasm_bindgen::prelude::*; @@ -58,7 +57,7 @@ fn results_to_js_array(values: &[Value]) -> Array { /// [Closures as host functions tracking issue](https://github.com/wasmerio/wasmer/issues/1840) #[derive(Clone, PartialEq)] pub struct Function { - pub(crate) handle: ContextHandle, + pub(crate) handle: StoreHandle, } impl Function { @@ -71,7 +70,7 @@ impl Function { /// /// ``` /// # use wasmer::{Function, FunctionType, Type, Store, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]); /// @@ -85,7 +84,7 @@ impl Function { /// /// ``` /// # use wasmer::{Function, FunctionType, Type, Store, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]); /// @@ -95,55 +94,63 @@ impl Function { /// }); /// ``` #[allow(clippy::cast_ptr_alignment)] - pub fn new(ctx: &mut impl AsContextMut, ty: FT, func: F) -> Self + pub fn new( + store: &mut impl AsStoreMut, + ctx: &FunctionEnv, + ty: FT, + func: F, + ) -> Self where FT: Into, - F: Fn(ContextMut<'_, T>, &[Value]) -> Result, RuntimeError> + F: Fn(FunctionEnvMut<'_, T>, &[Value]) -> Result, RuntimeError> + 'static + Send + Sync, { - let mut ctx = ctx.as_context_mut(); + let mut store = store.as_store_mut(); let function_type = ty.into(); let func_ty = function_type.clone(); - let raw_ctx = ctx.as_raw() as *mut u8; - + let raw_store = store.as_raw() as *mut u8; + let raw_ctx = ctx.clone(); let wrapped_func: JsValue = match function_type.results().len() { 0 => Closure::wrap(Box::new(move |args: &Array| { - let mut ctx: ContextMut = unsafe { ContextMut::from_raw(raw_ctx as _) }; + let mut store: StoreMut = unsafe { StoreMut::from_raw(raw_store as _) }; + let mut ctx: FunctionEnvMut = raw_ctx.clone().into_mut(&mut store); let wasm_arguments = function_type .params() .iter() .enumerate() .map(|(i, param)| param_from_js(param, &args.get(i as u32))) .collect::>(); - let _results = func(ctx.as_context_mut(), &wasm_arguments)?; + let _results = func(ctx, &wasm_arguments)?; Ok(()) }) as Box Result<(), JsValue>>) .into_js_value(), 1 => Closure::wrap(Box::new(move |args: &Array| { - let mut ctx: ContextMut = unsafe { ContextMut::from_raw(raw_ctx as _) }; + let mut store: StoreMut = unsafe { StoreMut::from_raw(raw_store as _) }; + let mut ctx: FunctionEnvMut = raw_ctx.clone().into_mut(&mut store); let wasm_arguments = function_type .params() .iter() .enumerate() .map(|(i, param)| param_from_js(param, &args.get(i as u32))) .collect::>(); - let results = func(ctx.as_context_mut(), &wasm_arguments)?; + let results = func(ctx, &wasm_arguments)?; return Ok(result_to_js(&results[0])); }) as Box Result>) .into_js_value(), _n => Closure::wrap(Box::new(move |args: &Array| { - let mut ctx: ContextMut = unsafe { ContextMut::from_raw(raw_ctx as _) }; + let mut store: StoreMut = unsafe { StoreMut::from_raw(raw_store as _) }; + let mut ctx: FunctionEnvMut = raw_ctx.clone().into_mut(&mut store); let wasm_arguments = function_type .params() .iter() .enumerate() .map(|(i, param)| param_from_js(param, &args.get(i as u32))) .collect::>(); - let results = func(ctx.as_context_mut(), &wasm_arguments)?; + let results = func(ctx, &wasm_arguments)?; return Ok(results_to_js_array(&results)); }) as Box Result>) @@ -154,7 +161,7 @@ impl Function { JSFunction::new_with_args("f", "return f(Array.prototype.slice.call(arguments, 1))"); let binded_func = dyn_func.bind1(&JsValue::UNDEFINED, &wrapped_func); let vm_function = VMFunction::new(binded_func, func_ty); - Self::from_vm_export(&mut ctx, vm_function) + Self::from_vm_export(&mut store, vm_function) } /// Creates a new host `Function` from a native function. @@ -166,7 +173,7 @@ impl Function { /// /// ``` /// # use wasmer::{Store, Function}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// fn sum(a: i32, b: i32) -> i32 { /// a + b @@ -174,13 +181,17 @@ impl Function { /// /// let f = Function::new_native(&store, sum); /// ``` - pub fn new_native(ctx: &mut impl AsContextMut, func: F) -> Self + pub fn new_native( + store: &mut impl AsStoreMut, + env: &FunctionEnv, + func: F, + ) -> Self where F: HostFunction, Args: WasmTypeList, Rets: WasmTypeList, { - let mut ctx = ctx.as_context_mut(); + let mut store = store.as_store_mut(); if std::mem::size_of::() != 0 { Self::closures_unsupported_panic(); } @@ -191,14 +202,15 @@ impl Function { let as_table = ft.unchecked_ref::(); let func = as_table.get(address).unwrap(); - let binded_func = func.bind1( + let binded_func = func.bind2( &JsValue::UNDEFINED, - &JsValue::from_f64(ctx.as_raw() as *mut u8 as usize as f64), + &JsValue::from_f64(store.as_raw() as *mut u8 as usize as f64), + &JsValue::from_f64(env.handle.internal_handle().index() as f64), ); let ty = function.ty(); let vm_function = VMFunction::new(binded_func, ty); Self { - handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_function), + handle: StoreHandle::new(store.objects_mut(), vm_function), } } @@ -208,7 +220,7 @@ impl Function { /// /// ``` /// # use wasmer::{Function, Store, Type}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// fn sum(a: i32, b: i32) -> i32 { /// a + b @@ -219,8 +231,8 @@ impl Function { /// assert_eq!(f.ty().params(), vec![Type::I32, Type::I32]); /// assert_eq!(f.ty().results(), vec![Type::I32]); /// ``` - pub fn ty<'context>(&self, ctx: &'context impl AsContextRef) -> &'context FunctionType { - &self.handle.get(ctx.as_context_ref().objects()).ty + pub fn ty<'context>(&self, ctx: &'context impl AsStoreRef) -> &'context FunctionType { + &self.handle.get(ctx.as_store_ref().objects()).ty } /// Returns the number of parameters that this function takes. @@ -228,18 +240,19 @@ impl Function { /// # Example /// /// ``` - /// # use wasmer::{Function, Store, Type}; - /// # let store = Store::default(); + /// # use wasmer::{Function, FunctionEnv, FunctionEnvMut, Store, Type}; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # - /// fn sum(a: i32, b: i32) -> i32 { + /// fn sum(_ctx: FunctionEnvMut<()>, a: i32, b: i32) -> i32 { /// a + b /// } /// - /// let f = Function::new_native(&store, sum); + /// let f = Function::new_native(&store, &env, sum); /// - /// assert_eq!(f.param_arity(), 2); + /// assert_eq!(f.param_arity(&store), 2); /// ``` - pub fn param_arity(&self, ctx: &impl AsContextRef) -> usize { + pub fn param_arity(&self, ctx: &impl AsStoreRef) -> usize { self.ty(ctx).params().len() } @@ -248,18 +261,19 @@ impl Function { /// # Example /// /// ``` - /// # use wasmer::{Function, Store, Type}; - /// # let store = Store::default(); + /// # use wasmer::{Function, FunctionEnv, FunctionEnvMut, Store, Type}; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # - /// fn sum(a: i32, b: i32) -> i32 { + /// fn sum(_ctx: FunctionEnvMut<()>, a: i32, b: i32) -> i32 { /// a + b /// } /// - /// let f = Function::new_native(&store, sum); + /// let f = Function::new_native(&store, &env, sum); /// - /// assert_eq!(f.result_arity(), 1); + /// assert_eq!(f.result_arity(&store), 1); /// ``` - pub fn result_arity(&self, ctx: &impl AsContextRef) -> usize { + pub fn result_arity(&self, ctx: &impl AsStoreRef) -> usize { self.ty(ctx).results().len() } @@ -275,7 +289,7 @@ impl Function { /// /// ``` /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) @@ -292,27 +306,27 @@ impl Function { /// /// assert_eq!(sum.call(&[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]); /// ``` - pub fn call( + pub fn call( &self, - ctx: &mut impl AsContextMut, + store: &mut impl AsStoreMut, params: &[Value], ) -> Result, RuntimeError> { let arr = js_sys::Array::new_with_length(params.len() as u32); - // let raw_ctx = ctx.as_context_mut().as_raw() as *mut u8; - // let mut ctx = unsafe { ContextMut::from_raw(raw_ctx as *mut ContextInner<()>) }; + // let raw_ctx = ctx.as_raw() as *mut u8; + // let mut env = unsafe { FunctionEnvMut::from_raw(raw_ctx as *mut StoreInner<()>) }; for (i, param) in params.iter().enumerate() { - let js_value = param.as_jsvalue(&ctx.as_context_ref()); + let js_value = param.as_jsvalue(&store.as_store_ref()); arr.set(i as u32, js_value); } let result = js_sys::Reflect::apply( - &self.handle.get(ctx.as_context_ref().objects()).function, + &self.handle.get(store.as_store_ref().objects()).function, &wasm_bindgen::JsValue::NULL, &arr, )?; - let result_types = self.handle.get(ctx.as_context_ref().objects()).ty.results(); + let result_types = self.handle.get(store.as_store_ref().objects()).ty.results(); match result_types.len() { 0 => Ok(Box::new([])), 1 => { @@ -331,19 +345,19 @@ impl Function { } } - pub(crate) fn from_vm_export(ctx: &mut impl AsContextMut, vm_function: VMFunction) -> Self { + pub(crate) fn from_vm_export(ctx: &mut impl AsStoreMut, vm_function: VMFunction) -> Self { Self { - handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_function), + handle: StoreHandle::new(ctx.objects_mut(), vm_function), } } pub(crate) fn from_vm_extern( - ctx: &mut impl AsContextMut, - internal: InternalContextHandle, + ctx: &mut impl AsStoreMut, + internal: InternalStoreHandle, ) -> Self { Self { handle: unsafe { - ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal) + StoreHandle::from_internal(ctx.as_store_ref().objects().id(), internal) }, } } @@ -355,7 +369,7 @@ impl Function { /// /// ``` /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) @@ -371,7 +385,7 @@ impl Function { /// let sum = instance.exports.get_function("sum").unwrap(); /// let sum_native = sum.native::<(i32, i32), i32>().unwrap(); /// - /// assert_eq!(sum_native.call(1, 2).unwrap(), 3); + /// assert_eq!(sum_native.call(&mut store, 1, 2).unwrap(), 3); /// ``` /// /// # Errors @@ -381,7 +395,7 @@ impl Function { /// /// ```should_panic /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) @@ -397,7 +411,7 @@ impl Function { /// let sum = instance.exports.get_function("sum").unwrap(); /// /// // This results in an error: `RuntimeError` - /// let sum_native = sum.native::<(i64, i64), i32>().unwrap(); + /// let sum_native = sum.native::<(i64, i64), i32>(&mut store).unwrap(); /// ``` /// /// If the `Rets` generic parameter does not match the exported function @@ -405,7 +419,7 @@ impl Function { /// /// ```should_panic /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) @@ -421,17 +435,17 @@ impl Function { /// let sum = instance.exports.get_function("sum").unwrap(); /// /// // This results in an error: `RuntimeError` - /// let sum_native = sum.native::<(i32, i32), i64>().unwrap(); + /// let sum_native = sum.native::<(i32, i32), i64>(&mut store).unwrap(); /// ``` pub fn native( &self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, ) -> Result, RuntimeError> where Args: WasmTypeList, Rets: WasmTypeList, { - let vm_function = self.handle.get(ctx.as_context_ref().objects()); + let vm_function = self.handle.get(ctx.as_store_ref().objects()); // type check { @@ -470,8 +484,8 @@ impl Function { } /// Checks whether this `Function` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { + self.handle.store_id() == ctx.as_store_ref().objects().id() } } @@ -495,7 +509,9 @@ impl fmt::Debug for Function { mod inner { use super::RuntimeError; use super::VMFunctionBody; - use crate::js::context::{AsContextMut, ContextInner, ContextMut}; + use crate::js::function_env::{FunctionEnvMut, VMFunctionEnvironment}; + use crate::js::store::{AsStoreMut, InternalStoreHandle, StoreHandle, StoreInner, StoreMut}; + use crate::js::FunctionEnv; use crate::js::NativeWasmTypeInto; use std::array::TryFromSliceError; use std::convert::{Infallible, TryInto}; @@ -641,7 +657,7 @@ mod inner { /// Constructs `Self` based on an array of values. /// /// # Safety - unsafe fn from_array(ctx: &mut impl AsContextMut, array: Self::Array) -> Self; + unsafe fn from_array(ctx: &mut impl AsStoreMut, array: Self::Array) -> Self; /// Constructs `Self` based on a slice of values. /// @@ -652,7 +668,7 @@ mod inner { /// /// # Safety unsafe fn from_slice( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, slice: &[f64], ) -> Result; @@ -660,7 +676,7 @@ mod inner { /// (list) of values. /// /// # Safety - unsafe fn into_array(self, ctx: &mut impl AsContextMut) -> Self::Array; + unsafe fn into_array(self, ctx: &mut impl AsStoreMut) -> Self::Array; /// Allocates and return an empty array of type `Array` that /// will hold a tuple (list) of values, usually to hold the @@ -671,13 +687,13 @@ mod inner { /// `CStruct`. /// /// # Safety - unsafe fn from_c_struct(ctx: &mut impl AsContextMut, c_struct: Self::CStruct) -> Self; + unsafe fn from_c_struct(ctx: &mut impl AsStoreMut, c_struct: Self::CStruct) -> Self; /// Builds and returns a C struct of type `CStruct` from a /// tuple (list) of values. /// /// # Safety - unsafe fn into_c_struct(self, ctx: &mut impl AsContextMut) -> Self::CStruct; + unsafe fn into_c_struct(self, ctx: &mut impl AsStoreMut) -> Self::CStruct; /// Writes the contents of a C struct to an array of `f64`. /// @@ -863,7 +879,7 @@ mod inner { #[allow(unused_mut)] #[allow(clippy::unused_unit)] #[allow(clippy::missing_safety_doc)] - unsafe fn from_array(mut _ctx: &mut impl AsContextMut, array: Self::Array) -> Self { + unsafe fn from_array(mut _ctx: &mut impl AsStoreMut, array: Self::Array) -> Self { // Unpack items of the array. #[allow(non_snake_case)] let [ $( $x ),* ] = array; @@ -877,13 +893,13 @@ mod inner { } #[allow(clippy::missing_safety_doc)] - unsafe fn from_slice(ctx: &mut impl AsContextMut, slice: &[f64]) -> Result { + unsafe fn from_slice(ctx: &mut impl AsStoreMut, slice: &[f64]) -> Result { Ok(Self::from_array(ctx, slice.try_into()?)) } #[allow(unused_mut)] #[allow(clippy::missing_safety_doc)] - unsafe fn into_array(self, mut _ctx: &mut impl AsContextMut) -> Self::Array { + unsafe fn into_array(self, mut _ctx: &mut impl AsStoreMut) -> Self::Array { // Unpack items of the tuple. #[allow(non_snake_case)] let ( $( $x ),* ) = self; @@ -904,7 +920,7 @@ mod inner { #[allow(unused_mut)] #[allow(clippy::unused_unit)] #[allow(clippy::missing_safety_doc)] - unsafe fn from_c_struct(mut _ctx: &mut impl AsContextMut, c_struct: Self::CStruct) -> Self { + unsafe fn from_c_struct(mut _ctx: &mut impl AsStoreMut, c_struct: Self::CStruct) -> Self { // Unpack items of the C structure. #[allow(non_snake_case)] let $c_struct_name( $( $x ),* ) = c_struct; @@ -918,7 +934,7 @@ mod inner { #[allow(unused_parens, non_snake_case, unused_mut)] #[allow(clippy::missing_safety_doc)] - unsafe fn into_c_struct(self, mut _ctx: &mut impl AsContextMut) -> Self::CStruct { + unsafe fn into_c_struct(self, mut _ctx: &mut impl AsStoreMut) -> Self::CStruct { // Unpack items of the tuple. let ( $( $x ),* ) = self; @@ -961,30 +977,35 @@ mod inner { $( $x: FromToNativeWasmType, )* Rets: WasmTypeList, RetsAsResult: IntoResult, - Func: Fn(ContextMut<'_, T>, $( $x , )*) -> RetsAsResult + 'static, + T: Send + 'static, + Func: Fn(FunctionEnvMut<'_, T>, $( $x , )*) -> RetsAsResult + 'static, { #[allow(non_snake_case)] fn function_body_ptr(self) -> *const VMFunctionBody { /// This is a function that wraps the real host /// function. Its address will be used inside the /// runtime. - unsafe extern "C" fn func_wrapper( ctx_ptr: usize, $( $x: <$x::Native as NativeWasmType>::Abi, )* ) -> Rets::CStruct + unsafe extern "C" fn func_wrapper( store_ptr: usize, handle_index: usize, $( $x: <$x::Native as NativeWasmType>::Abi, )* ) -> Rets::CStruct where $( $x: FromToNativeWasmType, )* Rets: WasmTypeList, RetsAsResult: IntoResult, - Func: Fn(ContextMut<'_, T>, $( $x , )*) -> RetsAsResult + 'static, + T: Send + 'static, + Func: Fn(FunctionEnvMut<'_, T>, $( $x , )*) -> RetsAsResult + 'static, { + // let env: &Env = unsafe { &*(ptr as *const u8 as *const Env) }; let func: &Func = &*(&() as *const () as *const Func); - let mut ctx = ContextMut::from_raw(ctx_ptr as *mut ContextInner); - let mut ctx2 = ContextMut::from_raw(ctx_ptr as *mut ContextInner); + let mut store = StoreMut::from_raw(store_ptr as *mut _); + let mut store2 = StoreMut::from_raw(store_ptr as *mut _); let result = panic::catch_unwind(AssertUnwindSafe(|| { - func(ctx2.as_context_mut(), $( FromToNativeWasmType::from_native(NativeWasmTypeInto::from_abi(&mut ctx, $x)) ),* ).into_result() + let handle: StoreHandle = StoreHandle::from_internal(store2.objects_mut().id(), InternalStoreHandle::from_index(handle_index).unwrap()); + let ctx: FunctionEnvMut = FunctionEnv::from_handle(handle).into_mut(&mut store2); + func(ctx, $( FromToNativeWasmType::from_native(NativeWasmTypeInto::from_abi(&mut store, $x)) ),* ).into_result() })); match result { - Ok(Ok(result)) => return result.into_c_struct(&mut ctx), + Ok(Ok(result)) => return result.into_c_struct(&mut store), #[allow(deprecated)] Ok(Err(trap)) => RuntimeError::raise(Box::new(trap)), Err(_panic) => unimplemented!(), @@ -1051,18 +1072,18 @@ mod inner { 0 } - unsafe fn from_array(_: &mut impl AsContextMut, _: Self::Array) -> Self { + unsafe fn from_array(_: &mut impl AsStoreMut, _: Self::Array) -> Self { unreachable!() } unsafe fn from_slice( - _: &mut impl AsContextMut, + _: &mut impl AsStoreMut, _: &[f64], ) -> Result { unreachable!() } - unsafe fn into_array(self, _: &mut impl AsContextMut) -> Self::Array { + unsafe fn into_array(self, _: &mut impl AsStoreMut) -> Self::Array { [] } @@ -1070,11 +1091,11 @@ mod inner { [] } - unsafe fn from_c_struct(_: &mut impl AsContextMut, self_: Self::CStruct) -> Self { + unsafe fn from_c_struct(_: &mut impl AsStoreMut, self_: Self::CStruct) -> Self { self_ } - unsafe fn into_c_struct(self, _: &mut impl AsContextMut) -> Self::CStruct { + unsafe fn into_c_struct(self, _: &mut impl AsStoreMut) -> Self::CStruct { self } diff --git a/lib/api/src/js/externals/global.rs b/lib/api/src/js/externals/global.rs index c570c7b27d9..47f4446a254 100644 --- a/lib/api/src/js/externals/global.rs +++ b/lib/api/src/js/externals/global.rs @@ -1,7 +1,7 @@ -use crate::js::context::{AsContextMut, AsContextRef, ContextHandle, InternalContextHandle}; use crate::js::export::VMGlobal; use crate::js::exports::{ExportError, Exportable}; use crate::js::externals::Extern; +use crate::js::store::{AsStoreMut, AsStoreRef, InternalStoreHandle, StoreHandle}; use crate::js::value::Value; use crate::js::wasm_bindgen_polyfill::Global as JSGlobal; use crate::js::GlobalType; @@ -17,7 +17,7 @@ use wasm_bindgen::JsValue; /// Spec: #[derive(Debug, Clone, PartialEq)] pub struct Global { - pub(crate) handle: ContextHandle, + pub(crate) handle: StoreHandle, } impl Global { @@ -27,14 +27,14 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Mutability, Store, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let g = Global::new(&store, Value::I32(1)); /// /// assert_eq!(g.get(), Value::I32(1)); /// assert_eq!(g.ty().mutability, Mutability::Const); /// ``` - pub fn new(ctx: &mut impl AsContextMut, val: Value) -> Self { + pub fn new(ctx: &mut impl AsStoreMut, val: Value) -> Self { Self::from_value(ctx, val, Mutability::Const).unwrap() } @@ -44,26 +44,26 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Mutability, Store, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let g = Global::new_mut(&store, Value::I32(1)); /// /// assert_eq!(g.get(), Value::I32(1)); /// assert_eq!(g.ty().mutability, Mutability::Var); /// ``` - pub fn new_mut(ctx: &mut impl AsContextMut, val: Value) -> Self { + pub fn new_mut(ctx: &mut impl AsStoreMut, val: Value) -> Self { Self::from_value(ctx, val, Mutability::Var).unwrap() } /// Create a `Global` with the initial value [`Value`] and the provided [`Mutability`]. fn from_value( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, val: Value, mutability: Mutability, ) -> Result { - if !val.is_from_context(ctx) { + if !val.is_from_store(ctx) { return Err(RuntimeError::new( - "cross-`Context` values are not supported", + "cross-`WasmerEnv` values are not supported", )); } let global_ty = GlobalType { @@ -99,7 +99,7 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Mutability, Store, Type, Value, GlobalType}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let c = Global::new(&store, Value::I32(1)); /// let v = Global::new_mut(&store, Value::I64(1)); @@ -107,8 +107,8 @@ impl Global { /// assert_eq!(c.ty(), &GlobalType::new(Type::I32, Mutability::Const)); /// assert_eq!(v.ty(), &GlobalType::new(Type::I64, Mutability::Var)); /// ``` - pub fn ty(&self, ctx: &impl AsContextRef) -> GlobalType { - self.handle.get(ctx.as_context_ref().objects()).ty + pub fn ty(&self, store: &impl AsStoreRef) -> GlobalType { + self.handle.get(store.as_store_ref().objects()).ty } /// Retrieves the current value [`Value`] that the Global has. @@ -117,23 +117,23 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Store, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let g = Global::new(&store, Value::I32(1)); /// /// assert_eq!(g.get(), Value::I32(1)); /// ``` - pub fn get(&self, ctx: &impl AsContextRef) -> Value { + pub fn get(&self, store: &impl AsStoreRef) -> Value { unsafe { let raw = self .handle - .get(ctx.as_context_ref().objects()) + .get(store.as_store_ref().objects()) .global .value() .as_f64() .unwrap(); - let ty = self.handle.get(ctx.as_context_ref().objects()).ty; - Value::from_raw(ctx, ty.ty, raw) + let ty = self.handle.get(store.as_store_ref().objects()).ty; + Value::from_raw(store, ty.ty, raw) } /* match self.vm_global.ty.ty { @@ -152,7 +152,7 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Store, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let g = Global::new_mut(&store, Value::I32(1)); /// @@ -169,7 +169,7 @@ impl Global { /// /// ```should_panic /// # use wasmer::{Global, Store, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let g = Global::new(&store, Value::I32(1)); /// @@ -180,20 +180,20 @@ impl Global { /// /// ```should_panic /// # use wasmer::{Global, Store, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let g = Global::new(&store, Value::I32(1)); /// /// // This results in an error: `RuntimeError`. /// g.set(Value::I64(2)).unwrap(); /// ``` - pub fn set(&self, ctx: &mut impl AsContextMut, val: Value) -> Result<(), RuntimeError> { - if !val.is_from_context(ctx) { + pub fn set(&self, store: &mut impl AsStoreMut, val: Value) -> Result<(), RuntimeError> { + if !val.is_from_store(store) { return Err(RuntimeError::new( - "cross-`Context` values are not supported", + "cross-`WasmerEnv` values are not supported", )); } - let global_ty = self.ty(&ctx); + let global_ty = self.ty(&store); if global_ty.mutability == Mutability::Const { return Err(RuntimeError::new("The global is immutable".to_owned())); } @@ -212,32 +212,32 @@ impl Global { } }; self.handle - .get_mut(ctx.as_context_mut().objects_mut()) + .get_mut(store.objects_mut()) .global .set_value(&new_value); Ok(()) } - pub(crate) fn from_vm_export(ctx: &mut impl AsContextMut, vm_global: VMGlobal) -> Self { + pub(crate) fn from_vm_export(store: &mut impl AsStoreMut, vm_global: VMGlobal) -> Self { Self { - handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_global), + handle: StoreHandle::new(store.objects_mut(), vm_global), } } pub(crate) fn from_vm_extern( - ctx: &mut impl AsContextMut, - internal: InternalContextHandle, + store: &mut impl AsStoreMut, + internal: InternalStoreHandle, ) -> Self { Self { handle: unsafe { - ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal) + StoreHandle::from_internal(store.as_store_ref().objects().id(), internal) }, } } - /// Checks whether this `Global` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + /// Checks whether this `Global` can be used with the given store. + pub fn is_from_store(&self, store: &impl AsStoreRef) -> bool { + self.handle.store_id() == store.as_store_ref().objects().id() } } diff --git a/lib/api/src/js/externals/memory.rs b/lib/api/src/js/externals/memory.rs index d100208c715..59cc788874a 100644 --- a/lib/api/src/js/externals/memory.rs +++ b/lib/api/src/js/externals/memory.rs @@ -1,9 +1,7 @@ -use crate::js::context::{ - AsContextMut, AsContextRef, ContextHandle, ContextObjects, InternalContextHandle, -}; use crate::js::export::VMMemory; use crate::js::exports::{ExportError, Exportable}; use crate::js::externals::Extern; +use crate::js::store::{AsStoreMut, AsStoreRef, InternalStoreHandle, StoreHandle, StoreObjects}; use crate::js::{MemoryAccessError, MemoryType}; use std::convert::TryInto; use std::marker::PhantomData; @@ -80,7 +78,7 @@ extern "C" { /// Spec: #[derive(Debug, Clone)] pub struct Memory { - pub(crate) handle: ContextHandle, + pub(crate) handle: StoreHandle, #[allow(dead_code)] view: js_sys::Uint8Array, } @@ -98,11 +96,11 @@ impl Memory { /// /// ``` /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let m = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); /// ``` - pub fn new(ctx: &mut impl AsContextMut, ty: MemoryType) -> Result { + pub fn new(ctx: &mut impl AsStoreMut, ty: MemoryType) -> Result { let descriptor = js_sys::Object::new(); js_sys::Reflect::set(&descriptor, &"initial".into(), &ty.minimum.0.into()).unwrap(); if let Some(max) = ty.maximum { @@ -123,15 +121,15 @@ impl Memory { /// /// ``` /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let mt = MemoryType::new(1, None, false); /// let m = Memory::new(&store, mt).unwrap(); /// /// assert_eq!(m.ty(), mt); /// ``` - pub fn ty(&self, ctx: &impl AsContextRef) -> MemoryType { - self.handle.get(ctx.as_context_ref().objects()).ty + pub fn ty(&self, ctx: &impl AsStoreRef) -> MemoryType { + self.handle.get(ctx.as_store_ref().objects()).ty } /// Returns the pointer to the raw bytes of the `Memory`. @@ -141,11 +139,11 @@ impl Memory { } /// Returns the size (in bytes) of the `Memory`. - pub fn data_size(&self, ctx: &impl AsContextRef) -> u64 { + pub fn data_size(&self, ctx: &impl AsStoreRef) -> u64 { js_sys::Reflect::get( &self .handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .memory .buffer(), &"byteLength".into(), @@ -161,17 +159,17 @@ impl Memory { /// /// ``` /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let m = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); /// /// assert_eq!(m.size(), Pages(1)); /// ``` - pub fn size(&self, ctx: &impl AsContextRef) -> Pages { + pub fn size(&self, ctx: &impl AsStoreRef) -> Pages { let bytes = js_sys::Reflect::get( &self .handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .memory .buffer(), &"byteLength".into(), @@ -189,7 +187,7 @@ impl Memory { /// /// ``` /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let m = Memory::new(&store, MemoryType::new(1, Some(3), false)).unwrap(); /// let p = m.grow(2).unwrap(); @@ -205,7 +203,7 @@ impl Memory { /// /// ```should_panic /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES}; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # /// let m = Memory::new(&store, MemoryType::new(1, Some(1), false)).unwrap(); /// @@ -214,20 +212,19 @@ impl Memory { /// ``` pub fn grow( &self, - ctx: &mut impl AsContextMut, + store: &mut impl AsStoreMut, delta: IntoPages, ) -> Result where IntoPages: Into, { let pages = delta.into(); - let mut ctx_mut = ctx.as_context_mut(); - let js_memory = &self.handle.get_mut(ctx_mut.objects_mut()).memory; + let js_memory = &self.handle.get_mut(store.objects_mut()).memory; let our_js_memory: &JSMemory = JsCast::unchecked_from_js_ref(js_memory); let new_pages = our_js_memory.grow(pages.0).map_err(|err| { if err.is_instance_of::() { MemoryError::CouldNotGrow { - current: self.size(&ctx.as_context_ref()), + current: self.size(&store.as_store_ref()), attempted_delta: pages, } } else { @@ -239,40 +236,40 @@ impl Memory { /// Used by tests #[doc(hidden)] - pub fn uint8view(&self, ctx: &impl AsContextRef) -> js_sys::Uint8Array { + pub fn uint8view(&self, ctx: &impl AsStoreRef) -> js_sys::Uint8Array { js_sys::Uint8Array::new( &self .handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .memory .buffer(), ) } - pub(crate) fn buffer<'a>(&'a self, _ctx: &'a impl AsContextRef) -> MemoryBuffer<'a> { + pub(crate) fn buffer<'a>(&'a self, _ctx: &'a impl AsStoreRef) -> MemoryBuffer<'a> { MemoryBuffer { base: &self.view as *const _ as *mut _, marker: PhantomData, } } - pub(crate) fn from_vm_export(ctx: &mut impl AsContextMut, vm_memory: VMMemory) -> Self { + pub(crate) fn from_vm_export(ctx: &mut impl AsStoreMut, vm_memory: VMMemory) -> Self { let view = js_sys::Uint8Array::new(&vm_memory.memory.buffer()); Self { - handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_memory), + handle: StoreHandle::new(ctx.objects_mut(), vm_memory), view, } } pub(crate) fn from_vm_extern( - ctx: &mut impl AsContextMut, - internal: InternalContextHandle, + ctx: &mut impl AsStoreMut, + internal: InternalStoreHandle, ) -> Self { let view = - js_sys::Uint8Array::new(&internal.get(ctx.as_context_ref().objects()).memory.buffer()); + js_sys::Uint8Array::new(&internal.get(ctx.as_store_ref().objects()).memory.buffer()); Self { handle: unsafe { - ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal) + StoreHandle::from_internal(ctx.as_store_ref().objects().id(), internal) }, view, } @@ -287,7 +284,7 @@ impl Memory { /// concurrent writes. pub fn read( &self, - _ctx: &impl AsContextRef, + _ctx: &impl AsStoreRef, offset: u64, data: &mut [u8], ) -> Result<(), MemoryAccessError> { @@ -317,7 +314,7 @@ impl Memory { /// concurrent writes. pub fn read_uninit<'a>( &self, - _ctx: &impl AsContextRef, + _ctx: &impl AsStoreRef, offset: u64, buf: &'a mut [MaybeUninit], ) -> Result<&'a mut [u8], MemoryAccessError> { @@ -352,7 +349,7 @@ impl Memory { /// concurrent reads/writes. pub fn write( &self, - _ctx: &mut impl AsContextMut, + _ctx: &mut impl AsStoreMut, offset: u64, data: &[u8], ) -> Result<(), MemoryAccessError> { @@ -371,8 +368,8 @@ impl Memory { } /// Checks whether this `Global` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { + self.handle.store_id() == ctx.as_store_ref().objects().id() } } @@ -389,7 +386,7 @@ impl<'a> Exportable<'a> for Memory { #[derive(Copy, Clone)] pub(crate) struct MemoryBuffer<'a> { base: *mut js_sys::Uint8Array, - marker: PhantomData<(&'a Memory, &'a ContextObjects)>, + marker: PhantomData<(&'a Memory, &'a StoreObjects)>, } impl<'a> MemoryBuffer<'a> { diff --git a/lib/api/src/js/externals/mod.rs b/lib/api/src/js/externals/mod.rs index 03c76ada645..ef34a5cc175 100644 --- a/lib/api/src/js/externals/mod.rs +++ b/lib/api/src/js/externals/mod.rs @@ -8,10 +8,10 @@ pub use self::global::Global; pub use self::memory::{Memory, MemoryError}; pub use self::table::Table; -use crate::js::context::{AsContextMut, AsContextRef}; use crate::js::export::Export; use crate::js::exports::{ExportError, Exportable}; use crate::js::store::StoreObject; +use crate::js::store::{AsStoreMut, AsStoreRef}; use crate::js::types::AsJs; use crate::js::ExternType; use std::fmt; @@ -34,7 +34,7 @@ pub enum Extern { impl Extern { /// Return the underlying type of the inner `Extern`. - pub fn ty(&self, ctx: &impl AsContextRef) -> ExternType { + pub fn ty(&self, ctx: &impl AsStoreRef) -> ExternType { match self { Self::Function(ft) => ExternType::Function(ft.ty(ctx).clone()), Self::Memory(ft) => ExternType::Memory(ft.ty(ctx)), @@ -44,7 +44,7 @@ impl Extern { } /// Create an `Extern` from an `wasmer_compiler::Export`. - pub fn from_vm_export(ctx: &mut impl AsContextMut, export: Export) -> Self { + pub fn from_vm_export(ctx: &mut impl AsStoreMut, export: Export) -> Self { match export { Export::Function(f) => Self::Function(Function::from_vm_extern(ctx, f)), Export::Memory(m) => Self::Memory(Memory::from_vm_extern(ctx, m)), @@ -54,12 +54,12 @@ impl Extern { } /// Checks whether this `Extern` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { match self { - Self::Function(val) => val.is_from_context(ctx), - Self::Memory(val) => val.is_from_context(ctx), - Self::Global(val) => val.is_from_context(ctx), - Self::Table(val) => val.is_from_context(ctx), + Self::Function(val) => val.is_from_store(ctx), + Self::Memory(val) => val.is_from_store(ctx), + Self::Global(val) => val.is_from_store(ctx), + Self::Table(val) => val.is_from_store(ctx), } } @@ -74,7 +74,7 @@ impl Extern { } impl AsJs for Extern { - fn as_jsvalue(&self, ctx: &impl AsContextRef) -> wasm_bindgen::JsValue { + fn as_jsvalue(&self, ctx: &impl AsStoreRef) -> wasm_bindgen::JsValue { match self { Self::Function(_) => self.to_export().as_jsvalue(ctx), Self::Global(_) => self.to_export().as_jsvalue(ctx), diff --git a/lib/api/src/js/externals/table.rs b/lib/api/src/js/externals/table.rs index f779b02d351..dd9143f2fd7 100644 --- a/lib/api/src/js/externals/table.rs +++ b/lib/api/src/js/externals/table.rs @@ -1,7 +1,7 @@ -use crate::js::context::{AsContextMut, AsContextRef, ContextHandle, InternalContextHandle}; use crate::js::export::{VMFunction, VMTable}; use crate::js::exports::{ExportError, Exportable}; use crate::js::externals::Extern; +use crate::js::store::{AsStoreMut, AsStoreRef, InternalStoreHandle, StoreHandle}; use crate::js::value::Value; use crate::js::RuntimeError; use crate::js::{FunctionType, TableType}; @@ -18,21 +18,21 @@ use js_sys::Function; /// Spec: #[derive(Debug, Clone, PartialEq)] pub struct Table { - pub(crate) handle: ContextHandle, + pub(crate) handle: StoreHandle, } fn set_table_item(table: &VMTable, item_index: u32, item: &Function) -> Result<(), RuntimeError> { table.table.set(item_index, item).map_err(|e| e.into()) } -fn get_function(ctx: &mut impl AsContextMut, val: Value) -> Result { - if !val.is_from_context(ctx) { +fn get_function(ctx: &mut impl AsStoreMut, val: Value) -> Result { + if !val.is_from_store(ctx) { return Err(RuntimeError::new("cannot pass Value across contexts")); } match val { Value::FuncRef(Some(ref func)) => Ok(func .handle - .get(&ctx.as_context_ref().objects()) + .get(&ctx.as_store_ref().objects()) .function .clone() .into()), @@ -49,11 +49,11 @@ impl Table { /// This function will construct the `Table` using the store /// [`BaseTunables`][crate::js::tunables::BaseTunables]. pub fn new( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, ty: TableType, init: Value, ) -> Result { - let mut ctx = ctx.as_context_mut(); + let mut ctx = ctx; let descriptor = js_sys::Object::new(); js_sys::Reflect::set(&descriptor, &"initial".into(), &ty.minimum.into())?; if let Some(max) = ty.maximum { @@ -71,20 +71,20 @@ impl Table { } Ok(Self { - handle: ContextHandle::new(ctx.objects_mut(), table), + handle: StoreHandle::new(ctx.objects_mut(), table), }) } /// Returns the [`TableType`] of the `Table`. - pub fn ty(&self, ctx: &impl AsContextRef) -> TableType { - self.handle.get(ctx.as_context_ref().objects()).ty + pub fn ty(&self, ctx: &impl AsStoreRef) -> TableType { + self.handle.get(ctx.as_store_ref().objects()).ty } /// Retrieves an element of the table at the provided `index`. - pub fn get(&self, ctx: &mut impl AsContextMut, index: u32) -> Option { + pub fn get(&self, ctx: &mut impl AsStoreMut, index: u32) -> Option { if let Some(func) = self .handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .table .get(index) .ok() @@ -101,24 +101,17 @@ impl Table { /// Sets an element `val` in the Table at the provided `index`. pub fn set( &self, - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, index: u32, val: Value, ) -> Result<(), RuntimeError> { let item = get_function(ctx, val)?; - set_table_item( - self.handle.get_mut(ctx.as_context_mut().objects_mut()), - index, - &item, - ) + set_table_item(self.handle.get_mut(ctx.objects_mut()), index, &item) } /// Retrieves the size of the `Table` (in elements) - pub fn size(&self, ctx: &impl AsContextRef) -> u32 { - self.handle - .get(ctx.as_context_ref().objects()) - .table - .length() + pub fn size(&self, ctx: &impl AsStoreRef) -> u32 { + self.handle.get(ctx.as_store_ref().objects()).table.length() } /// Grows the size of the `Table` by `delta`, initializating @@ -130,7 +123,12 @@ impl Table { /// # Errors /// /// Returns an error if the `delta` is out of bounds for the table. - pub fn grow(&self, _delta: u32, _init: Value) -> Result { + pub fn grow( + &self, + store: &mut AsStoreMut, + _delta: u32, + _init: Value, + ) -> Result { unimplemented!(); } @@ -152,19 +150,19 @@ impl Table { } pub(crate) fn from_vm_extern( - ctx: &mut impl AsContextMut, - internal: InternalContextHandle, + ctx: &mut impl AsStoreMut, + internal: InternalStoreHandle, ) -> Self { Self { handle: unsafe { - ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal) + StoreHandle::from_internal(ctx.as_store_ref().objects().id(), internal) }, } } /// Checks whether this `Table` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { + self.handle.store_id() == ctx.as_store_ref().objects().id() } /// Get access to the backing VM value for this extern. This function is for @@ -177,9 +175,9 @@ impl Table { #[doc(hidden)] pub unsafe fn get_vm_table<'context>( &self, - ctx: &'context impl AsContextRef, + ctx: &'context impl AsStoreRef, ) -> &'context VMTable { - self.handle.get(ctx.as_context_ref().objects()) + self.handle.get(ctx.as_store_ref().objects()) } } diff --git a/lib/api/src/js/function_env.rs b/lib/api/src/js/function_env.rs new file mode 100644 index 00000000000..81ef590a7c2 --- /dev/null +++ b/lib/api/src/js/function_env.rs @@ -0,0 +1,153 @@ +use std::{any::Any, marker::PhantomData}; + +use crate::js::{StoreHandle, StoreObjects}; + +use crate::js::{AsStoreMut, AsStoreRef, StoreMut, StoreRef}; + +#[derive(Debug)] +#[repr(transparent)] +/// An opaque reference to a function environment. +/// The function environment data is owned by the `Store`. +pub struct FunctionEnv { + pub(crate) handle: StoreHandle, + _phantom: PhantomData, +} + +impl FunctionEnv { + /// Make a new extern reference + pub fn new(store: &mut impl AsStoreMut, value: T) -> Self + where + T: Any + Send + 'static + Sized, + { + Self { + handle: StoreHandle::new( + store.as_store_mut().objects_mut(), + VMFunctionEnvironment::new(value), + ), + _phantom: PhantomData, + } + } + + pub(crate) fn from_handle(handle: StoreHandle) -> Self { + Self { + handle, + _phantom: PhantomData, + } + } + + /// Get the data as reference + pub fn as_ref<'a>(&self, store: &'a impl AsStoreMut) -> &'a T + where + T: Any + Send + 'static + Sized, + { + self.handle + .get(store.as_store_ref().objects()) + .as_ref() + .downcast_ref::() + .unwrap() + } + + /// Get the data as mutable + pub fn as_mut<'a>(&self, store: &'a mut impl AsStoreMut) -> &'a mut T + where + T: Any + Send + 'static + Sized, + { + self.handle + .get_mut(store.objects_mut()) + .as_mut() + .downcast_mut::() + .unwrap() + } + + /// Convert it into a `FunctionEnvMut` + pub fn into_mut(self, store: &mut impl AsStoreMut) -> FunctionEnvMut + where + T: Any + Send + 'static + Sized, + { + FunctionEnvMut { + store_mut: store.as_store_mut(), + func_env: self, + } + } +} + +impl Clone for FunctionEnv { + fn clone(&self) -> Self { + Self { + handle: self.handle.clone(), + _phantom: self._phantom, + } + } +} + +/// A temporary handle to a [`Context`]. +pub struct FunctionEnvMut<'a, T: 'a> { + pub(crate) store_mut: StoreMut<'a>, + pub(crate) func_env: FunctionEnv, +} + +impl FunctionEnvMut<'_, T> { + /// Returns a reference to the host state in this context. + pub fn data(&self) -> &T { + self.func_env.as_ref(&self.store_mut) + } + + /// Returns a mutable- reference to the host state in this context. + pub fn data_mut<'a>(&'a mut self) -> &'a mut T { + self.func_env.as_mut(&mut self.store_mut) + } + + /// Borrows a new mutable reference + pub fn as_mut<'a>(&'a mut self) -> FunctionEnvMut<'a, T> { + FunctionEnvMut { + store_mut: self.store_mut.as_store_mut(), + func_env: self.func_env.clone(), + } + } +} + +impl AsStoreRef for FunctionEnvMut<'_, T> { + fn as_store_ref(&self) -> StoreRef<'_> { + StoreRef { + inner: self.store_mut.inner, + } + } +} + +impl AsStoreMut for FunctionEnvMut<'_, T> { + fn as_store_mut(&mut self) -> StoreMut<'_> { + StoreMut { + inner: self.store_mut.inner, + } + } + #[inline] + fn objects_mut(&mut self) -> &mut StoreObjects { + &mut self.store_mut.inner.objects + } +} + +/// Underlying FunctionEnvironment used by a `VMFunction`. +pub struct VMFunctionEnvironment { + contents: Box, +} + +impl VMFunctionEnvironment { + /// Wraps the given value to expose it to Wasm code as a function context. + pub fn new(val: impl Any + Send + 'static) -> Self { + Self { + contents: Box::new(val), + } + } + + #[allow(clippy::should_implement_trait)] + /// Returns a reference to the underlying value. + pub fn as_ref(&self) -> &(dyn Any + Send + 'static) { + &*self.contents + } + + #[allow(clippy::should_implement_trait)] + /// Returns a mutable reference to the underlying value. + pub fn as_mut(&mut self) -> &mut (dyn Any + Send + 'static) { + &mut *self.contents + } +} diff --git a/lib/api/src/js/imports.rs b/lib/api/src/js/imports.rs index 596336e62ef..2c43350c5c0 100644 --- a/lib/api/src/js/imports.rs +++ b/lib/api/src/js/imports.rs @@ -1,10 +1,10 @@ //! The import module contains the implementation data structures and helper functions used to //! manipulate and access a wasm module's imports including memories, tables, globals, and //! functions. -use crate::js::context::AsContextRef; use crate::js::error::InstantiationError; use crate::js::exports::Exports; use crate::js::module::Module; +use crate::js::store::AsStoreRef; use crate::js::types::AsJs; use crate::Extern; use std::collections::HashMap; @@ -97,7 +97,7 @@ impl Imports { /// /// # Usage /// ```no_run - /// # let store = Default::default(); + /// # let mut store = Default::default(); /// use wasmer::{Imports, Function}; /// fn foo(n: i32) -> i32 { /// n @@ -151,7 +151,7 @@ impl Imports { } /// Returns the `Imports` as a Javascript `Object` - pub fn as_jsobject(&self, ctx: &impl AsContextRef) -> js_sys::Object { + pub fn as_jsobject(&self, ctx: &impl AsStoreRef) -> js_sys::Object { let imports = js_sys::Object::new(); let namespaces: HashMap<&str, Vec<(&str, &Extern)>> = self.map @@ -235,7 +235,7 @@ impl fmt::Debug for Imports { /// /// ``` /// # use wasmer::{Function, Store}; -/// # let store = Store::default(); +/// # let mut store = Store::default(); /// use wasmer::imports; /// /// let import_object = imports! { @@ -300,7 +300,7 @@ mod test { use crate::js::export::Export; use wasm_bindgen_test::*; fn namespace() { - let store = Store::default(); + let mut store = Store::default(); let g1 = Global::new(&store, Val::I32(0)); let namespace = namespace! { "happy" => g1 @@ -323,7 +323,7 @@ mod test { fn imports_macro_allows_trailing_comma_and_none() { use crate::js::Function; - let store = Default::default(); + let mut store = Default::default(); fn func(arg: i32) -> i32 { arg + 1 @@ -372,7 +372,7 @@ mod test { } fn chaining_works() { - let store = Store::default(); + let mut store = Store::default(); let g = Global::new(&store, Val::I32(0)); let mut imports1 = imports! { @@ -402,7 +402,7 @@ mod test { } fn extending_conflict_overwrites() { - let store = Store::default(); + let mut store = Store::default(); let g1 = Global::new(&store, Val::I32(0)); let g2 = Global::new(&store, Val::F32(0.)); @@ -430,7 +430,7 @@ mod test { ); // now test it in reverse - let store = Store::default(); + let mut store = Store::default(); let g1 = Global::new(&store, Val::I32(0)); let g2 = Global::new(&store, Val::F32(0.)); diff --git a/lib/api/src/js/instance.rs b/lib/api/src/js/instance.rs index ca2c830d7e3..181ccff54f9 100644 --- a/lib/api/src/js/instance.rs +++ b/lib/api/src/js/instance.rs @@ -1,10 +1,10 @@ -use crate::js::context::{AsContextMut, AsContextRef, ContextHandle}; use crate::js::error::InstantiationError; use crate::js::export::Export; use crate::js::exports::Exports; use crate::js::externals::Extern; use crate::js::imports::Imports; use crate::js::module::Module; +use crate::js::store::{AsStoreMut, AsStoreRef, StoreHandle}; use js_sys::WebAssembly; use std::fmt; @@ -18,7 +18,7 @@ use std::fmt; /// Spec: #[derive(Clone)] pub struct Instance { - _handle: ContextHandle, + _handle: StoreHandle, module: Module, #[allow(dead_code)] imports: Imports, @@ -41,7 +41,7 @@ impl Instance { /// ``` /// # use wasmer::{imports, Store, Module, Global, Value, Instance}; /// # fn main() -> anyhow::Result<()> { - /// let store = Store::default(); + /// let mut store = Store::default(); /// let module = Module::new(&store, "(module)")?; /// let imports = imports!{ /// "host" => { @@ -61,13 +61,13 @@ impl Instance { /// * Link errors that happen when plugging the imports into the instance /// * Runtime errors that happen when running the module `start` function. pub fn new( - ctx: &mut impl AsContextMut, + mut ctx: &mut impl AsStoreMut, module: &Module, imports: &Imports, ) -> Result { let import_copy = imports.clone(); - let (instance, _imports): (ContextHandle, Vec) = module - .instantiate(&mut ctx.as_context_mut(), imports) + let (instance, _imports): (StoreHandle, Vec) = module + .instantiate(&mut ctx, imports) .map_err(|e| InstantiationError::Start(e))?; let self_instance = Self::from_module_and_instance(ctx, module, instance, import_copy)?; @@ -85,12 +85,12 @@ impl Instance { /// /// *This method is only available when targeting JS environments* pub fn from_module_and_instance( - ctx: &mut impl AsContextMut, + mut ctx: &mut impl AsStoreMut, module: &Module, - instance: ContextHandle, + instance: StoreHandle, imports: Imports, ) -> Result { - let instance_exports = instance.get(ctx.as_context_ref().objects()).exports(); + let instance_exports = instance.get(ctx.as_store_ref().objects()).exports(); let exports = module .exports() .map(|export_type| { @@ -104,9 +104,8 @@ impl Instance { )) })?; let export: Export = - Export::from_js_value(js_export, &mut ctx.as_context_mut(), extern_type)? - .into(); - let extern_ = Extern::from_vm_export(&mut ctx.as_context_mut(), export); + Export::from_js_value(js_export, &mut ctx, extern_type)?.into(); + let extern_ = Extern::from_vm_export(&mut ctx, export); Ok((name.to_string(), extern_)) }) .collect::>()?; @@ -126,11 +125,8 @@ impl Instance { /// Returns the inner WebAssembly Instance #[doc(hidden)] - pub fn raw<'context>( - &self, - ctx: &'context impl AsContextRef, - ) -> &'context WebAssembly::Instance { - &self._handle.get(ctx.as_context_ref().objects()) + pub fn raw<'context>(&self, ctx: &'context impl AsStoreRef) -> &'context WebAssembly::Instance { + &self._handle.get(ctx.as_store_ref().objects()) } } diff --git a/lib/api/src/js/js_import_object.rs b/lib/api/src/js/js_import_object.rs index f1e58aec906..e890c5bc144 100644 --- a/lib/api/src/js/js_import_object.rs +++ b/lib/api/src/js/js_import_object.rs @@ -1,5 +1,5 @@ -use crate::js::context::AsContextMut; use crate::js::error::WasmError; +use crate::js::store::AsStoreMut; use crate::js::{Export, ExternType, Module}; use std::collections::HashMap; @@ -53,7 +53,7 @@ impl JsImportObject { /// ``` pub fn get_export( &self, - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, module: &str, name: &str, ) -> Result { diff --git a/lib/api/src/js/mem_access.rs b/lib/api/src/js/mem_access.rs index e5eb45afb0a..f9416b067ab 100644 --- a/lib/api/src/js/mem_access.rs +++ b/lib/api/src/js/mem_access.rs @@ -1,7 +1,7 @@ -use crate::js::context::AsContextRef; use crate::js::externals::memory::MemoryBuffer; -use crate::RuntimeError; -use crate::{Memory, Memory32, Memory64, WasmPtr}; +use crate::js::store::AsStoreRef; +use crate::js::RuntimeError; +use crate::js::{Memory, Memory32, Memory64, WasmPtr}; use std::{ convert::TryInto, fmt, @@ -61,7 +61,7 @@ pub struct WasmRef<'a, T: ValueType> { impl<'a, T: ValueType> WasmRef<'a, T> { /// Creates a new `WasmRef` at the given offset in a memory. #[inline] - pub fn new(ctx: &'a impl AsContextRef, memory: &'a Memory, offset: u64) -> Self { + pub fn new(ctx: &'a impl AsStoreRef, memory: &'a Memory, offset: u64) -> Self { Self { buffer: memory.buffer(ctx), offset, @@ -160,7 +160,7 @@ impl<'a, T: ValueType> WasmSlice<'a, T> { /// Returns a `MemoryAccessError` if the slice length overflows. #[inline] pub fn new( - ctx: &'a impl AsContextRef, + ctx: &'a impl AsStoreRef, memory: &'a Memory, offset: u64, len: u64, diff --git a/lib/api/src/js/mod.rs b/lib/api/src/js/mod.rs index 8f75409a87f..9863123c55b 100644 --- a/lib/api/src/js/mod.rs +++ b/lib/api/src/js/mod.rs @@ -23,11 +23,11 @@ mod lib { } } -mod context; mod error; mod export; mod exports; mod externals; +mod function_env; mod imports; mod instance; mod js_import_object; @@ -44,7 +44,6 @@ mod types; mod value; mod wasm_bindgen_polyfill; -pub use crate::js::context::{AsContextMut, AsContextRef, Context, ContextMut, ContextRef}; pub use crate::js::error::{DeserializeError, InstantiationError, SerializeError}; pub use crate::js::export::Export; pub use crate::js::exports::{ExportError, Exportable, Exports, ExportsIterator}; @@ -52,6 +51,7 @@ pub use crate::js::externals::{ Extern, FromToNativeWasmType, Function, Global, HostFunction, Memory, MemoryError, Table, WasmTypeList, }; +pub use crate::js::function_env::{FunctionEnv, FunctionEnvMut}; pub use crate::js::imports::Imports; pub use crate::js::instance::Instance; pub use crate::js::js_import_object::JsImportObject; @@ -62,7 +62,9 @@ pub use crate::js::native_type::NativeWasmTypeInto; pub use crate::js::ptr::{Memory32, Memory64, MemorySize, WasmPtr, WasmPtr64}; pub use crate::js::trap::RuntimeError; -pub use crate::js::store::{Store, StoreObject}; +pub use crate::js::store::{ + AsStoreMut, AsStoreRef, Store, StoreHandle, StoreMut, StoreObject, StoreObjects, StoreRef, +}; pub use crate::js::types::ValType as Type; pub use crate::js::types::{ ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability, diff --git a/lib/api/src/js/module.rs b/lib/api/src/js/module.rs index 67ef83b9aa1..209f46dfd46 100644 --- a/lib/api/src/js/module.rs +++ b/lib/api/src/js/module.rs @@ -1,4 +1,3 @@ -use crate::js::context::{AsContextMut, ContextHandle}; #[cfg(feature = "wat")] use crate::js::error::WasmError; use crate::js::error::{CompileError, InstantiationError}; @@ -7,8 +6,10 @@ use crate::js::error::{DeserializeError, SerializeError}; use crate::js::externals::Extern; use crate::js::imports::Imports; use crate::js::store::Store; +use crate::js::store::{AsStoreMut, StoreHandle}; use crate::js::types::{AsJs, ExportType, ImportType}; use crate::js::RuntimeError; +use crate::AsStoreRef; use js_sys::{Reflect, Uint8Array, WebAssembly}; use std::fmt; use std::io; @@ -59,7 +60,6 @@ pub struct ModuleTypeHints { /// contents rather than a deep copy. #[derive(Clone)] pub struct Module { - store: Store, module: WebAssembly::Module, name: Option, // WebAssembly type hints @@ -95,7 +95,7 @@ impl Module { /// ``` /// use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = "(module)"; /// let module = Module::new(&store, wat)?; /// # Ok(()) @@ -107,7 +107,7 @@ impl Module { /// ``` /// use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// // The following is the same as: /// // (module /// // (type $t0 (func (param i32) (result i32))) @@ -129,7 +129,7 @@ impl Module { /// # } /// ``` #[allow(unreachable_code)] - pub fn new(store: &Store, bytes: impl AsRef<[u8]>) -> Result { + pub fn new(_store: &impl AsStoreRef, bytes: impl AsRef<[u8]>) -> Result { #[cfg(feature = "wat")] let bytes = wat::parse_bytes(bytes.as_ref()).map_err(|e| { CompileError::Wasm(WasmError::Generic(format!( @@ -137,11 +137,14 @@ impl Module { e ))) })?; - Self::from_binary(store, bytes.as_ref()) + Self::from_binary(_store, bytes.as_ref()) } /// Creates a new WebAssembly module from a file path. - pub fn from_file(_store: &Store, _file: impl AsRef) -> Result { + pub fn from_file( + _store: &impl AsStoreRef, + _file: impl AsRef, + ) -> Result { unimplemented!(); } @@ -150,10 +153,10 @@ impl Module { /// Opposed to [`Module::new`], this function is not compatible with /// the WebAssembly text format (if the "wat" feature is enabled for /// this crate). - pub fn from_binary(store: &Store, binary: &[u8]) -> Result { + pub fn from_binary(_store: &impl AsStoreRef, binary: &[u8]) -> Result { // // Self::validate(store, binary)?; - unsafe { Self::from_binary_unchecked(store, binary) } + unsafe { Self::from_binary_unchecked(_store, binary) } } /// Creates a new WebAssembly module skipping any kind of validation. @@ -163,7 +166,7 @@ impl Module { /// This is safe since the JS vm should be safe already. /// We maintain the `unsafe` to preserve the same API as Wasmer pub unsafe fn from_binary_unchecked( - store: &Store, + _store: &impl AsStoreRef, binary: &[u8], ) -> Result { let js_bytes = Uint8Array::view(binary); @@ -194,7 +197,6 @@ impl Module { let (type_hints, name) = (None, None); Ok(Self { - store: store.clone(), module, type_hints, name, @@ -209,7 +211,7 @@ impl Module { /// This validation is normally pretty fast and checks the enabled /// WebAssembly features in the Store Engine to assure deterministic /// validation of the Module. - pub fn validate(_store: &Store, binary: &[u8]) -> Result<(), CompileError> { + pub fn validate(_store: &impl AsStoreRef, binary: &[u8]) -> Result<(), CompileError> { let js_bytes = unsafe { Uint8Array::view(binary) }; match WebAssembly::validate(&js_bytes.into()) { Ok(true) => Ok(()), @@ -219,16 +221,17 @@ impl Module { pub(crate) fn instantiate( &self, - ctx: &mut impl AsContextMut, + store: &mut impl AsStoreMut, imports: &Imports, - ) -> Result<(ContextHandle, Vec), RuntimeError> { - // Ensure all imports come from the same context. + ) -> Result<(StoreHandle, Vec), RuntimeError> { + // Ensure all imports come from the same store. if imports .into_iter() - .any(|(_, import)| !import.is_from_context(ctx)) + .any(|(_, import)| !import.is_from_store(store)) { - // FIXME is RuntimeError::User appropriate? - return Err(RuntimeError::user(Box::new(InstantiationError::BadContext))); + return Err(RuntimeError::user(Box::new( + InstantiationError::DifferentStores, + ))); } let imports_object = js_sys::Object::new(); let mut import_externs: Vec = vec![]; @@ -241,7 +244,7 @@ impl Module { js_sys::Reflect::set( &val, &import_type.name().into(), - &import.as_jsvalue(&ctx.as_context_ref()), + &import.as_jsvalue(&store.as_store_ref()), )?; } else { // If the namespace doesn't exist @@ -249,7 +252,7 @@ impl Module { js_sys::Reflect::set( &import_namespace, &import_type.name().into(), - &import.as_jsvalue(&ctx.as_context_ref()), + &import.as_jsvalue(&store.as_store_ref()), )?; js_sys::Reflect::set( &imports_object, @@ -263,8 +266,8 @@ impl Module { // the error for us, so we don't need to handle it } Ok(( - ContextHandle::new( - ctx.as_context_mut().objects_mut(), + StoreHandle::new( + store.as_store_mut().objects_mut(), WebAssembly::Instance::new(&self.module, &imports_object) .map_err(|e: JsValue| -> RuntimeError { e.into() })?, ), @@ -282,7 +285,7 @@ impl Module { /// ``` /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = "(module $moduleName)"; /// let module = Module::new(&store, wat)?; /// assert_eq!(module.name(), Some("moduleName")); @@ -309,8 +312,11 @@ impl Module { /// This is safe since deserialization under `js` is essentially same as reconstructing `Module`. /// We maintain the `unsafe` to preserve the same API as Wasmer #[cfg(feature = "js-serializable-module")] - pub unsafe fn deserialize(store: &Store, bytes: &[u8]) -> Result { - Self::new(store, bytes).map_err(|e| DeserializeError::Compiler(e)) + pub unsafe fn deserialize( + _store: &impl AsStoreRef, + bytes: &[u8], + ) -> Result { + Self::new(_store, bytes).map_err(|e| DeserializeError::Compiler(e)) } /// Sets the name of the current module. @@ -325,7 +331,7 @@ impl Module { /// ``` /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = "(module)"; /// let mut module = Module::new(&store, wat)?; /// assert_eq!(module.name(), None); @@ -360,7 +366,7 @@ impl Module { /// ``` /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = r#"(module /// (import "host" "func1" (func)) /// (import "host" "func2" (func)) @@ -458,7 +464,7 @@ impl Module { /// ``` /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = r#"(module /// (func (export "namedfunc")) /// (memory (export "namedmemory") 1) @@ -530,11 +536,6 @@ impl Module { // pub fn custom_sections<'a>(&'a self, name: &'a str) -> impl Iterator> + 'a { // unimplemented!(); // } - - /// Returns the [`Store`] where the `Instance` belongs. - pub fn store(&self) -> &Store { - &self.store - } } impl fmt::Debug for Module { @@ -548,7 +549,6 @@ impl fmt::Debug for Module { impl From for Module { fn from(module: WebAssembly::Module) -> Module { Module { - store: Store::default(), module, name: None, type_hints: None, diff --git a/lib/api/src/js/native.rs b/lib/api/src/js/native.rs index ca21f752301..588f9618254 100644 --- a/lib/api/src/js/native.rs +++ b/lib/api/src/js/native.rs @@ -9,8 +9,9 @@ //! ``` use std::marker::PhantomData; -use crate::js::context::{AsContextMut, AsContextRef, ContextHandle}; use crate::js::externals::Function; +use crate::js::store::{AsStoreMut, AsStoreRef, StoreHandle}; +use crate::js::FunctionEnv; use crate::js::{FromToNativeWasmType, RuntimeError, WasmTypeList}; // use std::panic::{catch_unwind, AssertUnwindSafe}; use crate::js::export::VMFunction; @@ -23,7 +24,7 @@ use wasm_bindgen::JsValue; /// (using the Native ABI). #[derive(Clone)] pub struct TypedFunction { - pub(crate) handle: ContextHandle, + pub(crate) handle: StoreHandle, _phantom: PhantomData<(Args, Rets)>, } @@ -36,9 +37,13 @@ where Rets: WasmTypeList, { #[allow(dead_code)] - pub(crate) fn new(ctx: &mut impl AsContextMut, vm_function: VMFunction) -> Self { + pub(crate) fn new( + store: &mut impl AsStoreMut, + env: &FunctionEnv, + vm_function: VMFunction, + ) -> Self { Self { - handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_function), + handle: StoreHandle::new(store.as_store_mut().objects_mut(), vm_function), _phantom: PhantomData, } } @@ -61,11 +66,11 @@ macro_rules! impl_native_traits { { /// Call the typed func and return results. #[allow(clippy::too_many_arguments)] - pub fn call(&self, ctx: &mut impl AsContextMut, $( $x: $x, )* ) -> Result where + pub fn call(&self, mut ctx: &mut impl AsStoreMut, $( $x: $x, )* ) -> Result where $( $x: FromToNativeWasmType + crate::js::NativeWasmTypeInto, )* { - let params_list: Vec = vec![ $( JsValue::from_f64($x.into_raw(ctx))),* ]; - let results = self.handle.get(ctx.as_context_ref().objects()).function.apply( + let params_list: Vec = vec![ $( JsValue::from_f64($x.into_raw(&mut ctx))),* ]; + let results = self.handle.get(ctx.as_store_ref().objects()).function.apply( &JsValue::UNDEFINED, &Array::from_iter(params_list.iter()) )?; @@ -76,7 +81,7 @@ macro_rules! impl_native_traits { 1 => unsafe { let ty = Rets::wasm_types()[0]; let val = param_from_js(&ty, &results); - *mut_rets = val.as_raw(&mut ctx.as_context_mut()); + *mut_rets = val.as_raw(&mut ctx); } _n => { let results: Array = results.into(); @@ -85,7 +90,7 @@ macro_rules! impl_native_traits { unsafe { let val = param_from_js(&ret_type, &ret); let slot = mut_rets.add(i); - *slot = val.as_raw(&mut ctx.as_context_mut()); + *slot = val.as_raw(&mut ctx); } } } @@ -101,7 +106,7 @@ macro_rules! impl_native_traits { $( $x: FromToNativeWasmType, )* Rets: WasmTypeList, { - fn get_self_from_extern_with_generics(ctx: &impl AsContextRef, _extern: &crate::js::externals::Extern) -> Result { + fn get_self_from_extern_with_generics(ctx: &impl AsStoreRef, _extern: &crate::js::externals::Extern) -> Result { use crate::js::exports::Exportable; crate::js::Function::get_self_from_extern(_extern)?.native(ctx).map_err(|_| crate::js::exports::ExportError::IncompatibleType) } diff --git a/lib/api/src/js/native_type.rs b/lib/api/src/js/native_type.rs index e6dc2805462..d2a3abc1b68 100644 --- a/lib/api/src/js/native_type.rs +++ b/lib/api/src/js/native_type.rs @@ -3,113 +3,113 @@ use wasmer_types::{NativeWasmType, Type}; -use crate::Function; +use crate::js::Function; -use super::context::AsContextMut; +use super::store::AsStoreMut; /// `NativeWasmTypeInto` performs conversions from and into `NativeWasmType` /// types with a context. pub trait NativeWasmTypeInto: NativeWasmType + Sized { #[doc(hidden)] - fn into_abi(self, ctx: &mut impl AsContextMut) -> Self::Abi; + fn into_abi(self, ctx: &mut impl AsStoreMut) -> Self::Abi; #[doc(hidden)] - unsafe fn from_abi(ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self; + unsafe fn from_abi(ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self; /// Convert self to raw value representation. - fn into_raw(self, ctx: &mut impl AsContextMut) -> f64; + fn into_raw(self, ctx: &mut impl AsStoreMut) -> f64; /// Convert to self from raw value representation. /// /// # Safety /// - unsafe fn from_raw(ctx: &mut impl AsContextMut, raw: f64) -> Self; + unsafe fn from_raw(ctx: &mut impl AsStoreMut, raw: f64) -> Self; } impl NativeWasmTypeInto for i32 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> f64 { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> f64 { self.into() } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: f64) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: f64) -> Self { raw as _ } } impl NativeWasmTypeInto for i64 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> f64 { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> f64 { self as _ } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: f64) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: f64) -> Self { raw as _ } } impl NativeWasmTypeInto for f32 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> f64 { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> f64 { self as _ } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: f64) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: f64) -> Self { raw as _ } } impl NativeWasmTypeInto for f64 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> f64 { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> f64 { self } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: f64) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: f64) -> Self { raw } } diff --git a/lib/api/src/js/ptr.rs b/lib/api/src/js/ptr.rs index 95a1f8f1704..1e2af555f2f 100644 --- a/lib/api/src/js/ptr.rs +++ b/lib/api/src/js/ptr.rs @@ -1,7 +1,7 @@ -use crate::js::context::AsContextRef; +use crate::js::store::AsStoreRef; use crate::js::NativeWasmTypeInto; use crate::js::{externals::Memory, FromToNativeWasmType}; -use crate::{MemoryAccessError, WasmRef, WasmSlice}; +use crate::js::{MemoryAccessError, WasmRef, WasmSlice}; use std::convert::TryFrom; use std::{fmt, marker::PhantomData, mem}; pub use wasmer_types::Memory32; @@ -138,13 +138,13 @@ impl WasmPtr { /// Creates a `WasmRef` from this `WasmPtr` which allows reading and /// mutating of the value being pointed to. #[inline] - pub fn deref<'a>(self, ctx: &'a impl AsContextRef, memory: &'a Memory) -> WasmRef<'a, T> { + pub fn deref<'a>(self, ctx: &'a impl AsStoreRef, memory: &'a Memory) -> WasmRef<'a, T> { WasmRef::new(ctx, memory, self.offset.into()) } /// Reads the address pointed to by this `WasmPtr` in a memory. #[inline] - pub fn read(self, ctx: &impl AsContextRef, memory: &Memory) -> Result { + pub fn read(self, ctx: &impl AsStoreRef, memory: &Memory) -> Result { self.deref(ctx, memory).read() } @@ -152,7 +152,7 @@ impl WasmPtr { #[inline] pub fn write( self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, memory: &Memory, val: T, ) -> Result<(), MemoryAccessError> { @@ -167,7 +167,7 @@ impl WasmPtr { #[inline] pub fn slice<'a>( self, - ctx: &'a impl AsContextRef, + ctx: &'a impl AsStoreRef, memory: &'a Memory, len: M::Offset, ) -> Result, MemoryAccessError> { @@ -181,7 +181,7 @@ impl WasmPtr { #[inline] pub fn read_until<'a>( self, - ctx: &'a impl AsContextRef, + ctx: &'a impl AsStoreRef, memory: &'a Memory, mut end: impl FnMut(&T) -> bool, ) -> Result, MemoryAccessError> { @@ -206,7 +206,7 @@ impl WasmPtr { #[inline] pub fn read_utf8_string<'a>( self, - ctx: &'a impl AsContextRef, + ctx: &'a impl AsStoreRef, memory: &'a Memory, len: M::Offset, ) -> Result { @@ -221,7 +221,7 @@ impl WasmPtr { #[inline] pub fn read_utf8_string_with_nul<'a>( self, - ctx: &'a impl AsContextRef, + ctx: &'a impl AsStoreRef, memory: &'a Memory, ) -> Result { let vec = self.read_until(ctx, memory, |&byte| byte == 0)?; diff --git a/lib/api/src/js/store.rs b/lib/api/src/js/store.rs index 88c8b068f78..a2553df7407 100644 --- a/lib/api/src/js/store.rs +++ b/lib/api/src/js/store.rs @@ -1,5 +1,12 @@ use std::fmt; +/// We require the context to have a fixed memory address for its lifetime since +/// various bits of the VM have raw pointers that point back to it. Hence we +/// wrap the actual context in a box. +pub(crate) struct StoreInner { + pub(crate) objects: StoreObjects, +} + /// The store represents all global state that can be manipulated by /// WebAssembly programs. It consists of the runtime representation /// of all instances of functions, tables, memories, and globals that @@ -10,13 +17,18 @@ use std::fmt; /// [`Tunables`] (that are used to create the memories, tables and globals). /// /// Spec: -#[derive(Clone)] -pub struct Store; +pub struct Store { + pub(crate) inner: Box, +} impl Store { /// Creates a new `Store`. pub fn new() -> Self { - Self + Self { + inner: Box::new(StoreInner { + objects: Default::default(), + }), + } } /// Checks whether two stores are identical. A store is considered @@ -57,3 +69,377 @@ pub trait StoreObject { true } } + +impl AsStoreRef for Store { + fn as_store_ref(&self) -> StoreRef<'_> { + StoreRef { inner: &self.inner } + } +} +impl AsStoreMut for Store { + fn as_store_mut(&mut self) -> StoreMut<'_> { + StoreMut { + inner: &mut self.inner, + } + } + fn objects_mut(&mut self) -> &mut StoreObjects { + &mut self.inner.objects + } +} + +/// A temporary handle to a [`Context`]. +pub struct StoreRef<'a> { + pub(crate) inner: &'a StoreInner, +} + +impl<'a> StoreRef<'a> { + pub(crate) fn objects(&self) -> &'a StoreObjects { + &self.inner.objects + } + + /// Checks whether two stores are identical. A store is considered + /// equal to another store if both have the same engine. The + /// tunables are excluded from the logic. + pub fn same(a: &Self, b: &Self) -> bool { + a.inner.objects.id() == b.inner.objects.id() + } +} + +/// A temporary handle to a [`Context`]. +pub struct StoreMut<'a> { + pub(crate) inner: &'a mut StoreInner, +} + +impl<'a> StoreMut<'a> { + /// Checks whether two stores are identical. A store is considered + /// equal to another store if both have the same engine. The + /// tunables are excluded from the logic. + pub fn same(a: &Self, b: &Self) -> bool { + a.inner.objects.id() == b.inner.objects.id() + } + + pub(crate) fn as_raw(&self) -> *mut StoreInner { + self.inner as *const StoreInner as *mut StoreInner + } + + pub(crate) unsafe fn from_raw(raw: *mut StoreInner) -> Self { + Self { inner: &mut *raw } + } +} + +/// Helper trait for a value that is convertible to a [`StoreRef`]. +pub trait AsStoreRef { + /// Returns a `StoreRef` pointing to the underlying context. + fn as_store_ref(&self) -> StoreRef<'_>; +} + +/// Helper trait for a value that is convertible to a [`StoreMut`]. +pub trait AsStoreMut: AsStoreRef { + /// Returns a `StoreMut` pointing to the underlying context. + fn as_store_mut(&mut self) -> StoreMut<'_>; + + /// Returns the ObjectMutable + fn objects_mut(&mut self) -> &mut StoreObjects; +} + +impl AsStoreRef for StoreRef<'_> { + fn as_store_ref(&self) -> StoreRef<'_> { + StoreRef { inner: self.inner } + } +} + +impl AsStoreRef for StoreMut<'_> { + fn as_store_ref(&self) -> StoreRef<'_> { + StoreRef { inner: self.inner } + } +} +impl AsStoreMut for StoreMut<'_> { + fn as_store_mut(&mut self) -> StoreMut<'_> { + StoreMut { inner: self.inner } + } + fn objects_mut(&mut self) -> &mut StoreObjects { + &mut self.inner.objects + } +} + +impl AsStoreRef for &'_ T { + fn as_store_ref(&self) -> StoreRef<'_> { + T::as_store_ref(*self) + } +} +impl AsStoreRef for &'_ mut T { + fn as_store_ref(&self) -> StoreRef<'_> { + T::as_store_ref(*self) + } +} +impl AsStoreMut for &'_ mut T { + fn as_store_mut(&mut self) -> StoreMut<'_> { + T::as_store_mut(*self) + } + fn objects_mut(&mut self) -> &mut StoreObjects { + T::objects_mut(*self) + } +} + +pub use objects::*; + +use crate::js::FunctionEnv; +mod objects { + use crate::js::{ + export::{VMFunction, VMGlobal, VMMemory, VMTable}, + function_env::VMFunctionEnvironment, + }; + use std::{ + cell::UnsafeCell, + fmt, + marker::PhantomData, + num::{NonZeroU64, NonZeroUsize}, + ptr::NonNull, + sync::atomic::{AtomicU64, Ordering}, + }; + + /// Unique ID to identify a context. + /// + /// Every handle to an object managed by a context also contains the ID of the + /// context. This is used to check that a handle is always used with the + /// correct context. + #[derive(Debug, Copy, Clone, Eq, PartialEq)] + pub struct StoreId(NonZeroU64); + + impl Default for StoreId { + // Allocates a unique ID for a new context. + fn default() -> Self { + // No overflow checking is needed here: overflowing this would take + // thousands of years. + static NEXT_ID: AtomicU64 = AtomicU64::new(1); + Self(NonZeroU64::new(NEXT_ID.fetch_add(1, Ordering::Relaxed)).unwrap()) + } + } + + /// Trait to represent an object managed by a context. This is implemented on + /// the VM types managed by the context. + pub trait StoreObject: Sized { + fn list(ctx: &StoreObjects) -> &Vec; + fn list_mut(ctx: &mut StoreObjects) -> &mut Vec; + } + + macro_rules! impl_store_object { + ($($field:ident => $ty:ty,)*) => { + $( + impl StoreObject for $ty { + fn list(ctx: &StoreObjects) -> &Vec { + &ctx.$field + } + fn list_mut(ctx: &mut StoreObjects) -> &mut Vec { + &mut ctx.$field + } + } + )* + }; +} + + impl_store_object! { + functions => VMFunction, + tables => VMTable, + globals => VMGlobal, + memories => VMMemory, + instances => js_sys::WebAssembly::Instance, + function_environments => VMFunctionEnvironment, + } + + /// Set of objects managed by a context. + #[derive(Default)] + pub struct StoreObjects { + id: StoreId, + memories: Vec, + tables: Vec, + globals: Vec, + functions: Vec, + instances: Vec, + function_environments: Vec, + } + + impl StoreObjects { + /// Returns the ID of this context. + pub fn id(&self) -> StoreId { + self.id + } + + /// Returns a pair of mutable references from two handles. + /// + /// Panics if both handles point to the same object. + pub fn get_2_mut( + &mut self, + a: InternalStoreHandle, + b: InternalStoreHandle, + ) -> (&mut T, &mut T) { + assert_ne!(a.index(), b.index()); + let list = T::list_mut(self); + if a.index() < b.index() { + let (low, high) = list.split_at_mut(b.index()); + (&mut low[a.index()], &mut high[0]) + } else { + let (low, high) = list.split_at_mut(a.index()); + (&mut high[0], &mut low[a.index()]) + } + } + } + + /// Handle to an object managed by a context. + /// + /// Internally this is just an integer index into a context. A reference to the + /// context must be passed in separately to access the actual object. + pub struct StoreHandle { + id: StoreId, + internal: InternalStoreHandle, + } + + impl core::cmp::PartialEq for StoreHandle { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } + } + impl Clone for StoreHandle { + fn clone(&self) -> Self { + Self { + id: self.id, + internal: self.internal, + } + } + } + + impl fmt::Debug for StoreHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StoreHandle") + .field("id", &self.id) + .field("internal", &self.internal.index()) + .finish() + } + } + + impl StoreHandle { + /// Moves the given object into a context and returns a handle to it. + pub fn new(ctx: &mut StoreObjects, val: T) -> Self { + Self { + id: ctx.id, + internal: InternalStoreHandle::new(ctx, val), + } + } + + /// Returns a reference to the object that this handle points to. + pub fn get<'a>(&self, ctx: &'a StoreObjects) -> &'a T { + assert_eq!(self.id, ctx.id, "object used with the wrong context"); + self.internal.get(ctx) + } + + /// Returns a mutable reference to the object that this handle points to. + pub fn get_mut<'a>(&self, ctx: &'a mut StoreObjects) -> &'a mut T { + assert_eq!(self.id, ctx.id, "object used with the wrong context"); + self.internal.get_mut(ctx) + } + + /// Returns the internal handle contains within this handle. + pub fn internal_handle(&self) -> InternalStoreHandle { + self.internal + } + + /// Returns the ID of the context associated with the handle. + pub fn store_id(&self) -> StoreId { + self.id + } + + /// Constructs a `StoreHandle` from a `StoreId` and an `InternalStoreHandle`. + /// + /// # Safety + /// Handling `InternalStoreHandle` values is unsafe because they do not track context ID. + pub unsafe fn from_internal(id: StoreId, internal: InternalStoreHandle) -> Self { + Self { id, internal } + } + } + + /// Internal handle to an object owned by the current context. + /// + /// Unlike `StoreHandle` this does not track the context ID: it is only + /// intended to be used within objects already owned by a context. + #[repr(transparent)] + pub struct InternalStoreHandle { + // Use a NonZero here to reduce the size of Option. + idx: NonZeroUsize, + marker: PhantomData T>, + } + + impl Clone for InternalStoreHandle { + fn clone(&self) -> Self { + *self + } + } + impl Copy for InternalStoreHandle {} + + impl fmt::Debug for InternalStoreHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("InternalStoreHandle") + .field("idx", &self.idx) + .finish() + } + } + impl PartialEq for InternalStoreHandle { + fn eq(&self, other: &Self) -> bool { + self.idx == other.idx + } + } + impl Eq for InternalStoreHandle {} + + impl InternalStoreHandle { + /// Moves the given object into a context and returns a handle to it. + pub fn new(ctx: &mut StoreObjects, val: T) -> Self { + let list = T::list_mut(ctx); + let idx = NonZeroUsize::new(list.len() + 1).unwrap(); + list.push(val); + Self { + idx, + marker: PhantomData, + } + } + + /// Returns a reference to the object that this handle points to. + pub fn get<'a>(&self, ctx: &'a StoreObjects) -> &'a T { + &T::list(ctx)[self.idx.get() - 1] + } + + /// Returns a mutable reference to the object that this handle points to. + pub fn get_mut<'a>(&self, ctx: &'a mut StoreObjects) -> &'a mut T { + &mut T::list_mut(ctx)[self.idx.get() - 1] + } + + pub(crate) fn index(&self) -> usize { + self.idx.get() + } + + pub(crate) fn from_index(idx: usize) -> Option { + NonZeroUsize::new(idx).map(|idx| Self { + idx, + marker: PhantomData, + }) + } + } + + /// Data used by the generated code is generally located inline within the + /// `VMContext` for items defined in an instance. Host-defined objects are + /// allocated separately and owned directly by the context. + pub enum MaybeInstanceOwned { + /// The data is owned here. + Host(Box>), + + /// The data is stored inline in the `VMContext` of an instance. + Instance(NonNull), + } + + impl MaybeInstanceOwned { + /// Returns underlying pointer to the VM data. + pub fn as_ptr(&self) -> NonNull { + match self { + MaybeInstanceOwned::Host(p) => unsafe { NonNull::new_unchecked(p.get()) }, + MaybeInstanceOwned::Instance(p) => *p, + } + } + } +} diff --git a/lib/api/src/js/types.rs b/lib/api/src/js/types.rs index baf52038ddd..ebce0b27808 100644 --- a/lib/api/src/js/types.rs +++ b/lib/api/src/js/types.rs @@ -1,7 +1,7 @@ //use crate::js::externals::Function; // use crate::js::store::{Store, StoreObject}; // use crate::js::RuntimeError; -use crate::js::context::AsContextRef; +use crate::js::store::AsStoreRef; use crate::js::value::Value; use wasm_bindgen::JsValue; pub use wasmer_types::{ @@ -19,7 +19,7 @@ pub use wasmer_types::{ //pub type Value = Value; pub trait AsJs { - fn as_jsvalue(&self, ctx: &impl AsContextRef) -> JsValue; + fn as_jsvalue(&self, ctx: &impl AsStoreRef) -> JsValue; } #[inline] @@ -37,7 +37,7 @@ pub fn param_from_js(ty: &ValType, js_val: &JsValue) -> Value { } impl AsJs for Value { - fn as_jsvalue(&self, ctx: &impl AsContextRef) -> JsValue { + fn as_jsvalue(&self, ctx: &impl AsStoreRef) -> JsValue { match self { Self::I32(i) => JsValue::from_f64(*i as f64), Self::I64(i) => JsValue::from_f64(*i as f64), @@ -45,7 +45,7 @@ impl AsJs for Value { Self::F64(f) => JsValue::from_f64(*f), Self::FuncRef(Some(func)) => func .handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .function .clone() .into(), diff --git a/lib/api/src/js/value.rs b/lib/api/src/js/value.rs index 703b6df4502..99188e20d98 100644 --- a/lib/api/src/js/value.rs +++ b/lib/api/src/js/value.rs @@ -7,7 +7,7 @@ use wasmer_types::Type; //use crate::ExternRef; use crate::js::externals::function::Function; -use super::context::AsContextRef; +use super::store::AsStoreRef; /// WebAssembly computations manipulate values of basic value types: /// * Integers (32 or 64 bit width) @@ -82,7 +82,7 @@ impl Value { } /// Converts the `Value` into a `f64`. - pub fn as_raw(&self, ctx: &impl AsContextRef) -> f64 { + pub fn as_raw(&self, ctx: &impl AsStoreRef) -> f64 { match *self { Self::I32(v) => v as f64, Self::I64(v) => v as f64, @@ -90,7 +90,7 @@ impl Value { Self::F64(v) => v, Self::FuncRef(Some(ref f)) => f .handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .function .as_f64() .unwrap_or(0_f64), //TODO is this correct? @@ -105,7 +105,7 @@ impl Value { /// /// # Safety /// - pub unsafe fn from_raw(_ctx: &impl AsContextRef, ty: Type, raw: f64) -> Self { + pub unsafe fn from_raw(_ctx: &impl AsStoreRef, ty: Type, raw: f64) -> Self { match ty { Type::I32 => Self::I32(raw as i32), Type::I64 => Self::I64(raw as i64), @@ -128,7 +128,7 @@ impl Value { /// /// Externref and funcref values are tied to a context and can only be used /// with that context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { match self { Self::I32(_) | Self::I64(_) @@ -136,8 +136,8 @@ impl Value { | Self::F64(_) //| Self::ExternRef(None) | Self::FuncRef(None) => true, - //Self::ExternRef(Some(e)) => e.is_from_context(ctx), - Self::FuncRef(Some(f)) => f.is_from_context(ctx), + //Self::ExternRef(Some(e)) => e.is_from_store(ctx), + Self::FuncRef(Some(f)) => f.is_from_store(ctx), } } diff --git a/lib/api/src/lib.rs b/lib/api/src/lib.rs index dcdd56e3fe2..5a14ab0dab6 100644 --- a/lib/api/src/lib.rs +++ b/lib/api/src/lib.rs @@ -41,7 +41,7 @@ //! //! ```rust //! use wasmer::{Store, Module, Instance, Value, imports}; -//! use wasmer::Context as WasmerContext; +//! use wasmer::FunctionEnv; //! //! fn main() -> anyhow::Result<()> { //! let module_wat = r#" @@ -53,15 +53,15 @@ //! i32.add)) //! "#; //! -//! let store = Store::default(); -//! let mut ctx = WasmerContext::new(&store, ()); +//! let mut store = Store::default(); +//! let env = FunctionEnv::new(&mut store, ()); //! let module = Module::new(&store, &module_wat)?; //! // The module doesn't import anything, so we create an empty import object. //! let import_object = imports! {}; -//! let instance = Instance::new(&mut ctx, &module, &import_object)?; +//! let instance = Instance::new(&mut store, &module, &import_object)?; //! //! let add_one = instance.exports.get_function("add_one")?; -//! let result = add_one.call(&mut ctx, &[Value::I32(42)])?; +//! let result = add_one.call(&mut store, &[Value::I32(42)])?; //! assert_eq!(result[0], Value::I32(43)); //! //! Ok(()) @@ -151,13 +151,12 @@ //! [`imports`] macro: //! //! ``` -//! # use wasmer::{imports, Function, Memory, MemoryType, Store, Imports}; -//! # use wasmer::ContextMut; -//! # fn imports_example(mut ctx: ContextMut<()>, store: &Store) -> Imports { -//! let memory = Memory::new(&mut ctx, MemoryType::new(1, None, false)).unwrap(); +//! # use wasmer::{imports, Function, FunctionEnv, FunctionEnvMut, Memory, MemoryType, Store, Imports}; +//! # fn imports_example(mut ctx: FunctionEnv<()>, mut store: &mut Store) -> Imports { +//! let memory = Memory::new(&mut store, MemoryType::new(1, None, false)).unwrap(); //! imports! { //! "env" => { -//! "my_function" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>| println!("Hello")), +//! "my_function" => Function::new_native(&mut store, &ctx, |_ctx: FunctionEnvMut<()>| println!("Hello")), //! "memory" => memory, //! } //! } @@ -168,12 +167,12 @@ //! from any instance via `instance.exports`: //! //! ``` -//! # use wasmer::{imports, Instance, Function, Memory, TypedFunction, ContextMut}; -//! # fn exports_example(mut ctx: ContextMut<()>, instance: &Instance) -> anyhow::Result<()> { +//! # use wasmer::{imports, Instance, FunctionEnv, Memory, TypedFunction, Store}; +//! # fn exports_example(mut ctx: FunctionEnv<()>, mut store: &mut Store, instance: &Instance) -> anyhow::Result<()> { //! let memory = instance.exports.get_memory("memory")?; //! let memory: &Memory = instance.exports.get("some_other_memory")?; -//! let add: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut ctx, "add")?; -//! let result = add.call(&mut ctx, 5, 37)?; +//! let add: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut store, "add")?; +//! let result = add.call(&mut store, 5, 37)?; //! assert_eq!(result, 42); //! # Ok(()) //! # } @@ -395,7 +394,7 @@ //! i32.const 1 //! i32.add)) //! "#; -//! let store = Store::default(); +//! let mut store = Store::default(); //! let module = Module::new(&store, &module_wat).unwrap(); //! // The module doesn't import anything, so we create an empty import object. //! let import_object = imports! {}; diff --git a/lib/api/src/sys/context.rs b/lib/api/src/sys/context.rs deleted file mode 100644 index 1168fe8049f..00000000000 --- a/lib/api/src/sys/context.rs +++ /dev/null @@ -1,199 +0,0 @@ -use wasmer_vm::ContextObjects; - -use crate::Store; - -/// We require the context to have a fixed memory address for its lifetime since -/// various bits of the VM have raw pointers that point back to it. Hence we -/// wrap the actual context in a box. -pub(crate) struct ContextInner { - pub(crate) objects: ContextObjects, - pub(crate) store: Store, - pub(crate) data: T, -} - -/// A context containing a set of WebAssembly instances, along with host state. -/// -/// All WebAssembly instances must exist within a context. In the majority of -/// cases each instance will have its own context, but it is possible to have -/// multiple instances in a context when these instances need to interact with -/// each other, for example sharing a memory between instances or calling -/// functions in another instance. -/// -/// The lifetimes of run-time WebAssembly objects, notably [`Instance`], -/// [`Memory`], [`Global`], [`Table`] and [`Function`] is tied to a context: -/// the backing memory for these objects is only freed when the context is -/// freed. -/// -/// The `T` generic parameter allows arbitrary data to be attached to a context. -/// This data can be accessed using the [`Context::data`] and -/// [`Context::data_mut`] methods. Host functions defined using -/// [`Function::new`] and [`Function::new_native`] receive -/// a reference to the context when they are called. -pub struct Context { - pub(crate) inner: Box>, -} - -impl Context { - /// Creates a new context with the given host state. - // TODO: Eliminate the Store type and move its functionality into Engine. - pub fn new(store: &Store, data: T) -> Self { - Self { - inner: Box::new(ContextInner { - objects: Default::default(), - store: store.clone(), - data, - }), - } - } - - /// Returns a reference to the host state in this context. - pub fn data(&self) -> &T { - &self.inner.data - } - - /// Returns a mutable- reference to the host state in this context. - pub fn data_mut(&mut self) -> &mut T { - &mut self.inner.data - } - - /// Drops the context and returns the host state that was stored in it. - pub fn into_data(self) -> T { - self.inner.data - } - - /// Returns a reference to the `Store` of this context. - pub fn store(&self) -> &Store { - &self.inner.store - } - - /// For use with the C API - /// # Safety - /// - /// This is unsafe. - pub unsafe fn transmute_data(&mut self) -> &mut Context { - core::mem::transmute::<&mut Self, &mut Context>(self) - } -} - -/// A temporary handle to a [`Context`]. -pub struct ContextRef<'a, T: 'a> { - inner: &'a ContextInner, -} - -impl<'a, T> ContextRef<'a, T> { - /// Returns a reference to the host state in this context. - pub fn data(&self) -> &'a T { - &self.inner.data - } - - /// Returns a reference to the `Store` of this context. - pub fn store(&self) -> &Store { - &self.inner.store - } - - pub(crate) fn objects(&self) -> &'a ContextObjects { - &self.inner.objects - } -} - -/// A temporary handle to a [`Context`]. -pub struct ContextMut<'a, T: 'a> { - inner: &'a mut ContextInner, -} - -impl ContextMut<'_, T> { - /// Returns a reference to the host state in this context. - pub fn data(&self) -> &T { - &self.inner.data - } - - /// Returns a mutable- reference to the host state in this context. - pub fn data_mut(&mut self) -> &mut T { - &mut self.inner.data - } - - pub(crate) fn objects_mut(&mut self) -> &mut ContextObjects { - &mut self.inner.objects - } - - /// Returns a reference to the `Store` of this context. - pub fn store(&self) -> &Store { - &self.inner.store - } - - pub(crate) fn as_raw(&self) -> *mut ContextInner { - self.inner as *const ContextInner as *mut ContextInner - } - - pub(crate) unsafe fn from_raw(raw: *mut ContextInner) -> Self { - Self { inner: &mut *raw } - } -} - -/// Helper trait for a value that is convertible to a [`ContextRef`]. -pub trait AsContextRef { - /// Host state associated with the [`Context`]. - type Data; - - /// Returns a `ContextRef` pointing to the underlying context. - fn as_context_ref(&self) -> ContextRef<'_, Self::Data>; -} - -/// Helper trait for a value that is convertible to a [`ContextMut`]. -pub trait AsContextMut: AsContextRef { - /// Returns a `ContextMut` pointing to the underlying context. - fn as_context_mut(&mut self) -> ContextMut<'_, Self::Data>; -} - -impl AsContextRef for Context { - type Data = T; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - ContextRef { inner: &self.inner } - } -} -impl AsContextMut for Context { - fn as_context_mut(&mut self) -> ContextMut<'_, Self::Data> { - ContextMut { - inner: &mut self.inner, - } - } -} -impl AsContextRef for ContextRef<'_, T> { - type Data = T; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - ContextRef { inner: self.inner } - } -} -impl AsContextRef for ContextMut<'_, T> { - type Data = T; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - ContextRef { inner: self.inner } - } -} -impl AsContextMut for ContextMut<'_, T> { - fn as_context_mut(&mut self) -> ContextMut<'_, Self::Data> { - ContextMut { inner: self.inner } - } -} -impl AsContextRef for &'_ T { - type Data = T::Data; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - T::as_context_ref(*self) - } -} -impl AsContextRef for &'_ mut T { - type Data = T::Data; - - fn as_context_ref(&self) -> ContextRef<'_, Self::Data> { - T::as_context_ref(*self) - } -} -impl AsContextMut for &'_ mut T { - fn as_context_mut(&mut self) -> ContextMut<'_, Self::Data> { - T::as_context_mut(*self) - } -} diff --git a/lib/api/src/sys/exports.rs b/lib/api/src/sys/exports.rs index f9a66d94a19..0a9bce991ba 100644 --- a/lib/api/src/sys/exports.rs +++ b/lib/api/src/sys/exports.rs @@ -1,4 +1,4 @@ -use super::context::AsContextRef; +use super::store::AsStoreRef; use crate::sys::externals::{Extern, Function, Global, Memory, Table}; use crate::sys::native::TypedFunction; use crate::sys::WasmTypeList; @@ -18,16 +18,16 @@ use thiserror::Error; /// /// ```should_panic /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError}; -/// # use wasmer::Context as WasmerContext; -/// # let store = Store::default(); -/// # let mut ctx = WasmerContext::new(&store, ()); +/// # use wasmer::FunctionEnv; +/// # let mut store = Store::default(); +/// # let env = FunctionEnv::new(&mut store, ()); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (global $one (export "glob") f32 (f32.const 1))) /// # "#.as_bytes()).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let import_object = imports! {}; -/// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); +/// # let instance = Instance::new(&mut store, &module, &import_object).unwrap(); /// # /// // This results with an error: `ExportError::IncompatibleType`. /// let export = instance.exports.get_function("glob").unwrap(); @@ -37,13 +37,13 @@ use thiserror::Error; /// /// ```should_panic /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError}; -/// # use wasmer::Context as WasmerContext; -/// # let store = Store::default(); -/// # let mut ctx = WasmerContext::new(&store, ()); +/// # use wasmer::FunctionEnv; +/// # let mut store = Store::default(); +/// # let env = FunctionEnv::new(&mut store, ()); /// # let wasm_bytes = wat2wasm("(module)".as_bytes()).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let import_object = imports! {}; -/// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); +/// # let instance = Instance::new(&mut store, &module, &import_object).unwrap(); /// # /// // This results with an error: `ExportError::Missing`. /// let export = instance.exports.get_function("unknown").unwrap(); @@ -145,7 +145,7 @@ impl Exports { /// Get an export as a `TypedFunction`. pub fn get_native_function( &self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, name: &str, ) -> Result, ExportError> where @@ -158,7 +158,7 @@ impl Exports { /// Get an export as a `TypedFunction`. pub fn get_typed_function( &self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, name: &str, ) -> Result, ExportError> where diff --git a/lib/api/src/sys/extern_ref.rs b/lib/api/src/sys/extern_ref.rs index 33ff1da3475..c3ca736a710 100644 --- a/lib/api/src/sys/extern_ref.rs +++ b/lib/api/src/sys/extern_ref.rs @@ -1,34 +1,34 @@ use std::any::Any; -use wasmer_vm::{ContextHandle, VMExternObj, VMExternRef}; +use wasmer_vm::{StoreHandle, VMExternObj, VMExternRef}; -use super::context::{AsContextMut, AsContextRef}; +use super::store::{AsStoreMut, AsStoreRef}; #[derive(Debug, Clone)] #[repr(transparent)] /// An opaque reference to some data. This reference can be passed through Wasm. pub struct ExternRef { - handle: ContextHandle, + handle: StoreHandle, } impl ExternRef { /// Make a new extern reference - pub fn new(ctx: &mut impl AsContextMut, value: T) -> Self + pub fn new(ctx: &mut impl AsStoreMut, value: T) -> Self where T: Any + Send + Sync + 'static + Sized, { Self { - handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), VMExternObj::new(value)), + handle: StoreHandle::new(ctx.objects_mut(), VMExternObj::new(value)), } } /// Try to downcast to the given value. - pub fn downcast<'a, T>(&self, ctx: &'a impl AsContextRef) -> Option<&'a T> + pub fn downcast<'a, T>(&self, ctx: &'a impl AsStoreRef) -> Option<&'a T> where T: Any + Send + Sync + 'static + Sized, { self.handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .as_ref() .downcast_ref::() } @@ -38,14 +38,11 @@ impl ExternRef { } pub(crate) unsafe fn from_vm_externref( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, vm_externref: VMExternRef, ) -> Self { Self { - handle: ContextHandle::from_internal( - ctx.as_context_mut().objects_mut().id(), - vm_externref.0, - ), + handle: StoreHandle::from_internal(ctx.objects_mut().id(), vm_externref.0), } } @@ -56,7 +53,7 @@ impl ExternRef { /// /// Externref and funcref values are tied to a context and can only be used /// with that context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { + self.handle.store_id() == ctx.as_store_ref().objects().id() } } diff --git a/lib/api/src/sys/externals/function.rs b/lib/api/src/sys/externals/function.rs index d6c6cf8a8c1..7c21ee747e7 100644 --- a/lib/api/src/sys/externals/function.rs +++ b/lib/api/src/sys/externals/function.rs @@ -1,11 +1,11 @@ -use crate::sys::context::{AsContextMut, AsContextRef, ContextInner, ContextMut}; use crate::sys::exports::{ExportError, Exportable}; use crate::sys::externals::Extern; +use crate::sys::store::{AsStoreMut, AsStoreRef, StoreInner, StoreMut}; use crate::sys::FunctionType; use crate::sys::RuntimeError; use crate::sys::TypedFunction; -use crate::Value; +use crate::{FunctionEnv, FunctionEnvMut, Value}; use inner::StaticFunction; pub use inner::{FromToNativeWasmType, HostFunction, WasmTypeList}; use std::cell::UnsafeCell; @@ -13,10 +13,10 @@ use std::cmp::max; use std::ffi::c_void; use wasmer_types::RawValue; use wasmer_vm::{ - on_host_stack, raise_user_trap, resume_panic, wasmer_call_trampoline, ContextHandle, - InternalContextHandle, MaybeInstanceOwned, VMCallerCheckedAnyfunc, VMContext, - VMDynamicFunctionContext, VMExtern, VMFuncRef, VMFunction, VMFunctionBody, - VMFunctionEnvironment, VMFunctionKind, VMTrampoline, + on_host_stack, raise_user_trap, resume_panic, wasmer_call_trampoline, InternalStoreHandle, + MaybeInstanceOwned, StoreHandle, VMCallerCheckedAnyfunc, VMContext, VMDynamicFunctionContext, + VMExtern, VMFuncRef, VMFunction, VMFunctionBody, VMFunctionContext, VMFunctionKind, + VMTrampoline, }; /// A WebAssembly `function` instance. @@ -38,7 +38,7 @@ use wasmer_vm::{ /// [Closures as host functions tracking issue](https://github.com/wasmerio/wasmer/issues/1840) #[derive(Debug, Clone)] pub struct Function { - pub(crate) handle: ContextHandle, + pub(crate) handle: StoreHandle, } impl Function { @@ -50,14 +50,13 @@ impl Function { /// # Examples /// /// ``` - /// # use wasmer::{Function, FunctionType, Type, Store, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::{Function, FunctionEnv, FunctionType, Type, Store, Value}; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # /// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]); /// - /// let f = Function::new(&mut ctx, &signature, |_ctx, args| { + /// let f = Function::new(&mut store, &env, &signature, |_ctx, args| { /// let sum = args[0].unwrap_i32() + args[1].unwrap_i32(); /// Ok(vec![Value::I32(sum)]) /// }); @@ -66,38 +65,47 @@ impl Function { /// With constant signature: /// /// ``` - /// # use wasmer::{Function, FunctionType, Type, Store, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::{Function, FunctionEnv, FunctionType, Type, Store, Value}; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # /// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]); /// - /// let f = Function::new(&mut ctx, I32_I32_TO_I32, |_ctx, args| { + /// let f = Function::new(&mut store, &env, I32_I32_TO_I32, |_ctx, args| { /// let sum = args[0].unwrap_i32() + args[1].unwrap_i32(); /// Ok(vec![Value::I32(sum)]) /// }); /// ``` - pub fn new(ctx: &mut impl AsContextMut, ty: FT, func: F) -> Self + pub fn new( + store: &mut impl AsStoreMut, + env: &FunctionEnv, + ty: FT, + func: F, + ) -> Self where FT: Into, - F: Fn(ContextMut<'_, T>, &[Value]) -> Result, RuntimeError> + F: Fn(FunctionEnvMut, &[Value]) -> Result, RuntimeError> + 'static + Send + Sync, { - let mut ctx = ctx.as_context_mut(); let function_type = ty.into(); let func_ty = function_type.clone(); - let raw_ctx = ctx.as_raw() as *mut u8; + let func_env = env.clone(); + let raw_store = store.as_store_mut().as_raw() as *mut u8; let wrapper = move |values_vec: *mut RawValue| -> Result<(), RuntimeError> { unsafe { - let mut ctx = ContextMut::from_raw(raw_ctx as *mut ContextInner); + let mut store = StoreMut::from_raw(raw_store as *mut StoreInner); let mut args = Vec::with_capacity(func_ty.params().len()); for (i, ty) in func_ty.params().iter().enumerate() { - args.push(Value::from_raw(&mut ctx, *ty, *values_vec.add(i))); + args.push(Value::from_raw(&mut store, *ty, *values_vec.add(i))); } - let returns = func(ctx.as_context_mut(), &args)?; + let store_mut = StoreMut::from_raw(raw_store as *mut StoreInner); + let env = FunctionEnvMut { + store_mut, + func_env: func_env.clone(), + }; + let returns = func(env, &args)?; // We need to dynamically check that the returns // match the expected types, as well as expected length. @@ -110,7 +118,7 @@ impl Function { ))); } for (i, ret) in returns.iter().enumerate() { - *values_vec.add(i) = ret.as_raw(&ctx); + *values_vec.add(i) = ret.as_raw(&store); } } Ok(()) @@ -125,8 +133,11 @@ impl Function { // The engine linker will replace the address with one pointing to a // generated dynamic trampoline. let func_ptr = std::ptr::null() as *const VMFunctionBody; - let type_index = ctx.store().engine().register_signature(&function_type); - let vmctx = VMFunctionEnvironment { + let type_index = store + .as_store_mut() + .engine() + .register_signature(&function_type); + let vmctx = VMFunctionContext { host_env: host_data.as_ref() as *const _ as *mut c_void, }; let call_trampoline = host_data.ctx.call_trampoline_address(); @@ -144,7 +155,7 @@ impl Function { host_data, }; Self { - handle: ContextHandle::new(ctx.objects_mut(), vm_function), + handle: StoreHandle::new(store.as_store_mut().objects_mut(), vm_function), } } @@ -156,33 +167,41 @@ impl Function { /// # Example /// /// ``` - /// # use wasmer::{ContextMut, Store, Function}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::{Store, Function, FunctionEnv, FunctionEnvMut}; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # - /// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 { + /// fn sum(_ctx: FunctionEnvMut<()>, a: i32, b: i32) -> i32 { /// a + b /// } /// - /// let f = Function::new_native(&mut ctx, sum); + /// let f = Function::new_native(&mut store, &env, sum); /// ``` - pub fn new_native(ctx: &mut impl AsContextMut, func: F) -> Self + pub fn new_native( + store: &mut impl AsStoreMut, + env: &FunctionEnv, + func: F, + ) -> Self where F: HostFunction + 'static + Send + Sync, Args: WasmTypeList, Rets: WasmTypeList, { - let mut ctx = ctx.as_context_mut(); + // println!("new native {:p}", &new_ctx); + let host_data = Box::new(StaticFunction { - raw_ctx: ctx.as_raw() as *mut u8, + raw_store: store.as_store_mut().as_raw() as *mut u8, + env: env.clone(), func, }); let function_type = FunctionType::new(Args::wasm_types(), Rets::wasm_types()); let func_ptr = >::function_body_ptr(); - let type_index = ctx.store().engine().register_signature(&function_type); - let vmctx = VMFunctionEnvironment { + let type_index = store + .as_store_mut() + .engine() + .register_signature(&function_type); + let vmctx = VMFunctionContext { host_env: host_data.as_ref() as *const _ as *mut c_void, }; let call_trampoline = >::call_trampoline_address(); @@ -200,7 +219,7 @@ impl Function { host_data, }; Self { - handle: ContextHandle::new(ctx.objects_mut(), vm_function), + handle: StoreHandle::new(store.as_store_mut().objects_mut(), vm_function), } } @@ -209,30 +228,29 @@ impl Function { /// # Example /// /// ``` - /// # use wasmer::{ContextMut, Function, Store, Type}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::{Function, FunctionEnv, FunctionEnvMut, Store, Type}; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # - /// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 { + /// fn sum(_ctx: FunctionEnvMut<()>, a: i32, b: i32) -> i32 { /// a + b /// } /// - /// let f = Function::new_native(&mut ctx, sum); + /// let f = Function::new_native(&mut store, &env, sum); /// - /// assert_eq!(f.ty(&mut ctx).params(), vec![Type::I32, Type::I32]); - /// assert_eq!(f.ty(&mut ctx).results(), vec![Type::I32]); + /// assert_eq!(f.ty(&mut store).params(), vec![Type::I32, Type::I32]); + /// assert_eq!(f.ty(&mut store).results(), vec![Type::I32]); /// ``` - pub fn ty(&self, ctx: &impl AsContextRef) -> FunctionType { + pub fn ty(&self, store: &impl AsStoreRef) -> FunctionType { self.handle - .get(ctx.as_context_ref().objects()) + .get(store.as_store_ref().objects()) .signature .clone() } fn call_wasm( &self, - ctx: &mut impl AsContextMut, + store: &mut impl AsStoreMut, trampoline: VMTrampoline, params: &[Value], results: &mut [Value], @@ -245,7 +263,7 @@ impl Function { .join(", ") }; // TODO: Avoid cloning the signature here, it's expensive. - let signature = self.ty(ctx); + let signature = self.ty(store); if signature.params().len() != params.len() { return Err(RuntimeError::new(format!( "Parameters of type [{}] did not match signature {}", @@ -273,19 +291,19 @@ impl Function { param_types, &signature, ))); } - if !arg.is_from_context(ctx) { + if !arg.is_from_store(store) { return Err(RuntimeError::new( "cross-`Context` values are not supported", )); } - *slot = arg.as_raw(ctx); + *slot = arg.as_raw(store); } // Call the trampoline. - let vm_function = self.handle.get(ctx.as_context_ref().objects()); + let vm_function = self.handle.get(store.as_store_ref().objects()); if let Err(error) = unsafe { wasmer_call_trampoline( - ctx.as_context_ref().store(), + store.as_store_ref().signal_handler(), vm_function.anyfunc.as_ptr().as_ref().vmctx, trampoline, vm_function.anyfunc.as_ptr().as_ref().func_ptr, @@ -298,7 +316,7 @@ impl Function { // Load the return values out of `values_vec`. for (index, &value_type) in signature.results().iter().enumerate() { unsafe { - results[index] = Value::from_raw(ctx, value_type, values_vec[index]); + results[index] = Value::from_raw(store, value_type, values_vec[index]); } } @@ -310,21 +328,20 @@ impl Function { /// # Example /// /// ``` - /// # use wasmer::{ContextMut, Function, Store, Type}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::{Function, FunctionEnv, FunctionEnvMut, Store, Type}; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # - /// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 { + /// fn sum(_ctx: FunctionEnvMut<()>, a: i32, b: i32) -> i32 { /// a + b /// } /// - /// let f = Function::new_native(&mut ctx, sum); + /// let f = Function::new_native(&mut store, &env, sum); /// - /// assert_eq!(f.param_arity(&mut ctx), 2); + /// assert_eq!(f.param_arity(&mut store), 2); /// ``` - pub fn param_arity(&self, ctx: &impl AsContextRef) -> usize { - self.ty(ctx).params().len() + pub fn param_arity(&self, store: &impl AsStoreRef) -> usize { + self.ty(store).params().len() } /// Returns the number of results this function produces. @@ -332,21 +349,20 @@ impl Function { /// # Example /// /// ``` - /// # use wasmer::{ContextMut, Function, Store, Type}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::{Function, FunctionEnv, FunctionEnvMut, Store, Type}; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # - /// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 { + /// fn sum(_ctx: FunctionEnvMut<()>, a: i32, b: i32) -> i32 { /// a + b /// } /// - /// let f = Function::new_native(&mut ctx, sum); + /// let f = Function::new_native(&mut store, &env, sum); /// - /// assert_eq!(f.result_arity(&mut ctx), 1); + /// assert_eq!(f.result_arity(&mut store), 1); /// ``` - pub fn result_arity(&self, ctx: &impl AsContextRef) -> usize { - self.ty(ctx).results().len() + pub fn result_arity(&self, store: &impl AsStoreRef) -> usize { + self.ty(store).results().len() } /// Call the `Function` function. @@ -361,9 +377,9 @@ impl Function { /// /// ``` /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::FunctionEnv; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) @@ -374,42 +390,41 @@ impl Function { /// # "#.as_bytes()).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let import_object = imports! {}; - /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + /// # let instance = Instance::new(&mut store, &module, &import_object).unwrap(); /// # /// let sum = instance.exports.get_function("sum").unwrap(); /// - /// assert_eq!(sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]); + /// assert_eq!(sum.call(&mut store, &[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]); /// ``` pub fn call( &self, - ctx: &mut impl AsContextMut, + store: &mut impl AsStoreMut, params: &[Value], ) -> Result, RuntimeError> { let trampoline = unsafe { self.handle - .get(ctx.as_context_ref().objects()) + .get(store.as_store_ref().objects()) .anyfunc .as_ptr() .as_ref() .call_trampoline }; - let mut results = vec![Value::null(); self.result_arity(ctx)]; - self.call_wasm(ctx, trampoline, params, &mut results)?; + let mut results = vec![Value::null(); self.result_arity(store)]; + self.call_wasm(store, trampoline, params, &mut results)?; Ok(results.into_boxed_slice()) } - pub(crate) fn vm_funcref(&self, ctx: &impl AsContextRef) -> VMFuncRef { - let vm_function = self.handle.get(ctx.as_context_ref().objects()); + pub(crate) fn vm_funcref(&self, store: &impl AsStoreRef) -> VMFuncRef { + let vm_function = self.handle.get(store.as_store_ref().objects()); if vm_function.kind == VMFunctionKind::Dynamic { panic!("dynamic functions cannot be used in tables or as funcrefs"); } VMFuncRef(vm_function.anyfunc.as_ptr()) } - pub(crate) unsafe fn from_vm_funcref(ctx: &mut impl AsContextMut, funcref: VMFuncRef) -> Self { - let signature = ctx - .as_context_mut() - .store() + pub(crate) unsafe fn from_vm_funcref(store: &mut impl AsStoreMut, funcref: VMFuncRef) -> Self { + let signature = store + .as_store_ref() .engine() .lookup_signature(funcref.0.as_ref().type_index) .expect("Signature not found in store"); @@ -422,7 +437,7 @@ impl Function { host_data: Box::new(()), }; Self { - handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_function), + handle: StoreHandle::new(store.as_store_mut().objects_mut(), vm_function), } } @@ -433,9 +448,9 @@ impl Function { /// /// ``` /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::FunctionEnv; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) @@ -446,12 +461,12 @@ impl Function { /// # "#.as_bytes()).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let import_object = imports! {}; - /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + /// # let instance = Instance::new(&mut store, &module, &import_object).unwrap(); /// # /// let sum = instance.exports.get_function("sum").unwrap(); - /// let sum_native: TypedFunction<(i32, i32), i32> = sum.native(&mut ctx).unwrap(); + /// let sum_native: TypedFunction<(i32, i32), i32> = sum.native(&mut store).unwrap(); /// - /// assert_eq!(sum_native.call(&mut ctx, 1, 2).unwrap(), 3); + /// assert_eq!(sum_native.call(&mut store, 1, 2).unwrap(), 3); /// ``` /// /// # Errors @@ -461,9 +476,9 @@ impl Function { /// /// ```should_panic /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::FunctionEnv; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) @@ -474,12 +489,12 @@ impl Function { /// # "#.as_bytes()).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let import_object = imports! {}; - /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + /// # let instance = Instance::new(&mut store, &module, &import_object).unwrap(); /// # /// let sum = instance.exports.get_function("sum").unwrap(); /// /// // This results in an error: `RuntimeError` - /// let sum_native : TypedFunction<(i64, i64), i32> = sum.native(&mut ctx).unwrap(); + /// let sum_native : TypedFunction<(i64, i64), i32> = sum.native(&mut store).unwrap(); /// ``` /// /// If the `Rets` generic parameter does not match the exported function @@ -487,9 +502,9 @@ impl Function { /// /// ```should_panic /// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::FunctionEnv; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # let wasm_bytes = wat2wasm(r#" /// # (module /// # (func (export "sum") (param $x i32) (param $y i32) (result i32) @@ -500,22 +515,22 @@ impl Function { /// # "#.as_bytes()).unwrap(); /// # let module = Module::new(&store, wasm_bytes).unwrap(); /// # let import_object = imports! {}; - /// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + /// # let instance = Instance::new(&mut store, &module, &import_object).unwrap(); /// # /// let sum = instance.exports.get_function("sum").unwrap(); /// /// // This results in an error: `RuntimeError` - /// let sum_native: TypedFunction<(i32, i32), i64> = sum.native(&mut ctx).unwrap(); + /// let sum_native: TypedFunction<(i32, i32), i64> = sum.native(&mut store).unwrap(); /// ``` pub fn native( &self, - ctx: &impl AsContextRef, + store: &impl AsStoreRef, ) -> Result, RuntimeError> where Args: WasmTypeList, Rets: WasmTypeList, { - let vm_function = self.handle.get(ctx.as_context_ref().objects()); + let vm_function = self.handle.get(store.as_store_ref().objects()); // type check { @@ -549,19 +564,19 @@ impl Function { } pub(crate) fn from_vm_extern( - ctx: &mut impl AsContextMut, - internal: InternalContextHandle, + store: &mut impl AsStoreMut, + internal: InternalStoreHandle, ) -> Self { Self { handle: unsafe { - ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal) + StoreHandle::from_internal(store.as_store_ref().objects().id(), internal) }, } } - /// Checks whether this `Function` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + /// Checks whether this `Function` can be used with the given store. + pub fn is_from_store(&self, store: &impl AsStoreRef) -> bool { + self.handle.store_id() == store.as_store_ref().objects().id() } pub(crate) fn to_vm_extern(&self) -> VMExtern { @@ -590,10 +605,11 @@ where // This function wraps our func, to make it compatible with the // reverse trampoline signature unsafe extern "C" fn func_wrapper( - this: &VMDynamicFunctionContext, + this: &mut VMDynamicFunctionContext, values_vec: *mut RawValue, ) { use std::panic::{self, AssertUnwindSafe}; + let result = on_host_stack(|| panic::catch_unwind(AssertUnwindSafe(|| (this.ctx.func)(values_vec)))); @@ -633,12 +649,12 @@ mod inner { use std::panic::{self, AssertUnwindSafe}; use wasmer_vm::{on_host_stack, VMContext, VMTrampoline}; + use crate::sys::function_env::FunctionEnvMut; use wasmer_types::{NativeWasmType, RawValue, Type}; use wasmer_vm::{raise_user_trap, resume_panic, VMFunctionBody}; - use crate::sys::context::{ContextInner, ContextMut}; use crate::sys::NativeWasmTypeInto; - use crate::{AsContextMut, AsContextRef, ExternRef, Function}; + use crate::{AsStoreMut, AsStoreRef, ExternRef, Function, FunctionEnv, StoreMut}; /// A trait to convert a Rust value to a `WasmNativeType` value, /// or to convert `WasmNativeType` value to a Rust value. @@ -674,11 +690,11 @@ mod inner { /// `Self::Native` type. fn to_native(self) -> Self::Native; - /// Returns whether the given value is from the given context. + /// Returns whether the given value is from the given store. /// /// This always returns true for primitive types that can be used with /// any context. - fn is_from_context(&self, _ctx: &impl AsContextRef) -> bool { + fn is_from_store(&self, _ctx: &impl AsStoreRef) -> bool { true } } @@ -750,8 +766,8 @@ mod inner { fn from_native(n: Self::Native) -> Self { n } - fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.as_ref().map_or(true, |e| e.is_from_context(ctx)) + fn is_from_store(&self, store: &impl AsStoreRef) -> bool { + self.as_ref().map_or(true, |e| e.is_from_store(store)) } } @@ -764,8 +780,8 @@ mod inner { fn from_native(n: Self::Native) -> Self { n } - fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.as_ref().map_or(true, |f| f.is_from_context(ctx)) + fn is_from_store(&self, store: &impl AsStoreRef) -> bool { + self.as_ref().map_or(true, |f| f.is_from_store(store)) } } @@ -812,7 +828,7 @@ mod inner { /// Constructs `Self` based on an array of values. /// /// # Safety - unsafe fn from_array(ctx: &mut impl AsContextMut, array: Self::Array) -> Self; + unsafe fn from_array(ctx: &mut impl AsStoreMut, array: Self::Array) -> Self; /// Constructs `Self` based on a slice of values. /// @@ -823,7 +839,7 @@ mod inner { /// /// # Safety unsafe fn from_slice( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, slice: &[RawValue], ) -> Result; @@ -831,7 +847,7 @@ mod inner { /// (list) of values. /// /// # Safety - unsafe fn into_array(self, ctx: &mut impl AsContextMut) -> Self::Array; + unsafe fn into_array(self, store: &mut impl AsStoreMut) -> Self::Array; /// Allocates and return an empty array of type `Array` that /// will hold a tuple (list) of values, usually to hold the @@ -842,13 +858,13 @@ mod inner { /// `CStruct`. /// /// # Safety - unsafe fn from_c_struct(ctx: &mut impl AsContextMut, c_struct: Self::CStruct) -> Self; + unsafe fn from_c_struct(store: &mut impl AsStoreMut, c_struct: Self::CStruct) -> Self; /// Builds and returns a C struct of type `CStruct` from a /// tuple (list) of values. /// /// # Safety - unsafe fn into_c_struct(self, ctx: &mut impl AsContextMut) -> Self::CStruct; + unsafe fn into_c_struct(self, store: &mut impl AsStoreMut) -> Self::CStruct; /// Writes the contents of a C struct to an array of `RawValue`. /// @@ -963,8 +979,9 @@ mod inner { /// Represents a low-level Wasm static host function. See /// `super::Function::new_native` to learn more. - pub(crate) struct StaticFunction { - pub(crate) raw_ctx: *mut u8, + pub(crate) struct StaticFunction { + pub(crate) raw_store: *mut u8, + pub(crate) env: FunctionEnv, pub(crate) func: F, } @@ -996,7 +1013,7 @@ mod inner { #[allow(unused_mut)] #[allow(clippy::unused_unit)] #[allow(clippy::missing_safety_doc)] - unsafe fn from_array(mut _ctx: &mut impl AsContextMut, array: Self::Array) -> Self { + unsafe fn from_array(mut _store: &mut impl AsStoreMut, array: Self::Array) -> Self { // Unpack items of the array. #[allow(non_snake_case)] let [ $( $x ),* ] = array; @@ -1004,19 +1021,19 @@ mod inner { // Build the tuple. ( $( - FromToNativeWasmType::from_native(NativeWasmTypeInto::from_raw(_ctx, $x)) + FromToNativeWasmType::from_native(NativeWasmTypeInto::from_raw(_store, $x)) ),* ) } #[allow(clippy::missing_safety_doc)] - unsafe fn from_slice(ctx: &mut impl AsContextMut, slice: &[RawValue]) -> Result { - Ok(Self::from_array(ctx, slice.try_into()?)) + unsafe fn from_slice(store: &mut impl AsStoreMut, slice: &[RawValue]) -> Result { + Ok(Self::from_array(store, slice.try_into()?)) } #[allow(unused_mut)] #[allow(clippy::missing_safety_doc)] - unsafe fn into_array(self, mut _ctx: &mut impl AsContextMut) -> Self::Array { + unsafe fn into_array(self, mut _store: &mut impl AsStoreMut) -> Self::Array { // Unpack items of the tuple. #[allow(non_snake_case)] let ( $( $x ),* ) = self; @@ -1024,7 +1041,7 @@ mod inner { // Build the array. [ $( - FromToNativeWasmType::to_native($x).into_raw(_ctx) + FromToNativeWasmType::to_native($x).into_raw(_store) ),* ] } @@ -1037,28 +1054,28 @@ mod inner { #[allow(unused_mut)] #[allow(clippy::unused_unit)] #[allow(clippy::missing_safety_doc)] - unsafe fn from_c_struct(mut _ctx: &mut impl AsContextMut, c_struct: Self::CStruct) -> Self { + unsafe fn from_c_struct(mut _store: &mut impl AsStoreMut, c_struct: Self::CStruct) -> Self { // Unpack items of the C structure. #[allow(non_snake_case)] let $c_struct_name( $( $x ),* ) = c_struct; ( $( - FromToNativeWasmType::from_native(NativeWasmTypeInto::from_abi(_ctx, $x)) + FromToNativeWasmType::from_native(NativeWasmTypeInto::from_abi(_store, $x)) ),* ) } #[allow(unused_parens, non_snake_case, unused_mut)] #[allow(clippy::missing_safety_doc)] - unsafe fn into_c_struct(self, mut _ctx: &mut impl AsContextMut) -> Self::CStruct { + unsafe fn into_c_struct(self, mut _store: &mut impl AsStoreMut) -> Self::CStruct { // Unpack items of the tuple. let ( $( $x ),* ) = self; // Build the C structure. $c_struct_name( $( - FromToNativeWasmType::to_native($x).into_abi(_ctx) + FromToNativeWasmType::to_native($x).into_abi(_store) ),* ) } @@ -1086,7 +1103,7 @@ mod inner { // Implement `HostFunction` for a function that has the same arity than the tuple. #[allow(unused_parens)] - impl< $( $x, )* Rets, RetsAsResult, T, Func > + impl< $( $x, )* Rets, RetsAsResult, T: Send + 'static, Func > HostFunction for Func @@ -1094,33 +1111,41 @@ mod inner { $( $x: FromToNativeWasmType, )* Rets: WasmTypeList, RetsAsResult: IntoResult, - Func: Fn(ContextMut<'_, T>, $( $x , )*) -> RetsAsResult + 'static, + Func: Fn(FunctionEnvMut, $( $x , )*) -> RetsAsResult + 'static, { #[allow(non_snake_case)] fn function_body_ptr() -> *const VMFunctionBody { /// This is a function that wraps the real host /// function. Its address will be used inside the /// runtime. - unsafe extern "C" fn func_wrapper( env: &StaticFunction, $( $x: <$x::Native as NativeWasmType>::Abi, )* ) -> Rets::CStruct + unsafe extern "C" fn func_wrapper( env: &StaticFunction, $( $x: <$x::Native as NativeWasmType>::Abi, )* ) -> Rets::CStruct where $( $x: FromToNativeWasmType, )* Rets: WasmTypeList, RetsAsResult: IntoResult, - Func: Fn(ContextMut<'_, T>, $( $x , )*) -> RetsAsResult + 'static, + Func: Fn(FunctionEnvMut, $( $x , )*) -> RetsAsResult + 'static, { - let mut ctx = ContextMut::from_raw(env.raw_ctx as *mut ContextInner); - + // println!("func wrapper"); + let mut store = StoreMut::from_raw(env.raw_store as *mut _); let result = on_host_stack(|| { + // println!("func wrapper1"); panic::catch_unwind(AssertUnwindSafe(|| { $( - let $x = FromToNativeWasmType::from_native(NativeWasmTypeInto::from_abi(&mut ctx, $x)); + let $x = FromToNativeWasmType::from_native(NativeWasmTypeInto::from_abi(&mut store, $x)); )* - (env.func)(ctx.as_context_mut(), $($x),* ).into_result() + // println!("func wrapper2 {:p}", *env.raw_ctx); + let store_mut = StoreMut::from_raw(env.raw_store as *mut _); + let f_env = FunctionEnvMut { + store_mut, + func_env: env.env.clone(), + }; + // println!("func wrapper3"); + (env.func)(f_env, $($x),* ).into_result() })) }); match result { - Ok(Ok(result)) => return result.into_c_struct(&mut ctx), + Ok(Ok(result)) => return result.into_c_struct(&mut store), Ok(Err(trap)) => raise_user_trap(Box::new(trap)), Err(panic) => resume_panic(panic) , } @@ -1212,18 +1237,18 @@ mod inner { type CStruct = Self; type Array = [RawValue; 0]; - unsafe fn from_array(_: &mut impl AsContextMut, _: Self::Array) -> Self { + unsafe fn from_array(_: &mut impl AsStoreMut, _: Self::Array) -> Self { unreachable!() } unsafe fn from_slice( - _: &mut impl AsContextMut, + _: &mut impl AsStoreMut, _: &[RawValue], ) -> Result { unreachable!() } - unsafe fn into_array(self, _: &mut impl AsContextMut) -> Self::Array { + unsafe fn into_array(self, _: &mut impl AsStoreMut) -> Self::Array { [] } @@ -1231,11 +1256,11 @@ mod inner { [] } - unsafe fn from_c_struct(_: &mut impl AsContextMut, self_: Self::CStruct) -> Self { + unsafe fn from_c_struct(_: &mut impl AsStoreMut, self_: Self::CStruct) -> Self { self_ } - unsafe fn into_c_struct(self, _: &mut impl AsContextMut) -> Self::CStruct { + unsafe fn into_c_struct(self, _: &mut impl AsStoreMut) -> Self::CStruct { self } @@ -1249,14 +1274,12 @@ mod inner { #[cfg(test)] mod test_wasm_type_list { use super::*; - use crate::Context as WasmerContext; - use crate::Store; use wasmer_types::Type; /* #[test] fn test_from_array() { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); assert_eq!(<()>::from_array(&mut ctx, []), ()); assert_eq!(::from_array(&mut ctx, [RawValue{i32: 1}]), (1i32)); assert_eq!(<(i32, i64)>::from_array(&mut ctx, [RawValue{i32:1}, RawValue{i64:2}]), (1i32, 2i64)); @@ -1273,8 +1296,8 @@ mod inner { #[test] fn test_into_array() { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); assert_eq!(().into_array(&mut ctx), [0i128; 0]); assert_eq!((1i32).into_array(&mut ctx), [1i32]); assert_eq!((1i32, 2i64).into_array(&mut ctx), [RawValue{i32: 1}, RawValue{i64: 2}]); @@ -1293,8 +1316,8 @@ mod inner { /* #[test] fn test_from_c_struct() { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); assert_eq!(<()>::from_c_struct(&mut ctx, S0()), ()); assert_eq!(::from_c_struct(&mut ctx, S1(1)), (1i32)); assert_eq!(<(i32, i64)>::from_c_struct(&mut ctx, S2(1, 2)), (1i32, 2i64)); @@ -1331,7 +1354,7 @@ mod inner { mod test_function { use super::*; use crate::Store; - use crate::Context as WasmerContext; + use crate::FunctionEnv; use wasmer_types::Type; fn func() {} @@ -1354,15 +1377,15 @@ mod inner { #[test] fn test_function_types() { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); use wasmer_types::FunctionType; assert_eq!( - StaticFunction::new(func).ty(&mut ctx), + StaticFunction::new(func).ty(&mut store), FunctionType::new(vec![], vec![]) ); assert_eq!( - StaticFunction::new(func__i32).ty(&mut ctx), + StaticFunction::new(func__i32).ty(&mut store), FunctionType::new(vec![], vec![Type::I32]) ); assert_eq!( diff --git a/lib/api/src/sys/externals/global.rs b/lib/api/src/sys/externals/global.rs index 627325f4d16..108d256d08e 100644 --- a/lib/api/src/sys/externals/global.rs +++ b/lib/api/src/sys/externals/global.rs @@ -1,11 +1,11 @@ -use crate::sys::context::{AsContextMut, AsContextRef}; use crate::sys::exports::{ExportError, Exportable}; use crate::sys::externals::Extern; +use crate::sys::store::{AsStoreMut, AsStoreRef}; use crate::sys::value::Value; use crate::sys::GlobalType; use crate::sys::Mutability; use crate::sys::RuntimeError; -use wasmer_vm::{ContextHandle, InternalContextHandle, VMExtern, VMGlobal}; +use wasmer_vm::{InternalStoreHandle, StoreHandle, VMExtern, VMGlobal}; /// A WebAssembly `global` instance. /// @@ -15,7 +15,7 @@ use wasmer_vm::{ContextHandle, InternalContextHandle, VMExtern, VMGlobal}; /// Spec: #[derive(Debug, Clone)] pub struct Global { - handle: ContextHandle, + handle: StoreHandle, } impl Global { @@ -25,16 +25,14 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Mutability, Store, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let g = Global::new(&mut ctx, Value::I32(1)); + /// let g = Global::new(&mut store, Value::I32(1)); /// - /// assert_eq!(g.get(&mut ctx), Value::I32(1)); - /// assert_eq!(g.ty(&mut ctx).mutability, Mutability::Const); + /// assert_eq!(g.get(&mut store), Value::I32(1)); + /// assert_eq!(g.ty(&mut store).mutability, Mutability::Const); /// ``` - pub fn new(ctx: &mut impl AsContextMut, val: Value) -> Self { + pub fn new(ctx: &mut impl AsStoreMut, val: Value) -> Self { Self::from_value(ctx, val, Mutability::Const).unwrap() } @@ -44,26 +42,24 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Mutability, Store, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let g = Global::new_mut(&mut ctx, Value::I32(1)); + /// let g = Global::new_mut(&mut store, Value::I32(1)); /// - /// assert_eq!(g.get(&mut ctx), Value::I32(1)); - /// assert_eq!(g.ty(&mut ctx).mutability, Mutability::Var); + /// assert_eq!(g.get(&mut store), Value::I32(1)); + /// assert_eq!(g.ty(&mut store).mutability, Mutability::Var); /// ``` - pub fn new_mut(ctx: &mut impl AsContextMut, val: Value) -> Self { + pub fn new_mut(ctx: &mut impl AsStoreMut, val: Value) -> Self { Self::from_value(ctx, val, Mutability::Var).unwrap() } /// Create a `Global` with the initial value [`Val`] and the provided [`Mutability`]. fn from_value( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, val: Value, mutability: Mutability, ) -> Result { - if !val.is_from_context(ctx) { + if !val.is_from_store(ctx) { return Err(RuntimeError::new( "cross-`Context` values are not supported", )); @@ -77,7 +73,7 @@ impl Global { } Ok(Self { - handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), global), + handle: StoreHandle::new(ctx.objects_mut(), global), }) } @@ -87,18 +83,16 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Mutability, Store, Type, Value, GlobalType}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let c = Global::new(&mut ctx, Value::I32(1)); - /// let v = Global::new_mut(&mut ctx, Value::I64(1)); + /// let c = Global::new(&mut store, Value::I32(1)); + /// let v = Global::new_mut(&mut store, Value::I64(1)); /// - /// assert_eq!(c.ty(&mut ctx), GlobalType::new(Type::I32, Mutability::Const)); - /// assert_eq!(v.ty(&mut ctx), GlobalType::new(Type::I64, Mutability::Var)); + /// assert_eq!(c.ty(&mut store), GlobalType::new(Type::I32, Mutability::Const)); + /// assert_eq!(v.ty(&mut store), GlobalType::new(Type::I64, Mutability::Var)); /// ``` - pub fn ty(&self, ctx: &impl AsContextRef) -> GlobalType { - *self.handle.get(ctx.as_context_ref().objects()).ty() + pub fn ty(&self, ctx: &impl AsStoreRef) -> GlobalType { + *self.handle.get(ctx.as_store_ref().objects()).ty() } /// Retrieves the current value [`Val`] that the Global has. @@ -107,23 +101,21 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Store, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let g = Global::new(&mut ctx, Value::I32(1)); + /// let g = Global::new(&mut store, Value::I32(1)); /// - /// assert_eq!(g.get(&mut ctx), Value::I32(1)); + /// assert_eq!(g.get(&mut store), Value::I32(1)); /// ``` - pub fn get(&self, ctx: &mut impl AsContextMut) -> Value { + pub fn get(&self, ctx: &mut impl AsStoreMut) -> Value { unsafe { let raw = self .handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .vmglobal() .as_ref() .val; - let ty = self.handle.get(ctx.as_context_ref().objects()).ty().ty; + let ty = self.handle.get(ctx.as_store_ref().objects()).ty().ty; Value::from_raw(ctx, ty, raw) } } @@ -134,17 +126,15 @@ impl Global { /// /// ``` /// # use wasmer::{Global, Store, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let g = Global::new_mut(&mut ctx, Value::I32(1)); + /// let g = Global::new_mut(&mut store, Value::I32(1)); /// - /// assert_eq!(g.get(&mut ctx), Value::I32(1)); + /// assert_eq!(g.get(&mut store), Value::I32(1)); /// - /// g.set(&mut ctx, Value::I32(2)); + /// g.set(&mut store, Value::I32(2)); /// - /// assert_eq!(g.get(&mut ctx), Value::I32(2)); + /// assert_eq!(g.get(&mut store), Value::I32(2)); /// ``` /// /// # Errors @@ -153,30 +143,26 @@ impl Global { /// /// ```should_panic /// # use wasmer::{Global, Store, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let g = Global::new(&mut ctx, Value::I32(1)); + /// let g = Global::new(&mut store, Value::I32(1)); /// - /// g.set(&mut ctx, Value::I32(2)).unwrap(); + /// g.set(&mut store, Value::I32(2)).unwrap(); /// ``` /// /// Trying to set a value of a incompatible type will raise an error: /// /// ```should_panic /// # use wasmer::{Global, Store, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let g = Global::new(&mut ctx, Value::I32(1)); + /// let g = Global::new(&mut store, Value::I32(1)); /// /// // This results in an error: `RuntimeError`. - /// g.set(&mut ctx, Value::I64(2)).unwrap(); + /// g.set(&mut store, Value::I64(2)).unwrap(); /// ``` - pub fn set(&self, ctx: &mut impl AsContextMut, val: Value) -> Result<(), RuntimeError> { - if !val.is_from_context(ctx) { + pub fn set(&self, ctx: &mut impl AsStoreMut, val: Value) -> Result<(), RuntimeError> { + if !val.is_from_store(ctx) { return Err(RuntimeError::new( "cross-`Context` values are not supported", )); @@ -193,7 +179,7 @@ impl Global { } unsafe { self.handle - .get_mut(ctx.as_context_mut().objects_mut()) + .get_mut(ctx.objects_mut()) .vmglobal() .as_mut() .val = val.as_raw(ctx); @@ -202,19 +188,19 @@ impl Global { } pub(crate) fn from_vm_extern( - ctx: &mut impl AsContextMut, - internal: InternalContextHandle, + ctx: &mut impl AsStoreMut, + internal: InternalStoreHandle, ) -> Self { Self { handle: unsafe { - ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal) + StoreHandle::from_internal(ctx.as_store_ref().objects().id(), internal) }, } } /// Checks whether this `Global` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { + self.handle.store_id() == ctx.as_store_ref().objects().id() } pub(crate) fn to_vm_extern(&self) -> VMExtern { diff --git a/lib/api/src/sys/externals/memory.rs b/lib/api/src/sys/externals/memory.rs index 136e7620436..ae682740452 100644 --- a/lib/api/src/sys/externals/memory.rs +++ b/lib/api/src/sys/externals/memory.rs @@ -1,6 +1,6 @@ -use crate::sys::context::{AsContextMut, AsContextRef}; use crate::sys::exports::{ExportError, Exportable}; use crate::sys::externals::Extern; +use crate::sys::store::{AsStoreMut, AsStoreRef}; use crate::sys::MemoryType; use crate::MemoryAccessError; use std::convert::TryInto; @@ -9,9 +9,7 @@ use std::mem; use std::mem::MaybeUninit; use std::slice; use wasmer_types::Pages; -use wasmer_vm::{ - ContextHandle, ContextObjects, InternalContextHandle, MemoryError, VMExtern, VMMemory, -}; +use wasmer_vm::{InternalStoreHandle, MemoryError, StoreHandle, StoreObjects, VMExtern, VMMemory}; /// A WebAssembly `memory` instance. /// @@ -29,7 +27,7 @@ use wasmer_vm::{ /// Spec: #[derive(Debug, Clone)] pub struct Memory { - handle: ContextHandle, + handle: StoreHandle, } impl Memory { @@ -42,20 +40,18 @@ impl Memory { /// /// ``` /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let m = Memory::new(&mut ctx, MemoryType::new(1, None, false)).unwrap(); + /// let m = Memory::new(&mut store, MemoryType::new(1, None, false)).unwrap(); /// ``` - pub fn new(ctx: &mut impl AsContextMut, ty: MemoryType) -> Result { - let mut ctx = ctx.as_context_mut(); - let tunables = ctx.store().tunables(); + pub fn new(ctx: &mut impl AsStoreMut, ty: MemoryType) -> Result { + let mut ctx = ctx.as_store_mut(); + let tunables = ctx.tunables(); let style = tunables.memory_style(&ty); let memory = tunables.create_host_memory(&ty, &style)?; Ok(Self { - handle: ContextHandle::new(ctx.objects_mut(), memory), + handle: StoreHandle::new(ctx.objects_mut(), memory), }) } @@ -65,17 +61,15 @@ impl Memory { /// /// ``` /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # /// let mt = MemoryType::new(1, None, false); - /// let m = Memory::new(&mut ctx, mt).unwrap(); + /// let m = Memory::new(&mut store, mt).unwrap(); /// - /// assert_eq!(m.ty(&mut ctx), mt); + /// assert_eq!(m.ty(&mut store), mt); /// ``` - pub fn ty(&self, ctx: &impl AsContextRef) -> MemoryType { - self.handle.get(ctx.as_context_ref().objects()).ty() + pub fn ty(&self, ctx: &impl AsStoreRef) -> MemoryType { + self.handle.get(ctx.as_store_ref().objects()).ty() } /// Returns the pointer to the raw bytes of the `Memory`. @@ -83,31 +77,56 @@ impl Memory { // This used by wasmer-emscripten and wasmer-c-api, but should be treated // as deprecated and not used in future code. #[doc(hidden)] - pub fn data_ptr(&self, ctx: &impl AsContextRef) -> *mut u8 { + pub fn data_ptr(&self, ctx: &impl AsStoreRef) -> *mut u8 { self.buffer(ctx).base } /// Returns the size (in bytes) of the `Memory`. - pub fn data_size(&self, ctx: &impl AsContextRef) -> u64 { + pub fn data_size(&self, ctx: &impl AsStoreRef) -> u64 { self.buffer(ctx).len.try_into().unwrap() } + /// Retrieve a slice of the memory contents. + /// + /// # Safety + /// + /// Until the returned slice is dropped, it is undefined behaviour to + /// modify the memory contents in any way including by calling a wasm + /// function that writes to the memory or by resizing the memory. + #[doc(hidden)] + pub unsafe fn data_unchecked(&self, ctx: &impl AsStoreRef) -> &[u8] { + self.data_unchecked_mut(ctx) + } + + /// Retrieve a mutable slice of the memory contents. + /// + /// # Safety + /// + /// This method provides interior mutability without an UnsafeCell. Until + /// the returned value is dropped, it is undefined behaviour to read or + /// write to the pointed-to memory in any way except through this slice, + /// including by calling a wasm function that reads the memory contents or + /// by resizing this Memory. + #[allow(clippy::mut_from_ref)] + #[doc(hidden)] + pub unsafe fn data_unchecked_mut(&self, ctx: &impl AsStoreRef) -> &mut [u8] { + slice::from_raw_parts_mut(self.buffer(ctx).base, self.buffer(ctx).len) + } + /// Returns the size (in [`Pages`]) of the `Memory`. /// /// # Example /// /// ``` /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let m = Memory::new(&mut ctx, MemoryType::new(1, None, false)).unwrap(); + /// let m = Memory::new(&mut store, MemoryType::new(1, None, false)).unwrap(); /// - /// assert_eq!(m.size(&mut ctx), Pages(1)); + /// assert_eq!(m.size(&mut store), Pages(1)); /// ``` - pub fn size(&self, ctx: &impl AsContextRef) -> Pages { - self.handle.get(ctx.as_context_ref().objects()).size() + pub fn size(&self, ctx: &impl AsStoreRef) -> Pages { + self.handle.get(ctx.as_store_ref().objects()).size() } /// Grow memory by the specified amount of WebAssembly [`Pages`] and return @@ -117,15 +136,13 @@ impl Memory { /// /// ``` /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # let mut store = Store::default(); /// # - /// let m = Memory::new(&mut ctx, MemoryType::new(1, Some(3), false)).unwrap(); - /// let p = m.grow(&mut ctx, 2).unwrap(); + /// let m = Memory::new(&mut store, MemoryType::new(1, Some(3), false)).unwrap(); + /// let p = m.grow(&mut store, 2).unwrap(); /// /// assert_eq!(p, Pages(1)); - /// assert_eq!(m.size(&mut ctx), Pages(3)); + /// assert_eq!(m.size(&mut store), Pages(3)); /// ``` /// /// # Errors @@ -135,26 +152,24 @@ impl Memory { /// /// ```should_panic /// # use wasmer::{Memory, MemoryType, Pages, Store, Type, Value, WASM_MAX_PAGES}; - /// # use wasmer::Context as WasmerContext; - /// # let store = Store::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); + /// # use wasmer::FunctionEnv; + /// # let mut store = Store::default(); + /// # let env = FunctionEnv::new(&mut store, ()); /// # - /// let m = Memory::new(&mut ctx, MemoryType::new(1, Some(1), false)).unwrap(); + /// let m = Memory::new(&mut store, MemoryType::new(1, Some(1), false)).unwrap(); /// /// // This results in an error: `MemoryError::CouldNotGrow`. - /// let s = m.grow(&mut ctx, 1).unwrap(); + /// let s = m.grow(&mut store, 1).unwrap(); /// ``` pub fn grow( &self, - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, delta: IntoPages, ) -> Result where IntoPages: Into, { - self.handle - .get_mut(ctx.as_context_mut().objects_mut()) - .grow(delta.into()) + self.handle.get_mut(ctx.objects_mut()).grow(delta.into()) } /// Safely reads bytes from the memory at the given offset. @@ -166,7 +181,7 @@ impl Memory { /// concurrent writes. pub fn read( &self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, offset: u64, buf: &mut [u8], ) -> Result<(), MemoryAccessError> { @@ -185,7 +200,7 @@ impl Memory { /// concurrent writes. pub fn read_uninit<'a>( &self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, offset: u64, buf: &'a mut [MaybeUninit], ) -> Result<&'a mut [u8], MemoryAccessError> { @@ -201,15 +216,15 @@ impl Memory { /// concurrent reads/writes. pub fn write( &self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, offset: u64, data: &[u8], ) -> Result<(), MemoryAccessError> { self.buffer(ctx).write(offset, data) } - pub(crate) fn buffer<'a>(&'a self, ctx: &'a impl AsContextRef) -> MemoryBuffer<'a> { - let definition = self.handle.get(ctx.as_context_ref().objects()).vmmemory(); + pub(crate) fn buffer<'a>(&'a self, ctx: &'a impl AsStoreRef) -> MemoryBuffer<'a> { + let definition = self.handle.get(ctx.as_store_ref().objects()).vmmemory(); let def = unsafe { definition.as_ref() }; MemoryBuffer { base: def.base, @@ -219,19 +234,19 @@ impl Memory { } pub(crate) fn from_vm_extern( - ctx: &impl AsContextRef, - internal: InternalContextHandle, + ctx: &impl AsStoreRef, + internal: InternalStoreHandle, ) -> Self { Self { handle: unsafe { - ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal) + StoreHandle::from_internal(ctx.as_store_ref().objects().id(), internal) }, } } /// Checks whether this `Memory` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { + self.handle.store_id() == ctx.as_store_ref().objects().id() } pub(crate) fn to_vm_extern(&self) -> VMExtern { @@ -261,7 +276,7 @@ impl<'a> Exportable<'a> for Memory { pub(crate) struct MemoryBuffer<'a> { base: *mut u8, len: usize, - marker: PhantomData<(&'a Memory, &'a ContextObjects)>, + marker: PhantomData<(&'a Memory, &'a StoreObjects)>, } impl<'a> MemoryBuffer<'a> { diff --git a/lib/api/src/sys/externals/mod.rs b/lib/api/src/sys/externals/mod.rs index 7625f7ca206..da4fff433b7 100644 --- a/lib/api/src/sys/externals/mod.rs +++ b/lib/api/src/sys/externals/mod.rs @@ -14,7 +14,7 @@ use crate::sys::ExternType; use std::fmt; use wasmer_vm::VMExtern; -use super::context::{AsContextMut, AsContextRef}; +use super::store::{AsStoreMut, AsStoreRef}; /// An `Extern` is the runtime representation of an entity that /// can be imported or exported. @@ -34,7 +34,7 @@ pub enum Extern { impl Extern { /// Return the underlying type of the inner `Extern`. - pub fn ty(&self, ctx: &impl AsContextRef) -> ExternType { + pub fn ty(&self, ctx: &impl AsStoreRef) -> ExternType { match self { Self::Function(ft) => ExternType::Function(ft.ty(ctx)), Self::Memory(ft) => ExternType::Memory(ft.ty(ctx)), @@ -44,7 +44,7 @@ impl Extern { } /// Create an `Extern` from an `wasmer_engine::Export`. - pub fn from_vm_extern(ctx: &mut impl AsContextMut, vm_extern: VMExtern) -> Self { + pub fn from_vm_extern(ctx: &mut impl AsStoreMut, vm_extern: VMExtern) -> Self { match vm_extern { VMExtern::Function(f) => Self::Function(Function::from_vm_extern(ctx, f)), VMExtern::Memory(m) => Self::Memory(Memory::from_vm_extern(ctx, m)), @@ -54,12 +54,12 @@ impl Extern { } /// Checks whether this `Extern` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { match self { - Self::Function(f) => f.is_from_context(ctx), - Self::Global(g) => g.is_from_context(ctx), - Self::Memory(m) => m.is_from_context(ctx), - Self::Table(t) => t.is_from_context(ctx), + Self::Function(f) => f.is_from_store(ctx), + Self::Global(g) => g.is_from_store(ctx), + Self::Memory(m) => m.is_from_store(ctx), + Self::Table(t) => t.is_from_store(ctx), } } diff --git a/lib/api/src/sys/externals/table.rs b/lib/api/src/sys/externals/table.rs index 9e2862b9bd5..7f6a24cb36d 100644 --- a/lib/api/src/sys/externals/table.rs +++ b/lib/api/src/sys/externals/table.rs @@ -1,10 +1,10 @@ -use crate::sys::context::{AsContextMut, AsContextRef}; use crate::sys::exports::{ExportError, Exportable}; use crate::sys::externals::Extern; +use crate::sys::store::{AsStoreMut, AsStoreRef}; use crate::sys::RuntimeError; use crate::sys::TableType; use crate::{ExternRef, Function, Value}; -use wasmer_vm::{ContextHandle, InternalContextHandle, TableElement, VMExtern, VMTable}; +use wasmer_vm::{InternalStoreHandle, StoreHandle, TableElement, VMExtern, VMTable}; /// A WebAssembly `table` instance. /// @@ -17,7 +17,7 @@ use wasmer_vm::{ContextHandle, InternalContextHandle, TableElement, VMExtern, VM /// Spec: #[derive(Debug, Clone)] pub struct Table { - handle: ContextHandle, + handle: StoreHandle, } fn set_table_item( @@ -29,10 +29,10 @@ fn set_table_item( } fn value_to_table_element( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, val: Value, ) -> Result { - if !val.is_from_context(ctx) { + if !val.is_from_store(ctx) { return Err(RuntimeError::new("cannot pass Value across contexts")); } Ok(match val { @@ -46,7 +46,7 @@ fn value_to_table_element( }) } -fn value_from_table_element(ctx: &mut impl AsContextMut, item: wasmer_vm::TableElement) -> Value { +fn value_from_table_element(ctx: &mut impl AsStoreMut, item: wasmer_vm::TableElement) -> Value { match item { wasmer_vm::TableElement::FuncRef(funcref) => { Value::FuncRef(funcref.map(|f| unsafe { Function::from_vm_funcref(ctx, f) })) @@ -65,13 +65,13 @@ impl Table { /// This function will construct the `Table` using the store /// [`BaseTunables`][crate::sys::BaseTunables]. pub fn new( - ctx: &mut impl AsContextMut, + mut ctx: &mut impl AsStoreMut, ty: TableType, init: Value, ) -> Result { - let mut ctx = ctx.as_context_mut(); let item = value_to_table_element(&mut ctx, init)?; - let tunables = ctx.store().tunables(); + let mut ctx = ctx.as_store_mut(); + let tunables = ctx.tunables(); let style = tunables.table_style(&ty); let mut table = tunables .create_host_table(&ty, &style) @@ -83,39 +83,35 @@ impl Table { } Ok(Self { - handle: ContextHandle::new(ctx.objects_mut(), table), + handle: StoreHandle::new(ctx.objects_mut(), table), }) } /// Returns the [`TableType`] of the `Table`. - pub fn ty(&self, ctx: &impl AsContextRef) -> TableType { - *self.handle.get(ctx.as_context_ref().objects()).ty() + pub fn ty(&self, ctx: &impl AsStoreRef) -> TableType { + *self.handle.get(ctx.as_store_ref().objects()).ty() } /// Retrieves an element of the table at the provided `index`. - pub fn get(&self, ctx: &mut impl AsContextMut, index: u32) -> Option { - let item = self.handle.get(ctx.as_context_ref().objects()).get(index)?; + pub fn get(&self, ctx: &mut impl AsStoreMut, index: u32) -> Option { + let item = self.handle.get(ctx.as_store_ref().objects()).get(index)?; Some(value_from_table_element(ctx, item)) } /// Sets an element `val` in the Table at the provided `index`. pub fn set( &self, - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, index: u32, val: Value, ) -> Result<(), RuntimeError> { let item = value_to_table_element(ctx, val)?; - set_table_item( - self.handle.get_mut(ctx.as_context_mut().objects_mut()), - index, - item, - ) + set_table_item(self.handle.get_mut(ctx.objects_mut()), index, item) } /// Retrieves the size of the `Table` (in elements) - pub fn size(&self, ctx: &impl AsContextRef) -> u32 { - self.handle.get(ctx.as_context_ref().objects()).size() + pub fn size(&self, ctx: &impl AsStoreRef) -> u32 { + self.handle.get(ctx.as_store_ref().objects()).size() } /// Grows the size of the `Table` by `delta`, initializating @@ -129,13 +125,13 @@ impl Table { /// Returns an error if the `delta` is out of bounds for the table. pub fn grow( &self, - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, delta: u32, init: Value, ) -> Result { let item = value_to_table_element(ctx, init)?; self.handle - .get_mut(ctx.as_context_mut().objects_mut()) + .get_mut(ctx.objects_mut()) .grow(delta, item) .ok_or_else(|| RuntimeError::new(format!("failed to grow table by `{}`", delta))) } @@ -148,19 +144,19 @@ impl Table { /// Returns an error if the range is out of bounds of either the source or /// destination tables. pub fn copy( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, dst_table: &Self, dst_index: u32, src_table: &Self, src_index: u32, len: u32, ) -> Result<(), RuntimeError> { - if dst_table.handle.context_id() != src_table.handle.context_id() { + if dst_table.handle.store_id() != src_table.handle.store_id() { return Err(RuntimeError::new( "cross-`Context` table copies are not supported", )); } - let mut ctx = ctx.as_context_mut(); + let ctx = ctx; if dst_table.handle.internal_handle() == src_table.handle.internal_handle() { let table = dst_table.handle.get_mut(ctx.objects_mut()); table.copy_within(dst_index, src_index, len) @@ -176,19 +172,19 @@ impl Table { } pub(crate) fn from_vm_extern( - ctx: &mut impl AsContextMut, - internal: InternalContextHandle, + ctx: &mut impl AsStoreMut, + internal: InternalStoreHandle, ) -> Self { Self { handle: unsafe { - ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal) + StoreHandle::from_internal(ctx.as_store_ref().objects().id(), internal) }, } } /// Checks whether this `Table` can be used with the given context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { - self.handle.context_id() == ctx.as_context_ref().objects().id() + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { + self.handle.store_id() == ctx.as_store_ref().objects().id() } pub(crate) fn to_vm_extern(&self) -> VMExtern { diff --git a/lib/api/src/sys/function_env.rs b/lib/api/src/sys/function_env.rs new file mode 100644 index 00000000000..c2fd67018c6 --- /dev/null +++ b/lib/api/src/sys/function_env.rs @@ -0,0 +1,120 @@ +use std::{any::Any, marker::PhantomData}; + +use wasmer_vm::{StoreHandle, StoreObjects, VMFunctionEnvironment}; + +use crate::{AsStoreMut, AsStoreRef, StoreMut, StoreRef}; + +#[derive(Debug)] +#[repr(transparent)] +/// An opaque reference to a function environment. +/// The function environment data is owned by the `Store`. +pub struct FunctionEnv { + pub(crate) handle: StoreHandle, + _phantom: PhantomData, +} + +impl FunctionEnv { + /// Make a new extern reference + pub fn new(store: &mut impl AsStoreMut, value: T) -> Self + where + T: Any + Send + 'static + Sized, + { + Self { + handle: StoreHandle::new( + store.as_store_mut().objects_mut(), + VMFunctionEnvironment::new(value), + ), + _phantom: PhantomData, + } + } + + /// Get the data as reference + pub fn as_ref<'a>(&self, store: &'a impl AsStoreMut) -> &'a T + where + T: Any + Send + 'static + Sized, + { + self.handle + .get(store.as_store_ref().objects()) + .as_ref() + .downcast_ref::() + .unwrap() + } + + /// Get the data as mutable + pub fn as_mut<'a>(&self, store: &'a mut impl AsStoreMut) -> &'a mut T + where + T: Any + Send + 'static + Sized, + { + self.handle + .get_mut(store.objects_mut()) + .as_mut() + .downcast_mut::() + .unwrap() + } + + /// Convert it into a `FunctionEnvMut` + pub fn into_mut(self, store: &mut impl AsStoreMut) -> FunctionEnvMut + where + T: Any + Send + 'static + Sized, + { + FunctionEnvMut { + store_mut: store.as_store_mut(), + func_env: self, + } + } +} + +impl Clone for FunctionEnv { + fn clone(&self) -> Self { + Self { + handle: self.handle.clone(), + _phantom: self._phantom, + } + } +} + +/// A temporary handle to a [`Context`]. +pub struct FunctionEnvMut<'a, T: 'a> { + pub(crate) store_mut: StoreMut<'a>, + pub(crate) func_env: FunctionEnv, +} + +impl FunctionEnvMut<'_, T> { + /// Returns a reference to the host state in this context. + pub fn data(&self) -> &T { + self.func_env.as_ref(&self.store_mut) + } + + /// Returns a mutable- reference to the host state in this context. + pub fn data_mut(&mut self) -> &mut T { + self.func_env.as_mut(&mut self.store_mut) + } + + /// Borrows a new mutable reference + pub fn as_mut(&mut self) -> FunctionEnvMut<'_, T> { + FunctionEnvMut { + store_mut: self.store_mut.as_store_mut(), + func_env: self.func_env.clone(), + } + } +} + +impl AsStoreRef for FunctionEnvMut<'_, T> { + fn as_store_ref(&self) -> StoreRef<'_> { + StoreRef { + inner: self.store_mut.inner, + } + } +} + +impl AsStoreMut for FunctionEnvMut<'_, T> { + fn as_store_mut(&mut self) -> StoreMut<'_> { + StoreMut { + inner: self.store_mut.inner, + } + } + #[inline] + fn objects_mut(&mut self) -> &mut StoreObjects { + &mut self.store_mut.inner.objects + } +} diff --git a/lib/api/src/sys/imports.rs b/lib/api/src/sys/imports.rs index 5c479c54b3c..a93171a3115 100644 --- a/lib/api/src/sys/imports.rs +++ b/lib/api/src/sys/imports.rs @@ -16,19 +16,19 @@ use wasmer_types::ImportError; /// /// # Usage: /// ```no_run -/// use wasmer::{ContextMut, Exports, Module, Instance, imports, Imports, Function}; -/// # fn foo_test(mut ctx: ContextMut<()>, module: Module) { +/// use wasmer::{Store, Exports, Module, Instance, imports, Imports, Function, FunctionEnv, FunctionEnvMut}; +/// # fn foo_test(mut env: FunctionEnv<()>, mut store: &mut Store, module: Module) { /// -/// let host_fn = Function::new_native(&mut ctx, foo); +/// let host_fn = Function::new_native(&mut store, &env, foo); /// let import_object: Imports = imports! { /// "env" => { /// "foo" => host_fn, /// }, /// }; /// -/// let instance = Instance::new(&mut ctx, &module, &import_object).expect("Could not instantiate module."); +/// let instance = Instance::new(&mut store, &module, &import_object).expect("Could not instantiate module."); /// -/// fn foo(_ctx: ContextMut<()>, n: i32) -> i32 { +/// fn foo(_ctx: FunctionEnvMut<()>, n: i32) -> i32 { /// n /// } /// @@ -97,15 +97,15 @@ impl Imports { /// /// # Usage /// ```no_run - /// # use wasmer::Context as WasmerContext; - /// # let store = Default::default(); - /// # let mut ctx = WasmerContext::new(&store, ()); - /// use wasmer::{ContextMut, Imports, Function}; - /// fn foo(_ctx: ContextMut<()>, n: i32) -> i32 { + /// # use wasmer::{FunctionEnv, Store}; + /// # let mut store: Store = Default::default(); + /// # let env = FunctionEnv::new(&mut store, ()); + /// use wasmer::{StoreMut, Imports, Function, FunctionEnvMut}; + /// fn foo(_ctx: FunctionEnvMut<()>, n: i32) -> i32 { /// n /// } /// let mut import_object = Imports::new(); - /// import_object.define("env", "foo", Function::new_native(&mut ctx, foo)); + /// import_object.define("env", "foo", Function::new_native(&mut store, &env, foo)); /// ``` pub fn define(&mut self, ns: &str, name: &str, val: impl Into) { self.map @@ -210,19 +210,18 @@ impl fmt::Debug for Imports { /// # Usage /// /// ``` -/// # use wasmer::{ContextMut, Function, Store}; -/// # use wasmer::Context as WasmerContext; -/// # let store = Store::default(); -/// # let mut ctx = WasmerContext::new(&store, ()); +/// # use wasmer::{StoreMut, Function, Store, FunctionEnv, FunctionEnvMut}; +/// # let mut store = Store::default(); +/// # let env = FunctionEnv::new(&mut store, ()); /// use wasmer::imports; /// /// let import_object = imports! { /// "env" => { -/// "foo" => Function::new_native(&mut ctx, foo) +/// "foo" => Function::new_native(&mut store, &env, foo) /// }, /// }; /// -/// fn foo(_ctx: ContextMut<()>, n: i32) -> i32 { +/// fn foo(_env: FunctionEnvMut<()>, n: i32) -> i32 { /// n /// } /// ``` @@ -271,18 +270,15 @@ macro_rules! import_namespace { #[cfg(test)] mod test { - use crate::sys::exports::Exportable; - use crate::sys::Context as WasmerContext; - use crate::sys::Exports; - use crate::sys::{Global, Store, Value}; + use crate::sys::FunctionEnv; + use crate::sys::{AsStoreMut, Global, Store, Value}; use wasmer_types::Type; use wasmer_vm::VMExtern; - /* + #[test] fn namespace() { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let g1 = Global::new(&mut ctx, Value::I32(0)); + let mut store = Store::default(); + let g1 = Global::new(&mut store, Value::I32(0)); let namespace = namespace! { "happy" => g1 }; @@ -294,73 +290,72 @@ mod test { assert!( if let VMExtern::Global(happy_dog_global) = happy_dog_entry.to_vm_extern() { - happy_dog_global.get(&mut ctx).ty == Type::I32 + (*happy_dog_global.get(store.objects_mut()).ty()).ty == Type::I32 } else { false } ); } - */ + #[test] fn imports_macro_allows_trailing_comma_and_none() { - use crate::sys::ContextMut; use crate::sys::Function; + use crate::sys::FunctionEnvMut; - let store = Default::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store: Store = Default::default(); + let env = FunctionEnv::new(&mut store, ()); - fn func(_ctx: ContextMut<()>, arg: i32) -> i32 { + fn func(_ctx: FunctionEnvMut<()>, arg: i32) -> i32 { arg + 1 } let _ = imports! { "env" => { - "func" => Function::new_native(&mut ctx, func), + "func" => Function::new_native(&mut store, &env, func), }, }; let _ = imports! { "env" => { - "func" => Function::new_native(&mut ctx, func), + "func" => Function::new_native(&mut store, &env, func), } }; let _ = imports! { "env" => { - "func" => Function::new_native(&mut ctx, func), + "func" => Function::new_native(&mut store, &env, func), }, "abc" => { - "def" => Function::new_native(&mut ctx, func), + "def" => Function::new_native(&mut store, &env, func), } }; let _ = imports! { "env" => { - "func" => Function::new_native(&mut ctx, func) + "func" => Function::new_native(&mut store, &env, func) }, }; let _ = imports! { "env" => { - "func" => Function::new_native(&mut ctx, func) + "func" => Function::new_native(&mut store, &env, func) } }; let _ = imports! { "env" => { - "func1" => Function::new_native(&mut ctx, func), - "func2" => Function::new_native(&mut ctx, func) + "func1" => Function::new_native(&mut store, &env, func), + "func2" => Function::new_native(&mut store, &env, func) } }; let _ = imports! { "env" => { - "func1" => Function::new_native(&mut ctx, func), - "func2" => Function::new_native(&mut ctx, func), + "func1" => Function::new_native(&mut store, &env, func), + "func2" => Function::new_native(&mut store, &env, func), } }; } #[test] fn chaining_works() { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); - let g = Global::new(&mut ctx, Value::I32(0)); + let g = Global::new(&mut store, Value::I32(0)); let mut imports1 = imports! { "dog" => { @@ -390,10 +385,9 @@ mod test { #[test] fn extending_conflict_overwrites() { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let g1 = Global::new(&mut ctx, Value::I32(0)); - let g2 = Global::new(&mut ctx, Value::I64(0)); + let mut store = Store::default(); + let g1 = Global::new(&mut store, Value::I32(0)); + let g2 = Global::new(&mut store, Value::I64(0)); let mut imports1 = imports! { "dog" => { @@ -408,7 +402,7 @@ mod test { }; imports1.extend(&imports2); - let happy_dog_entry = imports1.get_export("dog", "happy").unwrap(); + let _happy_dog_entry = imports1.get_export("dog", "happy").unwrap(); /* assert!( if let Exports::Global(happy_dog_global) = happy_dog_entry.to_vm_extern() { @@ -419,10 +413,9 @@ mod test { ); */ // now test it in reverse - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let g1 = Global::new(&mut ctx, Value::I32(0)); - let g2 = Global::new(&mut ctx, Value::I64(0)); + let mut store = Store::default(); + let g1 = Global::new(&mut store, Value::I32(0)); + let g2 = Global::new(&mut store, Value::I64(0)); let imports1 = imports! { "dog" => { @@ -437,7 +430,7 @@ mod test { }; imports2.extend(&imports1); - let happy_dog_entry = imports2.get_export("dog", "happy").unwrap(); + let _happy_dog_entry = imports2.get_export("dog", "happy").unwrap(); /* assert!( if let Exports::Global(happy_dog_global) = happy_dog_entry.to_vm_extern() { diff --git a/lib/api/src/sys/instance.rs b/lib/api/src/sys/instance.rs index 547a12d1ba3..bcc4d6beb55 100644 --- a/lib/api/src/sys/instance.rs +++ b/lib/api/src/sys/instance.rs @@ -5,9 +5,9 @@ use crate::sys::module::Module; use crate::sys::{LinkError, RuntimeError}; use std::fmt; use thiserror::Error; -use wasmer_vm::{ContextHandle, InstanceHandle}; +use wasmer_vm::{InstanceHandle, StoreHandle}; -use super::context::AsContextMut; +use super::store::AsStoreMut; /// A WebAssembly Instance is a stateful, executable /// instance of a WebAssembly [`Module`]. @@ -19,7 +19,7 @@ use super::context::AsContextMut; /// Spec: #[derive(Clone)] pub struct Instance { - _handle: ContextHandle, + _handle: StoreHandle, module: Module, /// The exports for an instance. pub exports: Exports, @@ -59,13 +59,13 @@ pub enum InstantiationError { /// The module was compiled with a CPU feature that is not available on /// the current host. - #[error("missing requires CPU features: {0:?}")] + #[error("missing required CPU features: {0:?}")] CpuFeature(String), - /// Import from a different [`Context`]. - /// This error occurs when an import from a different context is used. - #[error("cannot mix imports from different contexts")] - BadContext, + /// Import from a different [`Store`]. + /// This error occurs when an import from a different store is used. + #[error("cannot mix imports from different stores")] + DifferentStores, } impl From for InstantiationError { @@ -87,17 +87,17 @@ impl Instance { /// /// ``` /// # use wasmer::{imports, Store, Module, Global, Value, Instance}; - /// # use wasmer::Context as WasmerContext; + /// # use wasmer::FunctionEnv; /// # fn main() -> anyhow::Result<()> { - /// let store = Store::default(); - /// let mut ctx = WasmerContext::new(&store, ()); + /// let mut store = Store::default(); + /// let env = FunctionEnv::new(&mut store, ()); /// let module = Module::new(&store, "(module)")?; /// let imports = imports!{ /// "host" => { - /// "var" => Global::new(&mut ctx, Value::I32(2)) + /// "var" => Global::new(&mut store, Value::I32(2)) /// } /// }; - /// let instance = Instance::new(&mut ctx, &module, &imports)?; + /// let instance = Instance::new(&mut store, &module, &imports)?; /// # Ok(()) /// # } /// ``` @@ -110,7 +110,7 @@ impl Instance { /// * Link errors that happen when plugging the imports into the instance /// * Runtime errors that happen when running the module `start` function. pub fn new( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, module: &Module, imports: &Imports, ) -> Result { @@ -129,7 +129,7 @@ impl Instance { .collect::(); let instance = Self { - _handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), handle), + _handle: StoreHandle::new(ctx.objects_mut(), handle), module: module.clone(), exports, }; @@ -148,7 +148,7 @@ impl Instance { /// * Link errors that happen when plugging the imports into the instance /// * Runtime errors that happen when running the module `start` function. pub fn new_by_index( - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, module: &Module, externs: &[Extern], ) -> Result { @@ -165,7 +165,7 @@ impl Instance { .collect::(); let instance = Self { - _handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), handle), + _handle: StoreHandle::new(ctx.objects_mut(), handle), module: module.clone(), exports, }; diff --git a/lib/api/src/sys/mem_access.rs b/lib/api/src/sys/mem_access.rs index bc92dd140a1..debb46c0c68 100644 --- a/lib/api/src/sys/mem_access.rs +++ b/lib/api/src/sys/mem_access.rs @@ -12,8 +12,8 @@ use std::{ use thiserror::Error; use wasmer_types::ValueType; -use super::context::AsContextRef; use super::externals::memory::MemoryBuffer; +use super::store::AsStoreRef; /// Error for invalid [`Memory`] access. #[derive(Clone, Copy, Debug, Error)] @@ -62,7 +62,7 @@ pub struct WasmRef<'a, T: ValueType> { impl<'a, T: ValueType> WasmRef<'a, T> { /// Creates a new `WasmRef` at the given offset in a memory. #[inline] - pub fn new(ctx: &'a impl AsContextRef, memory: &'a Memory, offset: u64) -> Self { + pub fn new(ctx: &'a impl AsStoreRef, memory: &'a Memory, offset: u64) -> Self { Self { buffer: memory.buffer(ctx), offset, @@ -161,7 +161,7 @@ impl<'a, T: ValueType> WasmSlice<'a, T> { /// Returns a `MemoryAccessError` if the slice length overflows. #[inline] pub fn new( - ctx: &'a impl AsContextRef, + ctx: &'a impl AsStoreRef, memory: &'a Memory, offset: u64, len: u64, diff --git a/lib/api/src/sys/mod.rs b/lib/api/src/sys/mod.rs index e9e4ce3a40d..9eca8454d15 100644 --- a/lib/api/src/sys/mod.rs +++ b/lib/api/src/sys/mod.rs @@ -1,7 +1,7 @@ -mod context; mod exports; mod extern_ref; mod externals; +mod function_env; mod imports; mod instance; mod mem_access; @@ -13,18 +13,19 @@ mod store; mod tunables; mod value; -pub use crate::sys::context::{AsContextMut, AsContextRef, Context, ContextMut, ContextRef}; pub use crate::sys::exports::{ExportError, Exportable, Exports, ExportsIterator}; pub use crate::sys::extern_ref::ExternRef; pub use crate::sys::externals::{ Extern, FromToNativeWasmType, Function, Global, HostFunction, Memory, Table, WasmTypeList, }; +pub use crate::sys::function_env::{FunctionEnv, FunctionEnvMut}; pub use crate::sys::imports::Imports; pub use crate::sys::instance::{Instance, InstantiationError}; pub use crate::sys::mem_access::{MemoryAccessError, WasmRef, WasmSlice, WasmSliceIter}; pub use crate::sys::module::Module; pub use crate::sys::native::TypedFunction; pub use crate::sys::native_type::NativeWasmTypeInto; +pub use crate::sys::store::{AsStoreMut, AsStoreRef, StoreMut, StoreRef}; pub use crate::sys::ptr::{Memory32, Memory64, MemorySize, WasmPtr, WasmPtr64}; pub use crate::sys::store::Store; @@ -81,7 +82,7 @@ If you wish to use more than one compiler, you can simply create the own store. use wasmer::{Store, Universal, Singlepass}; let engine = Universal::new(Singlepass::default()).engine(); -let store = Store::new_with_engine(&engine); +let mut store = Store::new_with_engine(&engine); ```"# ); diff --git a/lib/api/src/sys/module.rs b/lib/api/src/sys/module.rs index 3d23b4cbbda..ccd7c1d4299 100644 --- a/lib/api/src/sys/module.rs +++ b/lib/api/src/sys/module.rs @@ -1,5 +1,6 @@ -use crate::sys::store::Store; use crate::sys::InstantiationError; +use crate::AsStoreMut; +use crate::AsStoreRef; use std::fmt; use std::io; use std::path::Path; @@ -14,8 +15,6 @@ use wasmer_types::{ use wasmer_types::{ExportType, ImportType}; use wasmer_vm::InstanceHandle; -use super::context::AsContextMut; - #[derive(Error, Debug)] pub enum IoCompileError { /// An IO error @@ -51,7 +50,6 @@ pub struct Module { // In the future, this code should be refactored to properly describe the // ownership of the code and its metadata. artifact: Arc, - store: Store, } impl Module { @@ -81,7 +79,7 @@ impl Module { /// ``` /// use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = "(module)"; /// let module = Module::new(&store, wat)?; /// # Ok(()) @@ -93,7 +91,7 @@ impl Module { /// ``` /// use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// // The following is the same as: /// // (module /// // (type $t0 (func (param i32) (result i32))) @@ -115,7 +113,7 @@ impl Module { /// # } /// ``` #[allow(unreachable_code)] - pub fn new(store: &Store, bytes: impl AsRef<[u8]>) -> Result { + pub fn new(store: &impl AsStoreRef, bytes: impl AsRef<[u8]>) -> Result { #[cfg(feature = "wat")] let bytes = wat::parse_bytes(bytes.as_ref()).map_err(|e| { CompileError::Wasm(WasmError::Generic(format!( @@ -128,7 +126,10 @@ impl Module { } /// Creates a new WebAssembly module from a file path. - pub fn from_file(store: &Store, file: impl AsRef) -> Result { + pub fn from_file( + store: &impl AsStoreRef, + file: impl AsRef, + ) -> Result { let file_ref = file.as_ref(); let canonical = file_ref.canonicalize()?; let wasm_bytes = std::fs::read(file_ref)?; @@ -145,7 +146,7 @@ impl Module { /// Opposed to [`Module::new`], this function is not compatible with /// the WebAssembly text format (if the "wat" feature is enabled for /// this crate). - pub fn from_binary(store: &Store, binary: &[u8]) -> Result { + pub fn from_binary(store: &impl AsStoreRef, binary: &[u8]) -> Result { Self::validate(store, binary)?; unsafe { Self::from_binary_unchecked(store, binary) } } @@ -158,7 +159,7 @@ impl Module { /// in environments where the WebAssembly modules are trusted and validated /// beforehand. pub unsafe fn from_binary_unchecked( - store: &Store, + store: &impl AsStoreRef, binary: &[u8], ) -> Result { let module = Self::compile(store, binary)?; @@ -171,13 +172,16 @@ impl Module { /// This validation is normally pretty fast and checks the enabled /// WebAssembly features in the Store Engine to assure deterministic /// validation of the Module. - pub fn validate(store: &Store, binary: &[u8]) -> Result<(), CompileError> { - store.engine().validate(binary) + pub fn validate(store: &impl AsStoreRef, binary: &[u8]) -> Result<(), CompileError> { + store.as_store_ref().engine().validate(binary) } - fn compile(store: &Store, binary: &[u8]) -> Result { - let artifact = store.engine().compile(binary, store.tunables())?; - Ok(Self::from_artifact(store, artifact)) + fn compile(store: &impl AsStoreRef, binary: &[u8]) -> Result { + let artifact = store + .as_store_ref() + .engine() + .compile(binary, store.as_store_ref().tunables())?; + Ok(Self::from_artifact(artifact)) } /// Serializes a module into a binary representation that the `Engine` @@ -188,7 +192,7 @@ impl Module { /// ```ignore /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # let module = Module::from_file(&store, "path/to/foo.wasm")?; /// let serialized = module.serialize()?; /// # Ok(()) @@ -206,7 +210,7 @@ impl Module { /// ```ignore /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # let module = Module::from_file(&store, "path/to/foo.wasm")?; /// module.serialize_to_file("path/to/foo.so")?; /// # Ok(()) @@ -234,14 +238,17 @@ impl Module { /// ```ignore /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let module = Module::deserialize(&store, serialized_data)?; /// # Ok(()) /// # } /// ``` - pub unsafe fn deserialize(store: &Store, bytes: &[u8]) -> Result { - let artifact = store.engine().deserialize(bytes)?; - Ok(Self::from_artifact(store, artifact)) + pub unsafe fn deserialize( + store: &impl AsStoreRef, + bytes: &[u8], + ) -> Result { + let artifact = store.as_store_ref().engine().deserialize(bytes)?; + Ok(Self::from_artifact(artifact)) } /// Deserializes a a serialized Module located in a `Path` into a `Module`. @@ -255,47 +262,48 @@ impl Module { /// /// ```ignore /// # use wasmer::*; - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// # fn main() -> anyhow::Result<()> { /// let module = Module::deserialize_from_file(&store, path)?; /// # Ok(()) /// # } /// ``` pub unsafe fn deserialize_from_file( - store: &Store, + store: &impl AsStoreRef, path: impl AsRef, ) -> Result { - let artifact = store.engine().deserialize_from_file(path.as_ref())?; - Ok(Self::from_artifact(store, artifact)) + let artifact = store + .as_store_ref() + .engine() + .deserialize_from_file(path.as_ref())?; + Ok(Self::from_artifact(artifact)) } - fn from_artifact(store: &Store, artifact: Arc) -> Self { - Self { - store: store.clone(), - artifact, - } + fn from_artifact(artifact: Arc) -> Self { + Self { artifact } } pub(crate) fn instantiate( &self, - ctx: &mut impl AsContextMut, + store: &mut impl AsStoreMut, imports: &[crate::Extern], ) -> Result { // Ensure all imports come from the same context. for import in imports { - if !import.is_from_context(ctx) { - return Err(InstantiationError::BadContext); + if !import.is_from_store(store) { + return Err(InstantiationError::DifferentStores); } } - + let mut store_mut = store.as_store_mut(); + let (tunables, objects) = store_mut.tunables_and_objects_mut(); unsafe { let mut instance_handle = self.artifact.instantiate( - self.store.tunables(), + tunables, &imports .iter() .map(crate::Extern::to_vm_extern) .collect::>(), - ctx.as_context_mut().objects_mut(), + objects, )?; // After the instance handle is created, we need to initialize @@ -303,8 +311,10 @@ impl Module { // of this steps traps, we still need to keep the instance alive // as some of the Instance elements may have placed in other // instance tables. - self.artifact - .finish_instantiation(&self.store, &mut instance_handle)?; + self.artifact.finish_instantiation( + store.as_store_ref().signal_handler(), + &mut instance_handle, + )?; Ok(instance_handle) } @@ -320,7 +330,7 @@ impl Module { /// ``` /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = "(module $moduleName)"; /// let module = Module::new(&store, wat)?; /// assert_eq!(module.name(), Some("moduleName")); @@ -343,7 +353,7 @@ impl Module { /// ``` /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = "(module)"; /// let mut module = Module::new(&store, wat)?; /// assert_eq!(module.name(), None); @@ -371,7 +381,7 @@ impl Module { /// ``` /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = r#"(module /// (import "host" "func1" (func)) /// (import "host" "func2" (func)) @@ -399,7 +409,7 @@ impl Module { /// ``` /// # use wasmer::*; /// # fn main() -> anyhow::Result<()> { - /// # let store = Store::default(); + /// # let mut store = Store::default(); /// let wat = r#"(module /// (func (export "namedfunc")) /// (memory (export "namedmemory") 1) @@ -427,11 +437,6 @@ impl Module { self.artifact.module_ref().custom_sections(name) } - /// Returns the [`Store`] where the `Instance` belongs. - pub fn store(&self) -> &Store { - &self.store - } - /// The ABI of the ModuleInfo is very unstable, we refactor it very often. /// This function is public because in some cases it can be useful to get some /// extra information from the module. diff --git a/lib/api/src/sys/native.rs b/lib/api/src/sys/native.rs index 3866509be8e..b9aab2647db 100644 --- a/lib/api/src/sys/native.rs +++ b/lib/api/src/sys/native.rs @@ -10,7 +10,7 @@ use std::marker::PhantomData; use crate::sys::{ - AsContextMut, FromToNativeWasmType, Function, NativeWasmTypeInto, RuntimeError, WasmTypeList, + AsStoreMut, FromToNativeWasmType, Function, NativeWasmTypeInto, RuntimeError, WasmTypeList, }; use wasmer_types::RawValue; @@ -66,17 +66,17 @@ macro_rules! impl_native_traits { /// Call the typed func and return results. #[allow(unused_mut)] #[allow(clippy::too_many_arguments)] - pub fn call(&self, ctx: &mut impl AsContextMut, $( $x: $x, )* ) -> Result { + pub fn call(&self, ctx: &mut impl AsStoreMut, $( $x: $x, )* ) -> Result { let anyfunc = unsafe { *self.func .handle - .get(ctx.as_context_ref().objects()) + .get(ctx.as_store_ref().objects()) .anyfunc .as_ptr() .as_ref() }; // Ensure all parameters come from the same context. - if $(!FromToNativeWasmType::is_from_context(&$x, ctx) ||)* false { + if $(!FromToNativeWasmType::is_from_store(&$x, ctx) ||)* false { return Err(RuntimeError::new( "cross-`Context` values are not supported", )); @@ -99,7 +99,7 @@ macro_rules! impl_native_traits { }; unsafe { wasmer_vm::wasmer_call_trampoline( - ctx.as_context_ref().store(), + ctx.as_store_ref().signal_handler(), anyfunc.vmctx, anyfunc.call_trampoline, anyfunc.func_ptr, diff --git a/lib/api/src/sys/native_type.rs b/lib/api/src/sys/native_type.rs index 746c3b21585..2b9b54df19e 100644 --- a/lib/api/src/sys/native_type.rs +++ b/lib/api/src/sys/native_type.rs @@ -6,133 +6,133 @@ use wasmer_vm::{VMExternRef, VMFuncRef}; use crate::{ExternRef, Function}; -use super::context::AsContextMut; +use super::store::AsStoreMut; /// `NativeWasmTypeInto` performs conversions from and into `NativeWasmType` /// types with a context. pub trait NativeWasmTypeInto: NativeWasmType + Sized { #[doc(hidden)] - fn into_abi(self, ctx: &mut impl AsContextMut) -> Self::Abi; + fn into_abi(self, ctx: &mut impl AsStoreMut) -> Self::Abi; #[doc(hidden)] - unsafe fn from_abi(ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self; + unsafe fn from_abi(ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self; /// Convert self to raw value representation. - fn into_raw(self, ctx: &mut impl AsContextMut) -> RawValue; + fn into_raw(self, ctx: &mut impl AsStoreMut) -> RawValue; /// Convert to self from raw value representation. /// /// # Safety /// - unsafe fn from_raw(ctx: &mut impl AsContextMut, raw: RawValue) -> Self; + unsafe fn from_raw(ctx: &mut impl AsStoreMut, raw: RawValue) -> Self; } impl NativeWasmTypeInto for i32 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> RawValue { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> RawValue { RawValue { i32: self } } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: RawValue) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: RawValue) -> Self { raw.i32 } } impl NativeWasmTypeInto for i64 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> RawValue { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> RawValue { RawValue { i64: self } } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: RawValue) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: RawValue) -> Self { raw.i64 } } impl NativeWasmTypeInto for f32 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> RawValue { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> RawValue { RawValue { f32: self } } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: RawValue) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: RawValue) -> Self { raw.f32 } } impl NativeWasmTypeInto for f64 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> RawValue { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> RawValue { RawValue { f64: self } } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: RawValue) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: RawValue) -> Self { raw.f64 } } impl NativeWasmTypeInto for u128 { #[inline] - unsafe fn from_abi(_ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(_ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { abi } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> RawValue { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> RawValue { RawValue { u128: self } } #[inline] - unsafe fn from_raw(_ctx: &mut impl AsContextMut, raw: RawValue) -> Self { + unsafe fn from_raw(_ctx: &mut impl AsStoreMut, raw: RawValue) -> Self { raw.u128 } } @@ -144,23 +144,23 @@ impl NativeWasmType for ExternRef { impl NativeWasmTypeInto for Option { #[inline] - unsafe fn from_abi(ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { VMExternRef::from_raw(RawValue { externref: abi }) .map(|e| ExternRef::from_vm_externref(ctx, e)) } #[inline] - fn into_abi(self, _ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, _ctx: &mut impl AsStoreMut) -> Self::Abi { self.map_or(0, |e| unsafe { e.vm_externref().into_raw().externref }) } #[inline] - fn into_raw(self, _ctx: &mut impl AsContextMut) -> RawValue { + fn into_raw(self, _ctx: &mut impl AsStoreMut) -> RawValue { self.map_or(RawValue { externref: 0 }, |e| e.vm_externref().into_raw()) } #[inline] - unsafe fn from_raw(ctx: &mut impl AsContextMut, raw: RawValue) -> Self { + unsafe fn from_raw(ctx: &mut impl AsStoreMut, raw: RawValue) -> Self { VMExternRef::from_raw(raw).map(|e| ExternRef::from_vm_externref(ctx, e)) } } @@ -172,22 +172,22 @@ impl NativeWasmType for Function { impl NativeWasmTypeInto for Option { #[inline] - unsafe fn from_abi(ctx: &mut impl AsContextMut, abi: Self::Abi) -> Self { + unsafe fn from_abi(ctx: &mut impl AsStoreMut, abi: Self::Abi) -> Self { VMFuncRef::from_raw(RawValue { funcref: abi }).map(|f| Function::from_vm_funcref(ctx, f)) } #[inline] - fn into_abi(self, ctx: &mut impl AsContextMut) -> Self::Abi { + fn into_abi(self, ctx: &mut impl AsStoreMut) -> Self::Abi { self.map_or(0, |f| unsafe { f.vm_funcref(ctx).into_raw().externref }) } #[inline] - fn into_raw(self, ctx: &mut impl AsContextMut) -> RawValue { + fn into_raw(self, ctx: &mut impl AsStoreMut) -> RawValue { self.map_or(RawValue { externref: 0 }, |e| e.vm_funcref(ctx).into_raw()) } #[inline] - unsafe fn from_raw(ctx: &mut impl AsContextMut, raw: RawValue) -> Self { + unsafe fn from_raw(ctx: &mut impl AsStoreMut, raw: RawValue) -> Self { VMFuncRef::from_raw(raw).map(|f| Function::from_vm_funcref(ctx, f)) } } diff --git a/lib/api/src/sys/ptr.rs b/lib/api/src/sys/ptr.rs index 1f46dc84b9b..8a430e6e4dd 100644 --- a/lib/api/src/sys/ptr.rs +++ b/lib/api/src/sys/ptr.rs @@ -5,13 +5,11 @@ use std::convert::TryFrom; use std::{fmt, marker::PhantomData, mem}; use wasmer_types::ValueType; -use super::context::AsContextRef; - -pub use wasmer_types::MemorySize; +use super::store::AsStoreRef; pub use wasmer_types::Memory32; - pub use wasmer_types::Memory64; +pub use wasmer_types::MemorySize; /// Alias for `WasmPtr. pub type WasmPtr64 = WasmPtr; @@ -23,8 +21,8 @@ pub type WasmPtr64 = WasmPtr; /// ``` /// # use wasmer::Memory; /// # use wasmer::WasmPtr; -/// # use wasmer::ContextMut; -/// pub fn host_import(mut ctx: ContextMut<()>, memory: Memory, ptr: WasmPtr) { +/// # use wasmer::FunctionEnvMut; +/// pub fn host_import(mut ctx: FunctionEnvMut<()>, memory: Memory, ptr: WasmPtr) { /// let derefed_ptr = ptr.deref(&mut ctx, &memory); /// let inner_val: u32 = derefed_ptr.read().expect("pointer in bounds"); /// println!("Got {} from Wasm memory address 0x{:X}", inner_val, ptr.offset()); @@ -39,7 +37,7 @@ pub type WasmPtr64 = WasmPtr; /// # use wasmer::Memory; /// # use wasmer::WasmPtr; /// # use wasmer::ValueType; -/// # use wasmer::ContextMut; +/// # use wasmer::FunctionEnvMut; /// /// // This is safe as the 12 bytes represented by this struct /// // are valid for all bit combinations. @@ -51,7 +49,7 @@ pub type WasmPtr64 = WasmPtr; /// z: f32 /// } /// -/// fn update_vector_3(mut ctx: ContextMut<()>, memory: Memory, ptr: WasmPtr) { +/// fn update_vector_3(mut ctx: FunctionEnvMut<()>, memory: Memory, ptr: WasmPtr) { /// let derefed_ptr = ptr.deref(&mut ctx, &memory); /// let mut inner_val: V3 = derefed_ptr.read().expect("pointer in bounds"); /// println!("Got {:?} from Wasm memory address 0x{:X}", inner_val, ptr.offset()); @@ -144,13 +142,13 @@ impl WasmPtr { /// Creates a `WasmRef` from this `WasmPtr` which allows reading and /// mutating of the value being pointed to. #[inline] - pub fn deref<'a>(self, ctx: &'a impl AsContextRef, memory: &'a Memory) -> WasmRef<'a, T> { + pub fn deref<'a>(self, ctx: &'a impl AsStoreRef, memory: &'a Memory) -> WasmRef<'a, T> { WasmRef::new(ctx, memory, self.offset.into()) } /// Reads the address pointed to by this `WasmPtr` in a memory. #[inline] - pub fn read(self, ctx: &impl AsContextRef, memory: &Memory) -> Result { + pub fn read(self, ctx: &impl AsStoreRef, memory: &Memory) -> Result { self.deref(&ctx, memory).read() } @@ -158,7 +156,7 @@ impl WasmPtr { #[inline] pub fn write( self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, memory: &Memory, val: T, ) -> Result<(), MemoryAccessError> { @@ -173,7 +171,7 @@ impl WasmPtr { #[inline] pub fn slice<'a>( self, - ctx: &'a impl AsContextRef, + ctx: &'a impl AsStoreRef, memory: &'a Memory, len: M::Offset, ) -> Result, MemoryAccessError> { @@ -187,7 +185,7 @@ impl WasmPtr { #[inline] pub fn read_until( self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, memory: &Memory, mut end: impl FnMut(&T) -> bool, ) -> Result, MemoryAccessError> { @@ -212,7 +210,7 @@ impl WasmPtr { #[inline] pub fn read_utf8_string( self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, memory: &Memory, len: M::Offset, ) -> Result { @@ -227,7 +225,7 @@ impl WasmPtr { #[inline] pub fn read_utf8_string_with_nul( self, - ctx: &impl AsContextRef, + ctx: &impl AsStoreRef, memory: &Memory, ) -> Result { let vec = self.read_until(ctx, memory, |&byte| byte == 0)?; diff --git a/lib/api/src/sys/store.rs b/lib/api/src/sys/store.rs index ad8c2bce2c7..862ebda5b61 100644 --- a/lib/api/src/sys/store.rs +++ b/lib/api/src/sys/store.rs @@ -1,9 +1,21 @@ use crate::sys::tunables::BaseTunables; use std::fmt; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use wasmer_compiler::CompilerConfig; use wasmer_compiler::{Engine, Tunables, Universal}; -use wasmer_vm::{init_traps, TrapHandler, TrapHandlerFn}; +use wasmer_vm::{init_traps, TrapHandlerFn}; + +use wasmer_vm::StoreObjects; + +/// We require the context to have a fixed memory address for its lifetime since +/// various bits of the VM have raw pointers that point back to it. Hence we +/// wrap the actual context in a box. +pub(crate) struct StoreInner { + pub(crate) objects: StoreObjects, + pub(crate) engine: Arc, + pub(crate) tunables: Box, + pub(crate) trap_handler: Option>>, +} /// The store represents all global state that can be manipulated by /// WebAssembly programs. It consists of the runtime representation @@ -15,11 +27,8 @@ use wasmer_vm::{init_traps, TrapHandler, TrapHandlerFn}; /// [`Tunables`] (that are used to create the memories, tables and globals). /// /// Spec: -#[derive(Clone)] pub struct Store { - engine: Arc, - tunables: Arc, - trap_handler: Arc>>>, + pub(crate) inner: Box, } impl Store { @@ -38,9 +47,8 @@ impl Store { } /// Set the trap handler in this store. - pub fn set_trap_handler(&self, handler: Option>) { - let mut m = self.trap_handler.write().unwrap(); - *m = handler; + pub fn set_trap_handler(&mut self, handler: Option>>) { + self.inner.trap_handler = handler; } /// Creates a new `Store` with a specific [`Engine`] and [`Tunables`]. @@ -53,45 +61,21 @@ impl Store { init_traps(); Self { - engine: engine.cloned(), - tunables: Arc::new(tunables), - trap_handler: Arc::new(RwLock::new(None)), + inner: Box::new(StoreInner { + objects: Default::default(), + engine: engine.cloned(), + tunables: Box::new(tunables), + trap_handler: None, + }), } } - - /// Returns the [`Tunables`]. - pub fn tunables(&self) -> &dyn Tunables { - self.tunables.as_ref() - } - - /// Returns the [`Engine`]. - pub fn engine(&self) -> &Arc { - &self.engine - } - - /// Checks whether two stores are identical. A store is considered - /// equal to another store if both have the same engine. The - /// tunables are excluded from the logic. - pub fn same(a: &Self, b: &Self) -> bool { - a.engine.id() == b.engine.id() - } -} - -impl PartialEq for Store { - fn eq(&self, other: &Self) -> bool { - Self::same(self, other) - } } -unsafe impl TrapHandler for Store { - fn custom_trap_handler(&self, call: &dyn Fn(&TrapHandlerFn) -> bool) -> bool { - if let Some(handler) = self.trap_handler.read().unwrap().as_ref() { - call(handler) - } else { - false - } - } -} +// impl PartialEq for Store { +// fn eq(&self, other: &Self) -> bool { +// Self::same(self, other) +// } +// } // This is required to be able to set the trap_handler in the // Store. @@ -139,8 +123,151 @@ impl Default for Store { } } +impl AsStoreRef for Store { + fn as_store_ref(&self) -> StoreRef<'_> { + StoreRef { inner: &self.inner } + } +} +impl AsStoreMut for Store { + fn as_store_mut(&mut self) -> StoreMut<'_> { + StoreMut { + inner: &mut self.inner, + } + } + fn objects_mut(&mut self) -> &mut StoreObjects { + &mut self.inner.objects + } +} + impl fmt::Debug for Store { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Store").finish() } } + +/// A temporary handle to a [`Context`]. +pub struct StoreRef<'a> { + pub(crate) inner: &'a StoreInner, +} + +impl<'a> StoreRef<'a> { + pub(crate) fn objects(&self) -> &'a StoreObjects { + &self.inner.objects + } + + /// Returns the [`Tunables`]. + pub fn tunables(&self) -> &dyn Tunables { + self.inner.tunables.as_ref() + } + + /// Returns the [`Engine`]. + pub fn engine(&self) -> &Arc { + &self.inner.engine + } + + /// Checks whether two stores are identical. A store is considered + /// equal to another store if both have the same engine. The + /// tunables are excluded from the logic. + pub fn same(a: &Self, b: &Self) -> bool { + a.inner.engine.id() == b.inner.engine.id() + } + + /// The signal handler + #[inline] + pub fn signal_handler(&self) -> Option<*const TrapHandlerFn<'static>> { + self.inner + .trap_handler + .as_ref() + .map(|handler| &*handler as *const _) + } +} + +/// A temporary handle to a [`Context`]. +pub struct StoreMut<'a> { + pub(crate) inner: &'a mut StoreInner, +} + +impl<'a> StoreMut<'a> { + /// Returns the [`Tunables`]. + pub fn tunables(&self) -> &dyn Tunables { + self.inner.tunables.as_ref() + } + + /// Returns the [`Engine`]. + pub fn engine(&self) -> &Arc { + &self.inner.engine + } + + /// Checks whether two stores are identical. A store is considered + /// equal to another store if both have the same engine. The + /// tunables are excluded from the logic. + pub fn same(a: &Self, b: &Self) -> bool { + a.inner.engine.id() == b.inner.engine.id() + } + + pub(crate) fn tunables_and_objects_mut(&mut self) -> (&dyn Tunables, &mut StoreObjects) { + (self.inner.tunables.as_ref(), &mut self.inner.objects) + } + + pub(crate) fn as_raw(&self) -> *mut StoreInner { + self.inner as *const StoreInner as *mut StoreInner + } + + pub(crate) unsafe fn from_raw(raw: *mut StoreInner) -> Self { + Self { inner: &mut *raw } + } +} + +/// Helper trait for a value that is convertible to a [`StoreRef`]. +pub trait AsStoreRef { + /// Returns a `StoreRef` pointing to the underlying context. + fn as_store_ref(&self) -> StoreRef<'_>; +} + +/// Helper trait for a value that is convertible to a [`StoreMut`]. +pub trait AsStoreMut: AsStoreRef { + /// Returns a `StoreMut` pointing to the underlying context. + fn as_store_mut(&mut self) -> StoreMut<'_>; + + /// Returns the ObjectMutable + fn objects_mut(&mut self) -> &mut StoreObjects; +} + +impl AsStoreRef for StoreRef<'_> { + fn as_store_ref(&self) -> StoreRef<'_> { + StoreRef { inner: self.inner } + } +} + +impl AsStoreRef for StoreMut<'_> { + fn as_store_ref(&self) -> StoreRef<'_> { + StoreRef { inner: self.inner } + } +} +impl AsStoreMut for StoreMut<'_> { + fn as_store_mut(&mut self) -> StoreMut<'_> { + StoreMut { inner: self.inner } + } + fn objects_mut(&mut self) -> &mut StoreObjects { + &mut self.inner.objects + } +} + +impl AsStoreRef for &'_ T { + fn as_store_ref(&self) -> StoreRef<'_> { + T::as_store_ref(*self) + } +} +impl AsStoreRef for &'_ mut T { + fn as_store_ref(&self) -> StoreRef<'_> { + T::as_store_ref(*self) + } +} +impl AsStoreMut for &'_ mut T { + fn as_store_mut(&mut self) -> StoreMut<'_> { + T::as_store_mut(*self) + } + fn objects_mut(&mut self) -> &mut StoreObjects { + T::objects_mut(*self) + } +} diff --git a/lib/api/src/sys/value.rs b/lib/api/src/sys/value.rs index 03414a70483..d681692fcb3 100644 --- a/lib/api/src/sys/value.rs +++ b/lib/api/src/sys/value.rs @@ -9,8 +9,7 @@ use wasmer_vm::VMFuncRef; use crate::ExternRef; use crate::Function; -use super::context::AsContextMut; -use super::context::AsContextRef; +use super::store::{AsStoreMut, AsStoreRef}; pub use wasmer_types::RawValue; @@ -92,7 +91,7 @@ impl Value { } /// Converts the `Value` into a `RawValue`. - pub fn as_raw(&self, ctx: &impl AsContextRef) -> RawValue { + pub fn as_raw(&self, ctx: &impl AsStoreRef) -> RawValue { match *self { Self::I32(i32) => RawValue { i32 }, Self::I64(i64) => RawValue { i64 }, @@ -111,7 +110,7 @@ impl Value { /// /// # Safety /// - pub unsafe fn from_raw(ctx: &mut impl AsContextMut, ty: Type, raw: RawValue) -> Self { + pub unsafe fn from_raw(ctx: &mut impl AsStoreMut, ty: Type, raw: RawValue) -> Self { match ty { Type::I32 => Self::I32(raw.i32), Type::I64 => Self::I64(raw.i64), @@ -134,7 +133,7 @@ impl Value { /// /// Externref and funcref values are tied to a context and can only be used /// with that context. - pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool { + pub fn is_from_store(&self, ctx: &impl AsStoreRef) -> bool { match self { Self::I32(_) | Self::I64(_) @@ -143,8 +142,8 @@ impl Value { | Self::V128(_) | Self::ExternRef(None) | Self::FuncRef(None) => true, - Self::ExternRef(Some(e)) => e.is_from_context(ctx), - Self::FuncRef(Some(f)) => f.is_from_context(ctx), + Self::ExternRef(Some(e)) => e.is_from_store(ctx), + Self::FuncRef(Some(f)) => f.is_from_store(ctx), } } diff --git a/lib/api/tests/js_externals.rs b/lib/api/tests/js_externals.rs index 187e6a6b1fe..a17aae4b76d 100644 --- a/lib/api/tests/js_externals.rs +++ b/lib/api/tests/js_externals.rs @@ -5,20 +5,20 @@ mod js { #[wasm_bindgen_test] fn global_new() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); - let global = Global::new(&mut ctx, Value::I32(10)); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); + let global = Global::new(&mut store, Value::I32(10)); assert_eq!( - global.ty(&ctx), + global.ty(&store), GlobalType { ty: Type::I32, mutability: Mutability::Const } ); - let global_mut = Global::new_mut(&mut ctx, Value::I32(10)); + let global_mut = Global::new_mut(&mut store, Value::I32(10)); assert_eq!( - global_mut.ty(&ctx), + global_mut.ty(&store), GlobalType { ty: Type::I32, mutability: Mutability::Var @@ -28,50 +28,50 @@ mod js { #[wasm_bindgen_test] fn global_get() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); - let global_i32 = Global::new(&mut ctx, Value::I32(10)); - assert_eq!(global_i32.get(&ctx), Value::I32(10)); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); + let global_i32 = Global::new(&mut store, Value::I32(10)); + assert_eq!(global_i32.get(&store), Value::I32(10)); // 64-bit values are not yet fully supported in some versions of Node // Commenting this tests for now: // let global_i64 = Global::new(&store, Value::I64(20)); // assert_eq!(global_i64.get(), Value::I64(20)); - let global_f32 = Global::new(&mut ctx, Value::F32(10.0)); - assert_eq!(global_f32.get(&ctx), Value::F32(10.0)); + let global_f32 = Global::new(&mut store, Value::F32(10.0)); + assert_eq!(global_f32.get(&store), Value::F32(10.0)); // let global_f64 = Global::new(&store, Value::F64(20.0)); // assert_eq!(global_f64.get(), Value::F64(20.0)); } #[wasm_bindgen_test] fn global_set() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); - let global_i32 = Global::new(&mut ctx, Value::I32(10)); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); + let global_i32 = Global::new(&mut store, Value::I32(10)); // Set on a constant should error - assert!(global_i32.set(&mut ctx, Value::I32(20)).is_err()); + assert!(global_i32.set(&mut store, Value::I32(20)).is_err()); - let global_i32_mut = Global::new_mut(&mut ctx, Value::I32(10)); + let global_i32_mut = Global::new_mut(&mut store, Value::I32(10)); // Set on different type should error - assert!(global_i32_mut.set(&mut ctx, Value::I64(20)).is_err()); + assert!(global_i32_mut.set(&mut store, Value::I64(20)).is_err()); // Set on same type should succeed - global_i32_mut.set(&mut ctx, Value::I32(20)).unwrap(); - assert_eq!(global_i32_mut.get(&ctx), Value::I32(20)); + global_i32_mut.set(&mut store, Value::I32(20)).unwrap(); + assert_eq!(global_i32_mut.get(&store), Value::I32(20)); } #[wasm_bindgen_test] fn table_new() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); let table_type = TableType { ty: Type::FuncRef, minimum: 0, maximum: None, }; - let f = Function::new_native(&mut ctx, |_: ContextMut<'_, ()>| {}); - let table = Table::new(&mut ctx, table_type, Value::FuncRef(Some(f))).unwrap(); - assert_eq!(table.ty(&ctx), table_type); + let f = Function::new_native(&mut store, &env, |_: FunctionEnvMut<'_, ()>| {}); + let table = Table::new(&mut store, table_type, Value::FuncRef(Some(f))).unwrap(); + assert_eq!(table.ty(&store), table_type); // table.get() // Anyrefs not yet supported @@ -81,7 +81,7 @@ mod js { // maximum: None, // }; // let table = Table::new(&store, table_type, Value::ExternRef(ExternRef::Null))?; - // assert_eq!(*table.ty(&ctx), table_type); + // assert_eq!(*table.ty(&store), table_type); } // Tables are not yet fully supported in Wasm @@ -90,16 +90,16 @@ mod js { // #[test] // #[ignore] // fn table_get() -> Result<()> { - // let store = Store::default(); - // let mut ctx = Context::new(&store, ()); + // let mut store = Store::default(); + // let mut env = FunctionEnv::new(&mut store, ()); // let table_type = TableType { // ty: Type::FuncRef, // minimum: 0, // maximum: Some(1), // }; - // let f = Function::new(&mut ctx, |num: i32| num + 1); + // let f = Function::new(&mut store, &env, |num: i32| num + 1); // let table = Table::new(&store, table_type, Value::FuncRef(Some(f.clone())))?; - // assert_eq!(*table.ty(&ctx), table_type); + // assert_eq!(*table.ty(&store), table_type); // let _elem = table.get(0).unwrap(); // // assert_eq!(elem.funcref().unwrap(), f); // Ok(()) @@ -114,14 +114,14 @@ mod js { // #[test] // fn table_grow() -> Result<()> { - // let store = Store::default(); - // let mut ctx = Context::new(&store, ()); + // let mut store = Store::default(); + // let mut env = FunctionEnv::new(&mut store, ()); // let table_type = TableType { // ty: Type::FuncRef, // minimum: 0, // maximum: Some(10), // }; - // let f = Function::new(&mut ctx, |num: i32| num + 1); + // let f = Function::new(&mut store, &env, |num: i32| num + 1); // let table = Table::new(&store, table_type, Value::FuncRef(Some(f.clone())))?; // // Growing to a bigger maximum should return None // let old_len = table.grow(12, Value::FuncRef(Some(f.clone()))); @@ -143,32 +143,32 @@ mod js { #[wasm_bindgen_test] fn memory_new() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); let memory_type = MemoryType { shared: false, minimum: Pages(0), maximum: Some(Pages(10)), }; - let memory = Memory::new(&mut ctx, memory_type).unwrap(); - assert_eq!(memory.size(&ctx), Pages(0)); - assert_eq!(memory.ty(&ctx), memory_type); + let memory = Memory::new(&mut store, memory_type).unwrap(); + assert_eq!(memory.size(&store), Pages(0)); + assert_eq!(memory.ty(&store), memory_type); } #[wasm_bindgen_test] fn memory_grow() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); let desc = MemoryType::new(Pages(10), Some(Pages(16)), false); - let memory = Memory::new(&mut ctx, desc).unwrap(); - assert_eq!(memory.size(&ctx), Pages(10)); + let memory = Memory::new(&mut store, desc).unwrap(); + assert_eq!(memory.size(&store), Pages(10)); - let result = memory.grow(&mut ctx, Pages(2)).unwrap(); + let result = memory.grow(&mut store, Pages(2)).unwrap(); assert_eq!(result, Pages(10)); - assert_eq!(memory.size(&ctx), Pages(12)); + assert_eq!(memory.size(&store), Pages(12)); - let result = memory.grow(&mut ctx, Pages(10)); + let result = memory.grow(&mut store, Pages(10)); assert!(result.is_err()); assert_eq!( result, @@ -181,235 +181,270 @@ mod js { #[wasm_bindgen_test] fn function_new() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<'_, ()>| {}); - assert_eq!(function.ty(&ctx).clone(), FunctionType::new(vec![], vec![])); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<'_, ()>, _a: i32| {}); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); + let function = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<'_, ()>| {}); assert_eq!( - function.ty(&ctx).clone(), + function.ty(&store).clone(), + FunctionType::new(vec![], vec![]) + ); + let function = + Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<'_, ()>, _a: i32| {}); + assert_eq!( + function.ty(&store).clone(), FunctionType::new(vec![Type::I32], vec![]) ); let function = Function::new_native( - &mut ctx, - |_ctx: ContextMut<'_, ()>, _a: i32, _b: i64, _c: f32, _d: f64| {}, + &mut store, + &env, + |_ctx: FunctionEnvMut<'_, ()>, _a: i32, _b: i64, _c: f32, _d: f64| {}, ); assert_eq!( - function.ty(&ctx).clone(), + function.ty(&store).clone(), FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) ); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<'_, ()>| -> i32 { 1 }); + let function = + Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<'_, ()>| -> i32 { + 1 + }); assert_eq!( - function.ty(&ctx).clone(), + function.ty(&store).clone(), FunctionType::new(vec![], vec![Type::I32]) ); let function = Function::new_native( - &mut ctx, - |_ctx: ContextMut<'_, ()>| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, + &mut store, + &env, + |_ctx: FunctionEnvMut<'_, ()>| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, ); assert_eq!( - function.ty(&ctx).clone(), + function.ty(&store).clone(), FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) ); } #[wasm_bindgen_test] fn function_new_env() { - let store = Store::default(); + let mut store = Store::default(); #[derive(Clone)] struct MyEnv {} let my_env = MyEnv {}; - let mut ctx = Context::new(&store, my_env); + let mut env = FunctionEnv::new(&mut store, my_env); - let function = Function::new_native(&mut ctx, |_: ContextMut<'_, MyEnv>| {}); - assert_eq!(function.ty(&ctx).clone(), FunctionType::new(vec![], vec![])); - let function = Function::new_native(&mut ctx, |_: ContextMut<'_, MyEnv>, _a: i32| {}); + let function = Function::new_native(&mut store, &env, |_: FunctionEnvMut<'_, MyEnv>| {}); + assert_eq!( + function.ty(&store).clone(), + FunctionType::new(vec![], vec![]) + ); + let function = + Function::new_native(&mut store, &env, |_: FunctionEnvMut<'_, MyEnv>, _a: i32| {}); assert_eq!( - function.ty(&ctx).clone(), + function.ty(&store).clone(), FunctionType::new(vec![Type::I32], vec![]) ); let function = Function::new_native( - &mut ctx, - |_: ContextMut<'_, MyEnv>, _a: i32, _b: i64, _c: f32, _d: f64| {}, + &mut store, + &env, + |_: FunctionEnvMut<'_, MyEnv>, _a: i32, _b: i64, _c: f32, _d: f64| {}, ); assert_eq!( - function.ty(&ctx).clone(), + function.ty(&store).clone(), FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) ); - let function = Function::new_native(&mut ctx, |_: ContextMut<'_, MyEnv>| -> i32 { 1 }); + let function = + Function::new_native(&mut store, &env, |_: FunctionEnvMut<'_, MyEnv>| -> i32 { + 1 + }); assert_eq!( - function.ty(&ctx).clone(), + function.ty(&store).clone(), FunctionType::new(vec![], vec![Type::I32]) ); let function = Function::new_native( - &mut ctx, - |_: ContextMut<'_, MyEnv>| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, + &mut store, + &env, + |_: FunctionEnvMut<'_, MyEnv>| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, ); assert_eq!( - function.ty(&ctx).clone(), + function.ty(&store).clone(), FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) ); } #[wasm_bindgen_test] fn function_new_dynamic() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); // Using &FunctionType signature let function_type = FunctionType::new(vec![], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, ()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, ()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); let function_type = FunctionType::new(vec![Type::I32], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, ()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, ()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); let function_type = FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, ()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, ()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); let function_type = FunctionType::new(vec![], vec![Type::I32]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, ()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, ()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); let function_type = FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, ()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, ()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); // Using array signature let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); let function = Function::new( - &mut ctx, + &mut store, + &env, function_type, - |_ctx: ContextMut<'_, ()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, ()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).params(), [Type::V128]); + assert_eq!(function.ty(&store).params(), [Type::V128]); assert_eq!( - function.ty(&ctx).results(), + function.ty(&store).results(), [Type::I32, Type::F32, Type::F64] ); } #[wasm_bindgen_test] fn function_new_dynamic_env() { - let store = Store::default(); + let mut store = Store::default(); #[derive(Clone)] struct MyEnv {} let my_env = MyEnv {}; - let mut ctx = Context::new(&store, my_env); + let mut env = FunctionEnv::new(&mut store, my_env); // Using &FunctionType signature let function_type = FunctionType::new(vec![], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); let function_type = FunctionType::new(vec![Type::I32], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); let function_type = FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); let function_type = FunctionType::new(vec![], vec![Type::I32]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); let function_type = FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).clone(), function_type); + assert_eq!(function.ty(&store).clone(), function_type); // Using array signature let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); let function = Function::new( - &mut ctx, + &mut store, + &env, function_type, - |_ctx: ContextMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<'_, MyEnv>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&ctx).params(), [Type::V128]); + assert_eq!(function.ty(&store).params(), [Type::V128]); assert_eq!( - function.ty(&ctx).results(), + function.ty(&store).results(), [Type::I32, Type::F32, Type::F64] ); } #[wasm_bindgen_test] fn native_function_works() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); - let function = Function::new_native(&mut ctx, |_: ContextMut<'_, ()>| {}); - let typed_function: TypedFunction<(), ()> = function.native(&mut ctx).unwrap(); - let result = typed_function.call(&mut ctx); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); + let function = Function::new_native(&mut store, &env, |_: FunctionEnvMut<'_, ()>| {}); + let typed_function: TypedFunction<(), ()> = function.native(&mut store).unwrap(); + let result = typed_function.call(&mut store); assert!(result.is_ok()); - let function = - Function::new_native(&mut ctx, |_: ContextMut<'_, ()>, a: i32| -> i32 { a + 1 }); - let typed_function: TypedFunction = function.native(&mut ctx).unwrap(); - assert_eq!(typed_function.call(&mut ctx, 3).unwrap(), 4); + let function = Function::new_native( + &mut store, + &env, + |_: FunctionEnvMut<'_, ()>, a: i32| -> i32 { a + 1 }, + ); + let typed_function: TypedFunction = function.native(&mut store).unwrap(); + assert_eq!(typed_function.call(&mut store, 3).unwrap(), 4); // fn rust_abi(a: i32, b: i64, c: f32, d: f64) -> u64 { // (a as u64 * 1000) + (b as u64 * 100) + (c as u64 * 10) + (d as u64) // } - // let function = Function::new(&mut ctx, rust_abi); - // let typed_function: TypedFunction<(i32, i64, f32, f64), u64> = function.native(&mut ctx).unwrap(); + // let function = Function::new(&mut store, &env, rust_abi); + // let typed_function: TypedFunction<(i32, i64, f32, f64), u64> = function.native(&mut store).unwrap(); // assert_eq!(typed_function.call(8, 4, 1.5, 5.).unwrap(), 8415); - let function = Function::new_native(&mut ctx, |_: ContextMut<'_, ()>| -> i32 { 1 }); - let typed_function: TypedFunction<(), i32> = function.native(&mut ctx).unwrap(); - assert_eq!(typed_function.call(&mut ctx).unwrap(), 1); + let function = + Function::new_native(&mut store, &env, |_: FunctionEnvMut<'_, ()>| -> i32 { 1 }); + let typed_function: TypedFunction<(), i32> = function.native(&mut store).unwrap(); + assert_eq!(typed_function.call(&mut store).unwrap(), 1); - let function = Function::new_native(&mut ctx, |_: ContextMut<'_, ()>, _a: i32| {}); - let typed_function: TypedFunction = function.native(&mut ctx).unwrap(); - assert!(typed_function.call(&mut ctx, 4).is_ok()); + let function = + Function::new_native(&mut store, &env, |_: FunctionEnvMut<'_, ()>, _a: i32| {}); + let typed_function: TypedFunction = function.native(&mut store).unwrap(); + assert!(typed_function.call(&mut store, 4).is_ok()); - // let function = Function::new(&mut ctx, || -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }); - // let typed_function: TypedFunction<(), (i32, i64, f32, f64)> = function.native(&mut ctx).unwrap(); + // let function = Function::new(&mut store, &env, || -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }); + // let typed_function: TypedFunction<(), (i32, i64, f32, f64)> = function.native(&mut store).unwrap(); // assert_eq!(typed_function.call().unwrap(), (1, 2, 3.0, 4.0)); } #[wasm_bindgen_test] fn function_outlives_instance() { - let store = Store::default(); - let mut ctx = Context::new(&store, ()); + let mut store = Store::default(); + let mut env = FunctionEnv::new(&mut store, ()); let wat = r#"(module (type $sum_t (func (param i32 i32) (result i32))) (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) @@ -421,18 +456,18 @@ mod js { let f = { let module = Module::new(&store, wat).unwrap(); - let instance = Instance::new(&mut ctx, &module, &imports! {}).unwrap(); + let instance = Instance::new(&mut store, &module, &imports! {}).unwrap(); let f = instance.exports.get_function("sum").unwrap(); assert_eq!( - f.call(&mut ctx, &[Val::I32(4), Val::I32(5)]).unwrap(), + f.call(&mut store, &[Val::I32(4), Val::I32(5)]).unwrap(), vec![Val::I32(9)].into_boxed_slice() ); f.clone() }; assert_eq!( - f.call(&mut ctx, &[Val::I32(4), Val::I32(5)]).unwrap(), + f.call(&mut store, &[Val::I32(4), Val::I32(5)]).unwrap(), vec![Val::I32(9)].into_boxed_slice() ); } diff --git a/lib/api/tests/js_instance.rs b/lib/api/tests/js_instance.rs index c64d2e45431..c1d6102abe6 100644 --- a/lib/api/tests/js_instance.rs +++ b/lib/api/tests/js_instance.rs @@ -23,7 +23,7 @@ mod js { #[wasm_bindgen_test] fn test_exported_memory() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -41,24 +41,24 @@ mod js { .unwrap(); let import_object = imports! {}; - let mut ctx = Context::new(&store, ()); - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let mut env = FunctionEnv::new(&mut store, ()); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let memory = instance.exports.get_memory("mem").unwrap(); - assert!(memory.is_from_context(&ctx)); - assert_eq!(memory.ty(&ctx), MemoryType::new(Pages(1), None, false)); - assert_eq!(memory.size(&ctx), Pages(1)); - assert_eq!(memory.data_size(&ctx), 65536); - - memory.grow(&mut ctx, Pages(1)).unwrap(); - assert_eq!(memory.ty(&ctx), MemoryType::new(Pages(1), None, false)); - assert_eq!(memory.size(&ctx), Pages(2)); - assert_eq!(memory.data_size(&ctx), 65536 * 2); + assert!(memory.is_from_store(&store)); + assert_eq!(memory.ty(&store), MemoryType::new(Pages(1), None, false)); + assert_eq!(memory.size(&store), Pages(1)); + assert_eq!(memory.data_size(&store), 65536); + + memory.grow(&mut store, Pages(1)).unwrap(); + assert_eq!(memory.ty(&store), MemoryType::new(Pages(1), None, false)); + assert_eq!(memory.size(&store), Pages(2)); + assert_eq!(memory.data_size(&store), 65536 * 2); } #[wasm_bindgen_test] fn test_exported_function() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -81,22 +81,22 @@ mod js { .unwrap(); let import_object = imports! {}; - let mut ctx = Context::new(&store, ()); - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let mut env = FunctionEnv::new(&mut store, ()); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let get_magic = instance.exports.get_function("get_magic").unwrap(); assert_eq!( - get_magic.ty(&ctx).clone(), + get_magic.ty(&store).clone(), FunctionType::new(vec![], vec![Type::I32]) ); let expected = vec![Val::I32(42)].into_boxed_slice(); - assert_eq!(get_magic.call(&mut ctx, &[]).unwrap(), expected); + assert_eq!(get_magic.call(&mut store, &[]).unwrap(), expected); } #[wasm_bindgen_test] fn test_imported_function_dynamic() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -121,11 +121,11 @@ mod js { ))], }) .unwrap(); - let mut ctx = Context::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let imported_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); - let imported = Function::new(&mut ctx, imported_signature, |_env, args| { + let imported = Function::new(&mut store, &env, imported_signature, |_env, args| { log!("Calling `imported`..."); let result = args[0].unwrap_i32() * 2; log!("Result of `imported`: {:?}", result); @@ -137,19 +137,19 @@ mod js { "imported" => imported, } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let exported = instance.exports.get_function("exported").unwrap(); let expected = vec![Val::I32(6)].into_boxed_slice(); - assert_eq!(exported.call(&mut ctx, &[Val::I32(3)]).unwrap(), expected); + assert_eq!(exported.call(&mut store, &[Val::I32(3)]).unwrap(), expected); } // We comment it for now because in old versions of Node, only single return values are supported // #[wasm_bindgen_test] // fn test_imported_function_dynamic_multivalue() { - // let store = Store::default(); + // let mut store = Store::default(); // let mut module = Module::new( // &store, // br#" @@ -207,7 +207,7 @@ mod js { #[wasm_bindgen_test] fn test_imported_function_dynamic_with_env() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -238,10 +238,10 @@ mod js { multiplier: i32, } - let mut ctx = Context::new(&store, Env { multiplier: 3 }); + let mut env = FunctionEnv::new(&mut store, Env { multiplier: 3 }); let imported_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); - let imported = Function::new(&mut ctx, &imported_signature, |ctx, args| { + let imported = Function::new(&mut store, &env, &imported_signature, |ctx, args| { log!("Calling `imported`..."); let result = args[0].unwrap_i32() * ctx.data().multiplier; log!("Result of `imported`: {:?}", result); @@ -253,17 +253,17 @@ mod js { "imported" => imported, } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let exported = instance.exports.get_function("exported").unwrap(); let expected = vec![Val::I32(9)].into_boxed_slice(); - assert_eq!(exported.call(&mut ctx, &[Val::I32(3)]), Ok(expected)); + assert_eq!(exported.call(&mut store, &[Val::I32(3)]), Ok(expected)); } #[wasm_bindgen_test] fn test_imported_function_native() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -289,29 +289,29 @@ mod js { }) .unwrap(); - fn imported_fn(_: ContextMut<'_, ()>, arg: u32) -> u32 { + fn imported_fn(_: FunctionEnvMut<'_, ()>, arg: u32) -> u32 { return arg + 1; } - let mut ctx = Context::new(&store, ()); - let imported = Function::new_native(&mut ctx, imported_fn); + let mut env = FunctionEnv::new(&mut store, ()); + let imported = Function::new_native(&mut store, &env, imported_fn); let import_object = imports! { "env" => { "imported" => imported, } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let exported = instance.exports.get_function("exported").unwrap(); let expected = vec![Val::I32(5)].into_boxed_slice(); - assert_eq!(exported.call(&mut ctx, &[Val::I32(4)]), Ok(expected)); + assert_eq!(exported.call(&mut store, &[Val::I32(4)]), Ok(expected)); } #[wasm_bindgen_test] fn test_imported_function_native_with_env() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -342,33 +342,33 @@ mod js { multiplier: u32, } - fn imported_fn(ctx: ContextMut<'_, Env>, arg: u32) -> u32 { + fn imported_fn(ctx: FunctionEnvMut<'_, Env>, arg: u32) -> u32 { log!("inside imported_fn: ctx.data is {:?}", ctx.data()); - // log!("inside call id is {:?}", ctx.as_context_ref().objects().id); + // log!("inside call id is {:?}", ctx.as_store_ref().objects().id); return ctx.data().multiplier * arg; } - let mut ctx = Context::new(&store, Env { multiplier: 3 }); + let mut env = FunctionEnv::new(&mut store, Env { multiplier: 3 }); - let imported = Function::new_native(&mut ctx, imported_fn); + let imported = Function::new_native(&mut store, &env, imported_fn); let import_object = imports! { "env" => { "imported" => imported, } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let exported = instance.exports.get_function("exported").unwrap(); let expected = vec![Val::I32(12)].into_boxed_slice(); - ctx.data_mut().multiplier = 3; - assert_eq!(exported.call(&mut ctx, &[Val::I32(4)]), Ok(expected)); + env.as_mut(&mut store).multiplier = 3; + assert_eq!(exported.call(&mut store, &[Val::I32(4)]), Ok(expected)); } #[wasm_bindgen_test] fn test_imported_function_native_with_wasmer_env() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -401,76 +401,79 @@ mod js { memory: Option, } - fn imported_fn(ctx: ContextMut<'_, Env>, arg: u32) -> u32 { + fn imported_fn(ctx: FunctionEnvMut<'_, Env>, arg: u32) -> u32 { let memory: &Memory = ctx.data().memory.as_ref().unwrap(); let memory_val = memory.uint8view(&ctx).get_index(0); return (memory_val as u32) * ctx.data().multiplier * arg; } - let mut ctx = Context::new( - &store, + let mut env = FunctionEnv::new( + &mut store, Env { multiplier: 3, memory: None, }, ); - let imported = Function::new_native(&mut ctx, imported_fn); + let imported = Function::new_native(&mut store, &env, imported_fn); let import_object = imports! { "env" => { "imported" => imported, } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let memory = instance.exports.get_memory("memory").unwrap(); - assert_eq!(memory.data_size(&ctx), 65536); - let memory_val = memory.uint8view(&ctx).get_index(0); + assert_eq!(memory.data_size(&store), 65536); + let memory_val = memory.uint8view(&store).get_index(0); assert_eq!(memory_val, 0); - memory.uint8view(&ctx).set_index(0, 2); - let memory_val = memory.uint8view(&ctx).get_index(0); + memory.uint8view(&store).set_index(0, 2); + let memory_val = memory.uint8view(&store).get_index(0); assert_eq!(memory_val, 2); - ctx.data_mut().memory = Some(memory.clone()); + env.as_mut(&mut store).memory = Some(memory.clone()); let exported = instance.exports.get_function("exported").unwrap(); // It works with the provided memory let expected = vec![Val::I32(24)].into_boxed_slice(); - assert_eq!(exported.call(&mut ctx, &[Val::I32(4)]), Ok(expected)); + assert_eq!(exported.call(&mut store, &[Val::I32(4)]), Ok(expected)); // It works if we update the memory - memory.uint8view(&ctx).set_index(0, 3); + memory.uint8view(&store).set_index(0, 3); let expected = vec![Val::I32(36)].into_boxed_slice(); - assert_eq!(exported.call(&mut ctx, &[Val::I32(4)]), Ok(expected)); + assert_eq!(exported.call(&mut store, &[Val::I32(4)]), Ok(expected)); } #[wasm_bindgen_test] fn test_unit_native_function_env() { - let store = Store::default(); + let mut store = Store::default(); #[derive(Clone)] struct Env { multiplier: u32, } - let mut ctx = Context::new(&store, Env { multiplier: 3 }); + let mut env = FunctionEnv::new(&mut store, Env { multiplier: 3 }); - fn imported_fn(ctx: ContextMut<'_, Env>, args: &[Val]) -> Result, RuntimeError> { + fn imported_fn( + ctx: FunctionEnvMut<'_, Env>, + args: &[Val], + ) -> Result, RuntimeError> { let value = ctx.data().multiplier * args[0].unwrap_i32() as u32; return Ok(vec![Val::I32(value as _)]); } let imported_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); - let imported = Function::new(&mut ctx, imported_signature, imported_fn); + let imported = Function::new(&mut store, &env, imported_signature, imported_fn); let expected = vec![Val::I32(12)].into_boxed_slice(); - assert_eq!(imported.call(&mut ctx, &[Val::I32(4)]), Ok(expected)); + assert_eq!(imported.call(&mut store, &[Val::I32(4)]), Ok(expected)); } #[wasm_bindgen_test] fn test_imported_function_with_wasmer_env() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -503,15 +506,18 @@ mod js { memory: Option, } - fn imported_fn(ctx: ContextMut<'_, Env>, args: &[Val]) -> Result, RuntimeError> { + fn imported_fn( + ctx: FunctionEnvMut<'_, Env>, + args: &[Val], + ) -> Result, RuntimeError> { let memory: &Memory = ctx.data().memory.as_ref().unwrap(); let memory_val = memory.uint8view(&ctx).get_index(0); let value = (memory_val as u32) * ctx.data().multiplier * args[0].unwrap_i32() as u32; return Ok(vec![Val::I32(value as _)]); } - let mut ctx = Context::new( - &store, + let mut env = FunctionEnv::new( + &mut store, Env { multiplier: 3, memory: None, @@ -519,41 +525,41 @@ mod js { ); let imported_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); - let imported = Function::new(&mut ctx, imported_signature, imported_fn); + let imported = Function::new(&mut store, &env, imported_signature, imported_fn); let import_object = imports! { "env" => { "imported" => imported, } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let memory = instance.exports.get_memory("memory").unwrap(); - assert_eq!(memory.data_size(&ctx), 65536); - let memory_val = memory.uint8view(&ctx).get_index(0); + assert_eq!(memory.data_size(&store), 65536); + let memory_val = memory.uint8view(&store).get_index(0); assert_eq!(memory_val, 0); - memory.uint8view(&ctx).set_index(0, 2); - let memory_val = memory.uint8view(&ctx).get_index(0); + memory.uint8view(&store).set_index(0, 2); + let memory_val = memory.uint8view(&store).get_index(0); assert_eq!(memory_val, 2); - ctx.data_mut().memory = Some(memory.clone()); + env.as_mut(&mut store).memory = Some(memory.clone()); let exported = instance.exports.get_function("exported").unwrap(); // It works with the provided memory let expected = vec![Val::I32(24)].into_boxed_slice(); - assert_eq!(exported.call(&mut ctx, &[Val::I32(4)]), Ok(expected)); + assert_eq!(exported.call(&mut store, &[Val::I32(4)]), Ok(expected)); // It works if we update the memory - memory.uint8view(&ctx).set_index(0, 3); + memory.uint8view(&store).set_index(0, 3); let expected = vec![Val::I32(36)].into_boxed_slice(); - assert_eq!(exported.call(&mut ctx, &[Val::I32(4)]), Ok(expected)); + assert_eq!(exported.call(&mut store, &[Val::I32(4)]), Ok(expected)); } #[wasm_bindgen_test] fn test_imported_exported_global() { - let store = Store::default(); + let mut store = Store::default(); let mut module = Module::new( &store, br#" @@ -579,39 +585,39 @@ mod js { ], }) .unwrap(); - let mut ctx = Context::new(&store, ()); - let global = Global::new_mut(&mut ctx, Value::I32(0)); + let mut env = FunctionEnv::new(&mut store, ()); + let global = Global::new_mut(&mut store, Value::I32(0)); let import_object = imports! { "" => { "global" => global.clone() } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let get_global = instance.exports.get_function("getGlobal").unwrap(); assert_eq!( - get_global.call(&mut ctx, &[]), + get_global.call(&mut store, &[]), Ok(vec![Val::I32(0)].into_boxed_slice()) ); - global.set(&mut ctx, Value::I32(42)).unwrap(); + global.set(&mut store, Value::I32(42)).unwrap(); assert_eq!( - get_global.call(&mut ctx, &[]), + get_global.call(&mut store, &[]), Ok(vec![Val::I32(42)].into_boxed_slice()) ); let inc_global = instance.exports.get_function("incGlobal").unwrap(); - inc_global.call(&mut ctx, &[]).unwrap(); + inc_global.call(&mut store, &[]).unwrap(); assert_eq!( - get_global.call(&mut ctx, &[]), + get_global.call(&mut store, &[]), Ok(vec![Val::I32(43)].into_boxed_slice()) ); - assert_eq!(global.get(&ctx), Val::I32(43)); + assert_eq!(global.get(&store), Val::I32(43)); } #[wasm_bindgen_test] fn test_native_function() { - let store = Store::default(); + let mut store = Store::default(); let module = Module::new( &store, br#"(module @@ -623,30 +629,30 @@ mod js { ) .unwrap(); - fn sum(_: ContextMut<'_, ()>, a: i32, b: i32) -> i32 { + fn sum(_: FunctionEnvMut<'_, ()>, a: i32, b: i32) -> i32 { a + b } - let mut ctx = Context::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! { "env" => { - "sum" => Function::new_native(&mut ctx, sum), + "sum" => Function::new_native(&mut store, &env, sum), } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let add_one: TypedFunction = instance .exports - .get_typed_function(&ctx, "add_one") + .get_typed_function(&mut store, "add_one") .unwrap(); - assert_eq!(add_one.call(&mut ctx, 1), Ok(2)); + assert_eq!(add_one.call(&mut store, 1), Ok(2)); } #[wasm_bindgen_test] fn test_panic() { - let store = Store::default(); + let mut store = Store::default(); let module = Module::new( &store, br#" @@ -664,30 +670,32 @@ mod js { ) .unwrap(); - fn early_exit(_: ContextMut<'_, ()>) { + fn early_exit(_: FunctionEnvMut<'_, ()>) { panic!("Do panic") } - let mut ctx = Context::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! { "env" => { - "early_exit" => Function::new_native(&mut ctx, early_exit), + "early_exit" => Function::new_native(&mut store, &env, early_exit), } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); - let run_func: TypedFunction<(i32, i32), i32> = - instance.exports.get_typed_function(&ctx, "run").unwrap(); + let run_func: TypedFunction<(i32, i32), i32> = instance + .exports + .get_typed_function(&mut store, "run") + .unwrap(); assert!( - run_func.call(&mut ctx, 1, 7).is_err(), + run_func.call(&mut store, 1, 7).is_err(), "Expected early termination", ); let run_func = instance.exports.get_function("run").unwrap(); assert!( run_func - .call(&mut ctx, &[Val::I32(1), Val::I32(7)]) + .call(&mut store, &[Val::I32(1), Val::I32(7)]) .is_err(), "Expected early termination", ); @@ -695,7 +703,7 @@ mod js { #[wasm_bindgen_test] fn test_custom_error() { - let store = Store::default(); + let mut store = Store::default(); let module = Module::new( &store, br#" @@ -713,7 +721,7 @@ mod js { ) .unwrap(); - let mut ctx = Context::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); use std::fmt; @@ -728,17 +736,17 @@ mod js { impl std::error::Error for ExitCode {} - fn early_exit(_: ContextMut<'_, ()>) -> Result<(), ExitCode> { + fn early_exit(_: FunctionEnvMut<'_, ()>) -> Result<(), ExitCode> { Err(ExitCode(1)) } let import_object = imports! { "env" => { - "early_exit" => Function::new_native(&mut ctx, early_exit), + "early_exit" => Function::new_native(&mut store, &env, early_exit), } }; - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); fn test_result(result: Result) { match result { @@ -763,17 +771,19 @@ mod js { } } - let run_func: TypedFunction<(i32, i32), i32> = - instance.exports.get_typed_function(&ctx, "run").unwrap(); - test_result(run_func.call(&mut ctx, 1, 7)); + let run_func: TypedFunction<(i32, i32), i32> = instance + .exports + .get_typed_function(&mut store, "run") + .unwrap(); + test_result(run_func.call(&mut store, 1, 7)); let run_func = instance.exports.get_function("run").unwrap(); - test_result(run_func.call(&mut ctx, &[Val::I32(1), Val::I32(7)])); + test_result(run_func.call(&mut store, &[Val::I32(1), Val::I32(7)])); } #[wasm_bindgen_test] fn test_start_function_fails() { - let store = Store::default(); + let mut store = Store::default(); let module = Module::new( &store, br#" @@ -792,8 +802,8 @@ mod js { .unwrap(); let import_object = imports! {}; - let mut ctx = Context::new(&store, ()); - let result = Instance::new(&mut ctx, &module, &import_object); + let mut env = FunctionEnv::new(&mut store, ()); + let result = Instance::new(&mut store, &module, &import_object); let err = result.unwrap_err(); assert!(format!("{:?}", err).contains("zero")) } diff --git a/lib/api/tests/js_module.rs b/lib/api/tests/js_module.rs index a1c46e40a1a..3155e7e5f3b 100644 --- a/lib/api/tests/js_module.rs +++ b/lib/api/tests/js_module.rs @@ -6,7 +6,7 @@ mod js { #[wasm_bindgen_test] fn module_get_name() { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module)"#; let module = Module::new(&store, wat).unwrap(); assert_eq!(module.name(), None); @@ -14,7 +14,7 @@ mod js { #[wasm_bindgen_test] fn module_set_name() { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module $name)"#; let mut module = Module::new(&store, wat).unwrap(); @@ -32,12 +32,11 @@ mod js { let js_bytes = unsafe { Uint8Array::view(&binary) }; let js_module = WebAssembly::Module::new(&js_bytes.into()).unwrap(); let module: Module = js_module.into(); - assert_eq!(module.store(), &Store::default()); } #[wasm_bindgen_test] fn imports() { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (import "host" "func" (func)) (import "host" "memory" (memory 1)) @@ -108,7 +107,7 @@ mod js { #[wasm_bindgen_test] fn exports() { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (func (export "func") nop) (memory (export "memory") 2) @@ -182,7 +181,7 @@ mod js { // #[wasm_bindgen_test] // fn calling_host_functions_with_negative_values_works() { - // let store = Store::default(); + // let mut store = Store::default(); // let wat = r#"(module // (import "host" "host_func1" (func (param i64))) // (import "host" "host_func2" (func (param i32))) diff --git a/lib/api/tests/sys_externals.rs b/lib/api/tests/sys_externals.rs index d23ab50eeed..26be6969193 100644 --- a/lib/api/tests/sys_externals.rs +++ b/lib/api/tests/sys_externals.rs @@ -1,25 +1,24 @@ #[cfg(feature = "sys")] mod sys { use anyhow::Result; - use wasmer::Context as WasmerContext; + use wasmer::FunctionEnv; use wasmer::*; #[test] fn global_new() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let global = Global::new(&mut ctx, Value::I32(10)); + let mut store = Store::default(); + let global = Global::new(&mut store, Value::I32(10)); assert_eq!( - global.ty(&mut ctx), + global.ty(&mut store), GlobalType { ty: Type::I32, mutability: Mutability::Const } ); - let global_mut = Global::new_mut(&mut ctx, Value::I32(10)); + let global_mut = Global::new_mut(&mut store, Value::I32(10)); assert_eq!( - global_mut.ty(&mut ctx), + global_mut.ty(&mut store), GlobalType { ty: Type::I32, mutability: Mutability::Var @@ -31,51 +30,49 @@ mod sys { #[test] fn global_get() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let global_i32 = Global::new(&mut ctx, Value::I32(10)); - assert_eq!(global_i32.get(&mut ctx), Value::I32(10)); - let global_i64 = Global::new(&mut ctx, Value::I64(20)); - assert_eq!(global_i64.get(&mut ctx), Value::I64(20)); - let global_f32 = Global::new(&mut ctx, Value::F32(10.0)); - assert_eq!(global_f32.get(&mut ctx), Value::F32(10.0)); - let global_f64 = Global::new(&mut ctx, Value::F64(20.0)); - assert_eq!(global_f64.get(&mut ctx), Value::F64(20.0)); + let mut store = Store::default(); + let global_i32 = Global::new(&mut store, Value::I32(10)); + assert_eq!(global_i32.get(&mut store), Value::I32(10)); + let global_i64 = Global::new(&mut store, Value::I64(20)); + assert_eq!(global_i64.get(&mut store), Value::I64(20)); + let global_f32 = Global::new(&mut store, Value::F32(10.0)); + assert_eq!(global_f32.get(&mut store), Value::F32(10.0)); + let global_f64 = Global::new(&mut store, Value::F64(20.0)); + assert_eq!(global_f64.get(&mut store), Value::F64(20.0)); Ok(()) } #[test] fn global_set() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let global_i32 = Global::new(&mut ctx, Value::I32(10)); + let mut store = Store::default(); + let global_i32 = Global::new(&mut store, Value::I32(10)); // Set on a constant should error - assert!(global_i32.set(&mut ctx, Value::I32(20)).is_err()); + assert!(global_i32.set(&mut store, Value::I32(20)).is_err()); - let global_i32_mut = Global::new_mut(&mut ctx, Value::I32(10)); + let global_i32_mut = Global::new_mut(&mut store, Value::I32(10)); // Set on different type should error - assert!(global_i32_mut.set(&mut ctx, Value::I64(20)).is_err()); + assert!(global_i32_mut.set(&mut store, Value::I64(20)).is_err()); // Set on same type should succeed - global_i32_mut.set(&mut ctx, Value::I32(20))?; - assert_eq!(global_i32_mut.get(&mut ctx), Value::I32(20)); + global_i32_mut.set(&mut store, Value::I32(20))?; + assert_eq!(global_i32_mut.get(&mut store), Value::I32(20)); Ok(()) } #[test] fn table_new() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); let table_type = TableType { ty: Type::FuncRef, minimum: 0, maximum: None, }; - let f = Function::new_native(&mut ctx, |_ctx: ContextMut<()>| {}); - let table = Table::new(&mut ctx, table_type, Value::FuncRef(Some(f)))?; - assert_eq!(table.ty(&mut ctx), table_type); + let env = FunctionEnv::new(&mut store, ()); + let f = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>| {}); + let table = Table::new(&mut store, table_type, Value::FuncRef(Some(f)))?; + assert_eq!(table.ty(&mut store), table_type); // Anyrefs not yet supported // let table_type = TableType { @@ -92,17 +89,19 @@ mod sys { #[test] #[ignore] fn table_get() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); let table_type = TableType { ty: Type::FuncRef, minimum: 0, maximum: Some(1), }; - let f = Function::new_native(&mut ctx, |_ctx: ContextMut<()>, num: i32| num + 1); - let table = Table::new(&mut ctx, table_type, Value::FuncRef(Some(f)))?; - assert_eq!(table.ty(&mut ctx), table_type); - let _elem = table.get(&mut ctx, 0).unwrap(); + let f = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>, num: i32| { + num + 1 + }); + let table = Table::new(&mut store, table_type, Value::FuncRef(Some(f)))?; + assert_eq!(table.ty(&mut store), table_type); + let _elem = table.get(&mut store, 0).unwrap(); // assert_eq!(elem.funcref().unwrap(), f); Ok(()) } @@ -116,21 +115,23 @@ mod sys { #[test] fn table_grow() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); let table_type = TableType { ty: Type::FuncRef, minimum: 0, maximum: Some(10), }; - let f = Function::new_native(&mut ctx, |_ctx: ContextMut<()>, num: i32| num + 1); - let table = Table::new(&mut ctx, table_type, Value::FuncRef(Some(f.clone())))?; + let f = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>, num: i32| { + num + 1 + }); + let table = Table::new(&mut store, table_type, Value::FuncRef(Some(f.clone())))?; // Growing to a bigger maximum should return None - let old_len = table.grow(&mut ctx, 12, Value::FuncRef(Some(f.clone()))); + let old_len = table.grow(&mut store, 12, Value::FuncRef(Some(f.clone()))); assert!(old_len.is_err()); // Growing to a bigger maximum should return None - let old_len = table.grow(&mut ctx, 5, Value::FuncRef(Some(f)))?; + let old_len = table.grow(&mut store, 5, Value::FuncRef(Some(f)))?; assert_eq!(old_len, 0); Ok(()) @@ -145,32 +146,30 @@ mod sys { #[test] fn memory_new() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); let memory_type = MemoryType { shared: false, minimum: Pages(0), maximum: Some(Pages(10)), }; - let memory = Memory::new(&mut ctx, memory_type)?; - assert_eq!(memory.size(&mut ctx), Pages(0)); - assert_eq!(memory.ty(&mut ctx), memory_type); + let memory = Memory::new(&mut store, memory_type)?; + assert_eq!(memory.size(&mut store), Pages(0)); + assert_eq!(memory.ty(&mut store), memory_type); Ok(()) } #[test] fn memory_grow() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); let desc = MemoryType::new(Pages(10), Some(Pages(16)), false); - let memory = Memory::new(&mut ctx, desc)?; - assert_eq!(memory.size(&mut ctx), Pages(10)); + let memory = Memory::new(&mut store, desc)?; + assert_eq!(memory.size(&mut store), Pages(10)); - let result = memory.grow(&mut ctx, Pages(2)).unwrap(); + let result = memory.grow(&mut store, Pages(2)).unwrap(); assert_eq!(result, Pages(10)); - assert_eq!(memory.size(&mut ctx), Pages(12)); + assert_eq!(memory.size(&mut store), Pages(12)); - let result = memory.grow(&mut ctx, Pages(10)); + let result = memory.grow(&mut store, Pages(10)); assert_eq!( result, Err(MemoryError::CouldNotGrow { @@ -180,7 +179,7 @@ mod sys { ); let bad_desc = MemoryType::new(Pages(15), Some(Pages(10)), false); - let bad_result = Memory::new(&mut ctx, bad_desc); + let bad_result = Memory::new(&mut store, bad_desc); assert!(matches!(bad_result, Err(MemoryError::InvalidMemory { .. }))); @@ -189,37 +188,41 @@ mod sys { #[test] fn function_new() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<_>| {}); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); + let function = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>| {}); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![], vec![]) ); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<_>, _a: i32| {}); + let function = + Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>, _a: i32| {}); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![Type::I32], vec![]) ); let function = Function::new_native( - &mut ctx, - |_ctx: ContextMut<_>, _a: i32, _b: i64, _c: f32, _d: f64| {}, + &mut store, + &env, + |_ctx: FunctionEnvMut<()>, _a: i32, _b: i64, _c: f32, _d: f64| {}, ); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) ); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<_>| -> i32 { 1 }); + let function = + Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>| -> i32 { 1 }); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![], vec![Type::I32]) ); - let function = - Function::new_native(&mut ctx, |_ctx: ContextMut<_>| -> (i32, i64, f32, f64) { - (1, 2, 3.0, 4.0) - }); + let function = Function::new_native( + &mut store, + &env, + |_ctx: FunctionEnvMut<()>| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, + ); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) ); Ok(()) @@ -227,41 +230,45 @@ mod sys { #[test] fn function_new_env() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); #[derive(Clone)] struct MyEnv {} let my_env = MyEnv {}; - let mut ctx = WasmerContext::new(&store, my_env); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut| {}); + let env = FunctionEnv::new(&mut store, my_env); + let function = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut| {}); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![], vec![]) ); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut, _a: i32| {}); + let function = + Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut, _a: i32| {}); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![Type::I32], vec![]) ); let function = Function::new_native( - &mut ctx, - |_ctx: ContextMut, _a: i32, _b: i64, _c: f32, _d: f64| {}, + &mut store, + &env, + |_ctx: FunctionEnvMut, _a: i32, _b: i64, _c: f32, _d: f64| {}, ); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]) ); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut| -> i32 { 1 }); + let function = + Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut| -> i32 { 1 }); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![], vec![Type::I32]) ); let function = Function::new_native( - &mut ctx, - |_ctx: ContextMut| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, + &mut store, + &env, + |_ctx: FunctionEnvMut| -> (i32, i64, f32, f64) { (1, 2, 3.0, 4.0) }, ); assert_eq!( - function.ty(&mut ctx).clone(), + function.ty(&mut store).clone(), FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]) ); Ok(()) @@ -269,58 +276,64 @@ mod sys { #[test] fn function_new_dynamic() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); // Using &FunctionType signature let function_type = FunctionType::new(vec![], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); let function_type = FunctionType::new(vec![Type::I32], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); let function_type = FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); let function_type = FunctionType::new(vec![], vec![Type::I32]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); let function_type = FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut<()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); // Using array signature let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); let function = Function::new( - &mut ctx, + &mut store, + &env, function_type, - |_ctx: ContextMut<()>, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut<()>, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).params(), [Type::V128]); + assert_eq!(function.ty(&mut store).params(), [Type::V128]); assert_eq!( - function.ty(&mut ctx).results(), + function.ty(&mut store).results(), [Type::I32, Type::F32, Type::F64] ); @@ -329,193 +342,199 @@ mod sys { #[test] fn function_new_dynamic_env() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); #[derive(Clone)] struct MyEnv {} let my_env = MyEnv {}; - let mut ctx = WasmerContext::new(&store, my_env); + let env = FunctionEnv::new(&mut store, my_env); // Using &FunctionType signature let function_type = FunctionType::new(vec![], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); let function_type = FunctionType::new(vec![Type::I32], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); let function_type = FunctionType::new(vec![Type::I32, Type::I64, Type::F32, Type::F64], vec![]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); let function_type = FunctionType::new(vec![], vec![Type::I32]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); let function_type = FunctionType::new(vec![], vec![Type::I32, Type::I64, Type::F32, Type::F64]); let function = Function::new( - &mut ctx, + &mut store, + &env, &function_type, - |_ctx: ContextMut, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).clone(), function_type); + assert_eq!(function.ty(&mut store).clone(), function_type); // Using array signature let function_type = ([Type::V128], [Type::I32, Type::F32, Type::F64]); let function = Function::new( - &mut ctx, + &mut store, + &env, function_type, - |_ctx: ContextMut, _values: &[Value]| unimplemented!(), + |_ctx: FunctionEnvMut, _values: &[Value]| unimplemented!(), ); - assert_eq!(function.ty(&mut ctx).params(), [Type::V128]); + assert_eq!(function.ty(&mut store).params(), [Type::V128]); assert_eq!( - function.ty(&mut ctx).results(), + function.ty(&mut store).results(), [Type::I32, Type::F32, Type::F64] ); Ok(()) } - #[test] - fn native_function_works() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<()>| {}); - let native_function: TypedFunction<(), ()> = function.native(&mut ctx).unwrap(); - let result = native_function.call(&mut ctx); - assert!(result.is_ok()); - - let function = - Function::new_native(&mut ctx, |_ctx: ContextMut<()>, a: i32| -> i32 { a + 1 }); - let native_function: TypedFunction = function.native(&mut ctx).unwrap(); - assert_eq!(native_function.call(&mut ctx, 3).unwrap(), 4); - - fn rust_abi(_ctx: ContextMut<()>, a: i32, b: i64, c: f32, d: f64) -> u64 { - (a as u64 * 1000) + (b as u64 * 100) + (c as u64 * 10) + (d as u64) - } - let function = Function::new_native(&mut ctx, rust_abi); - let native_function: TypedFunction<(i32, i64, f32, f64), u64> = - function.native(&mut ctx).unwrap(); - assert_eq!(native_function.call(&mut ctx, 8, 4, 1.5, 5.).unwrap(), 8415); - - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<()>| -> i32 { 1 }); - let native_function: TypedFunction<(), i32> = function.native(&mut ctx).unwrap(); - assert_eq!(native_function.call(&mut ctx).unwrap(), 1); - - let function = Function::new_native(&mut ctx, |_ctx: ContextMut<()>, _a: i32| {}); - let native_function: TypedFunction = function.native(&mut ctx).unwrap(); - assert!(native_function.call(&mut ctx, 4).is_ok()); - - let function = - Function::new_native(&mut ctx, |_ctx: ContextMut<()>| -> (i32, i64, f32, f64) { - (1, 2, 3.0, 4.0) - }); - let native_function: TypedFunction<(), (i32, i64, f32, f64)> = - function.native(&mut ctx).unwrap(); - assert_eq!(native_function.call(&mut ctx).unwrap(), (1, 2, 3.0, 4.0)); - - Ok(()) - } - - #[test] - fn function_outlives_instance() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let wat = r#"(module - (type $sum_t (func (param i32 i32) (result i32))) - (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add) - (export "sum" (func $sum_f))) -"#; - - let f = { - let module = Module::new(&store, wat)?; - let instance = Instance::new(&mut ctx, &module, &imports! {})?; - let f: TypedFunction<(i32, i32), i32> = - instance.exports.get_typed_function(&mut ctx, "sum")?; - - assert_eq!(f.call(&mut ctx, 4, 5)?, 9); - f - }; - - assert_eq!(f.call(&mut ctx, 4, 5)?, 9); - - Ok(()) - } - /* - #[test] - fn weak_instance_ref_externs_after_instance() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); - let wat = r#"(module - (memory (export "mem") 1) - (type $sum_t (func (param i32 i32) (result i32))) - (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add) - (export "sum" (func $sum_f))) - "#; - - let f = { - let module = Module::new(&store, wat)?; - let instance = Instance::new(&mut ctx, &module, &imports! {})?; - let f: TypedFunction<(i32, i32), i32> = - instance.exports.get_with_generics_weak("sum")?; - - assert_eq!(f.call(&mut ctx, 4, 5)?, 9); - f - }; - - assert_eq!(f.call(&mut ctx, 4, 5)?, 9); - - Ok(()) - } - */ - #[test] - fn manually_generate_wasmer_env() -> Result<()> { - let store = Store::default(); - #[derive(Clone)] - struct MyEnv { - val: u32, - memory: Option, - } - - fn host_function(ctx: ContextMut, arg1: u32, arg2: u32) -> u32 { - ctx.data().val + arg1 + arg2 - } - - let mut env = MyEnv { - val: 5, - memory: None, - }; - let mut ctx = WasmerContext::new(&store, env); - - let result = host_function(ctx.as_context_mut(), 7, 9); - assert_eq!(result, 21); - - let memory = Memory::new(&mut ctx, MemoryType::new(0, None, false))?; - ctx.data_mut().memory = Some(memory); - - let result = host_function(ctx.as_context_mut(), 1, 2); - assert_eq!(result, 8); - - Ok(()) - } + // #[test] + // fn native_function_works() -> Result<()> { + // let mut store = Store::default(); + // let env = FunctionEnv::new(&mut store, ()); + // let function = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>| {}); + // let native_function: TypedFunction<(), ()> = function.native(&mut store).unwrap(); + // let result = native_function.call(&mut store); + // assert!(result.is_ok()); + + // let function = + // Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>, a: i32| -> i32 { a + 1 }); + // let native_function: TypedFunction = function.native(&mut store).unwrap(); + // assert_eq!(native_function.call(&mut store, 3).unwrap(), 4); + + // fn rust_abi(_ctx: FunctionEnvMut<()>, a: i32, b: i64, c: f32, d: f64) -> u64 { + // (a as u64 * 1000) + (b as u64 * 100) + (c as u64 * 10) + (d as u64) + // } + // let function = Function::new_native(&mut store, &env, rust_abi); + // let native_function: TypedFunction<(i32, i64, f32, f64), u64> = + // function.native(&mut store).unwrap(); + // assert_eq!(native_function.call(&mut store, 8, 4, 1.5, 5.).unwrap(), 8415); + + // let function = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>| -> i32 { 1 }); + // let native_function: TypedFunction<(), i32> = function.native(&mut store).unwrap(); + // assert_eq!(native_function.call(&mut store).unwrap(), 1); + + // let function = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>, _a: i32| {}); + // let native_function: TypedFunction = function.native(&mut store).unwrap(); + // assert!(native_function.call(&mut store, 4).is_ok()); + + // let function = + // Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>| -> (i32, i64, f32, f64) { + // (1, 2, 3.0, 4.0) + // }); + // let native_function: TypedFunction<(), (i32, i64, f32, f64)> = + // function.native(&mut store).unwrap(); + // assert_eq!(native_function.call(&mut store).unwrap(), (1, 2, 3.0, 4.0)); + + // Ok(()) + // } + + // #[test] + // fn function_outlives_instance() -> Result<()> { + // let mut store = Store::default(); + // let env = FunctionEnv::new(&mut store, ()); + // let wat = r#"(module + // (type $sum_t (func (param i32 i32) (result i32))) + // (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) + // local.get $x + // local.get $y + // i32.add) + // (export "sum" (func $sum_f))) + // "#; + + // let f = { + // let module = Module::new(&store, wat)?; + // let instance = Instance::new(&mut store, &module, &imports! {})?; + // let f: TypedFunction<(i32, i32), i32> = + // instance.exports.get_typed_function(&mut store, "sum")?; + + // assert_eq!(f.call(&mut store, 4, 5)?, 9); + // f + // }; + + // assert_eq!(f.call(&mut store, 4, 5)?, 9); + + // Ok(()) + // } + // /* + // #[test] + // fn weak_instance_ref_externs_after_instance() -> Result<()> { + // let mut store = Store::default(); + // let env = FunctionEnv::new(&mut store, ()); + // let wat = r#"(module + // (memory (export "mem") 1) + // (type $sum_t (func (param i32 i32) (result i32))) + // (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32) + // local.get $x + // local.get $y + // i32.add) + // (export "sum" (func $sum_f))) + // "#; + + // let f = { + // let module = Module::new(&store, wat)?; + // let instance = Instance::new(&mut store, &module, &imports! {})?; + // let f: TypedFunction<(i32, i32), i32> = + // instance.exports.get_with_generics_weak("sum")?; + + // assert_eq!(f.call(&mut store, 4, 5)?, 9); + // f + // }; + + // assert_eq!(f.call(&mut store, 4, 5)?, 9); + + // Ok(()) + // } + // */ + // #[test] + // fn manually_generate_wasmer_env() -> Result<()> { + // let mut store = Store::default(); + // #[derive(Clone)] + // struct MyEnv { + // val: u32, + // memory: Option, + // } + + // fn host_function(ctx: FunctionEnvMut, arg1: u32, arg2: u32) -> u32 { + // ctx.data().val + arg1 + arg2 + // } + + // let mut env = MyEnv { + // val: 5, + // memory: None, + // }; + // let env = FunctionEnv::new(&mut store, env); + + // let result = host_function(ctx.as_context_mut(), 7, 9); + // assert_eq!(result, 21); + + // let memory = Memory::new(&mut store, MemoryType::new(0, None, false))?; + // ctx.as_mut(&mut store).memory = Some(memory); + + // let result = host_function(ctx.as_context_mut(), 1, 2); + // assert_eq!(result, 8); + + // Ok(()) + // } } diff --git a/lib/api/tests/sys_instance.rs b/lib/api/tests/sys_instance.rs index d3eac9255eb..234bffe93b4 100644 --- a/lib/api/tests/sys_instance.rs +++ b/lib/api/tests/sys_instance.rs @@ -1,13 +1,12 @@ #[cfg(feature = "sys")] mod sys { use anyhow::Result; - use wasmer::Context as WasmerContext; + use wasmer::FunctionEnv; use wasmer::*; #[test] fn exports_work_after_multiple_instances_have_been_freed() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); let module = Module::new( &store, " @@ -22,7 +21,7 @@ mod sys { )?; let imports = Imports::new(); - let instance = Instance::new(&mut ctx, &module, &imports)?; + let instance = Instance::new(&mut store, &module, &imports)?; let instance2 = instance.clone(); let instance3 = instance.clone(); @@ -35,7 +34,7 @@ mod sys { // All instances have been dropped, but `sum` continues to work! assert_eq!( - sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)])? + sum.call(&mut store, &[Value::I32(1), Value::I32(2)])? .into_vec(), vec![Value::I32(3)], ); @@ -45,24 +44,31 @@ mod sys { #[test] fn unit_native_function_env() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); + #[derive(Clone)] struct Env { multiplier: u32, } - fn imported_fn(ctx: ContextMut, args: &[Value]) -> Result, RuntimeError> { + fn imported_fn( + ctx: FunctionEnvMut, + args: &[Value], + ) -> Result, RuntimeError> { let value = ctx.data().multiplier * args[0].unwrap_i32() as u32; Ok(vec![Value::I32(value as _)]) } + // We create the environment let env = Env { multiplier: 3 }; - let mut ctx = WasmerContext::new(&store, env); + // We move the environment to the store, so it can be used by the `Function` + let env = FunctionEnv::new(&mut store, env); + let imported_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); - let imported = Function::new(&mut ctx, imported_signature, imported_fn); + let imported = Function::new(&mut store, &env, imported_signature, imported_fn); let expected = vec![Value::I32(12)].into_boxed_slice(); - let result = imported.call(&mut ctx, &[Value::I32(4)])?; + let result = imported.call(&mut store, &[Value::I32(4)])?; assert_eq!(result, expected); Ok(()) diff --git a/lib/api/tests/sys_module.rs b/lib/api/tests/sys_module.rs index 7b5cf58f290..551e8aaae70 100644 --- a/lib/api/tests/sys_module.rs +++ b/lib/api/tests/sys_module.rs @@ -1,7 +1,7 @@ #[cfg(feature = "sys")] mod sys { use anyhow::Result; - use wasmer::Context as WasmerContext; + use wasmer::FunctionEnv; use wasmer::*; #[test] @@ -162,7 +162,7 @@ mod sys { #[test] fn calling_host_functions_with_negative_values_works() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (import "host" "host_func1" (func (param i64))) (import "host" "host_func2" (func (param i32))) @@ -191,78 +191,78 @@ mod sys { (call 7 (i32.const -1))) )"#; let module = Module::new(&store, wat)?; - let mut ctx = WasmerContext::new(&store, ()); + let env = FunctionEnv::new(&mut store, ()); let imports = imports! { "host" => { - "host_func1" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, p: u64| { + "host_func1" => Function::new_native(&mut store, &env,|_ctx: FunctionEnvMut<()>, p: u64| { println!("host_func1: Found number {}", p); assert_eq!(p, u64::max_value()); }), - "host_func2" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, p: u32| { + "host_func2" => Function::new_native(&mut store, &env,|_ctx: FunctionEnvMut<()>, p: u32| { println!("host_func2: Found number {}", p); assert_eq!(p, u32::max_value()); }), - "host_func3" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, p: i64| { + "host_func3" => Function::new_native(&mut store, &env,|_ctx: FunctionEnvMut<()>, p: i64| { println!("host_func3: Found number {}", p); assert_eq!(p, -1); }), - "host_func4" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, p: i32| { + "host_func4" => Function::new_native(&mut store, &env,|_ctx: FunctionEnvMut<()>, p: i32| { println!("host_func4: Found number {}", p); assert_eq!(p, -1); }), - "host_func5" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, p: i16| { + "host_func5" => Function::new_native(&mut store, &env,|_ctx: FunctionEnvMut<()>, p: i16| { println!("host_func5: Found number {}", p); assert_eq!(p, -1); }), - "host_func6" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, p: u16| { + "host_func6" => Function::new_native(&mut store, &env,|_ctx: FunctionEnvMut<()>, p: u16| { println!("host_func6: Found number {}", p); assert_eq!(p, u16::max_value()); }), - "host_func7" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, p: i8| { + "host_func7" => Function::new_native(&mut store, &env,|_ctx: FunctionEnvMut<()>, p: i8| { println!("host_func7: Found number {}", p); assert_eq!(p, -1); }), - "host_func8" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, p: u8| { + "host_func8" => Function::new_native(&mut store, &env,|_ctx: FunctionEnvMut<()>, p: u8| { println!("host_func8: Found number {}", p); assert_eq!(p, u8::max_value()); }), } }; - let instance = Instance::new(&mut ctx, &module, &imports)?; + let instance = Instance::new(&mut store, &module, &imports)?; let f1: TypedFunction<(), ()> = instance .exports - .get_typed_function(&mut ctx, "call_host_func1")?; + .get_typed_function(&mut store, "call_host_func1")?; let f2: TypedFunction<(), ()> = instance .exports - .get_typed_function(&mut ctx, "call_host_func2")?; + .get_typed_function(&mut store, "call_host_func2")?; let f3: TypedFunction<(), ()> = instance .exports - .get_typed_function(&mut ctx, "call_host_func3")?; + .get_typed_function(&mut store, "call_host_func3")?; let f4: TypedFunction<(), ()> = instance .exports - .get_typed_function(&mut ctx, "call_host_func4")?; + .get_typed_function(&mut store, "call_host_func4")?; let f5: TypedFunction<(), ()> = instance .exports - .get_typed_function(&mut ctx, "call_host_func5")?; + .get_typed_function(&mut store, "call_host_func5")?; let f6: TypedFunction<(), ()> = instance .exports - .get_typed_function(&mut ctx, "call_host_func6")?; + .get_typed_function(&mut store, "call_host_func6")?; let f7: TypedFunction<(), ()> = instance .exports - .get_typed_function(&mut ctx, "call_host_func7")?; + .get_typed_function(&mut store, "call_host_func7")?; let f8: TypedFunction<(), ()> = instance .exports - .get_typed_function(&mut ctx, "call_host_func8")?; + .get_typed_function(&mut store, "call_host_func8")?; - f1.call(&mut ctx)?; - f2.call(&mut ctx)?; - f3.call(&mut ctx)?; - f4.call(&mut ctx)?; - f5.call(&mut ctx)?; - f6.call(&mut ctx)?; - f7.call(&mut ctx)?; - f8.call(&mut ctx)?; + f1.call(&mut store)?; + f2.call(&mut store)?; + f3.call(&mut store)?; + f4.call(&mut store)?; + f5.call(&mut store)?; + f6.call(&mut store)?; + f7.call(&mut store)?; + f8.call(&mut store)?; Ok(()) } diff --git a/lib/api/tests/sys_reference_types.rs b/lib/api/tests/sys_reference_types.rs index c28ab852e47..b31b32b4b78 100644 --- a/lib/api/tests/sys_reference_types.rs +++ b/lib/api/tests/sys_reference_types.rs @@ -1,15 +1,14 @@ #[cfg(feature = "sys")] mod sys { use anyhow::Result; - use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; - use wasmer::Context as WasmerContext; + use wasmer::FunctionEnv; use wasmer::*; #[test] fn func_ref_passed_and_returned() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (import "env" "func_ref_identity" (func (param funcref) (result funcref))) (type $ret_i32_ty (func (result i32))) @@ -25,33 +24,37 @@ mod sys { #[derive(Clone, Debug)] pub struct Env(Arc); let env = Env(Arc::new(AtomicBool::new(false))); - let mut ctx = WasmerContext::new(&store, env); + let env = FunctionEnv::new(&mut store, env); let imports = imports! { "env" => { - "func_ref_identity" => Function::new(&mut ctx, FunctionType::new([Type::FuncRef], [Type::FuncRef]), |_ctx: ContextMut, values: &[Value]| -> Result, _> { + "func_ref_identity" => Function::new(&mut store, &env, FunctionType::new([Type::FuncRef], [Type::FuncRef]), |_ctx: FunctionEnvMut, values: &[Value]| -> Result, _> { Ok(vec![values[0].clone()]) }) }, }; - let instance = Instance::new(&mut ctx, &module, &imports)?; + let instance = Instance::new(&mut store, &module, &imports)?; let f: &Function = instance.exports.get_function("run")?; - let results = f.call(&mut ctx, &[]).unwrap(); + let results = f.call(&mut store, &[]).unwrap(); if let Value::FuncRef(fr) = &results[0] { assert!(fr.is_none()); } else { panic!("funcref not found!"); } - let func_to_call = Function::new_native(&mut ctx, |mut ctx: ContextMut| -> i32 { - ctx.data_mut().0.store(true, Ordering::SeqCst); - 343 - }); + let func_to_call = + Function::new_native(&mut store, &env, |mut ctx: FunctionEnvMut| -> i32 { + ctx.data_mut().0.store(true, Ordering::SeqCst); + 343 + }); let call_set_value: &Function = instance.exports.get_function("call_set_value")?; let results: Box<[Value]> = - call_set_value.call(&mut ctx, &[Value::FuncRef(Some(func_to_call))])?; - assert!(ctx.data().0.load(Ordering::SeqCst)); + call_set_value.call(&mut store, &[Value::FuncRef(Some(func_to_call))])?; + assert!(env + .as_mut(&mut store.as_store_mut()) + .0 + .load(Ordering::SeqCst)); assert_eq!(&*results, &[Value::I32(343)]); Ok(()) @@ -59,7 +62,7 @@ mod sys { #[test] fn func_ref_passed_and_called() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (func $func_ref_call (import "env" "func_ref_call") (param funcref) (result i32)) (type $ret_i32_ty (func (result i32))) @@ -78,9 +81,9 @@ mod sys { (call $func_ref_call (ref.func $product))) )"#; let module = Module::new(&store, wat)?; - let mut ctx = WasmerContext::new(&store, ()); + let env = FunctionEnv::new(&mut store, ()); fn func_ref_call( - mut ctx: ContextMut<()>, + mut ctx: FunctionEnvMut<()>, values: &[Value], ) -> Result, RuntimeError> { // TODO: look into `Box<[Value]>` being returned breakage @@ -92,47 +95,46 @@ mod sys { let imports = imports! { "env" => { "func_ref_call" => Function::new( - &mut ctx, + &mut store, + &env, FunctionType::new([Type::FuncRef], [Type::I32]), func_ref_call ), - // TODO(reftypes): this should work - /* - "func_ref_call_native" => Function::new_native(&store, |f: Function| -> Result { - let f: TypedFunction::<(i32, i32), i32> = f.native()?; - f.call(7, 9) - }) - */ + // "func_ref_call_native" => Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>, f: Function| -> Result { + // let f: TypedFunction::<(i32, i32), i32> = f.native(&mut store)?; + // f.call(&mut store, 7, 9) + // }) }, }; - let instance = Instance::new(&mut ctx, &module, &imports)?; + let instance = Instance::new(&mut store, &module, &imports)?; { - fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 { + fn sum(_ctx: FunctionEnvMut<()>, a: i32, b: i32) -> i32 { a + b } - let sum_func = Function::new_native(&mut ctx, sum); + let sum_func = Function::new_native(&mut store, &env, sum); let call_func: &Function = instance.exports.get_function("call_func")?; - let result = call_func.call(&mut ctx, &[Value::FuncRef(Some(sum_func))])?; + let result = call_func.call(&mut store, &[Value::FuncRef(Some(sum_func))])?; assert_eq!(result[0].unwrap_i32(), 16); } { let f: TypedFunction<(), i32> = instance .exports - .get_typed_function(&mut ctx, "call_host_func_with_wasm_func")?; - let result = f.call(&mut ctx)?; + .get_typed_function(&mut store, "call_host_func_with_wasm_func")?; + let result = f.call(&mut store)?; assert_eq!(result, 63); } Ok(()) } + /* #[test] fn extern_ref_passed_and_returned() -> Result<()> { - let store = Store::default(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = Store::default(); + let env = FunctionEnv::new(&mut store, ()); let wat = r#"(module (func $extern_ref_identity (import "env" "extern_ref_identity") (param externref) (result externref)) (func $extern_ref_identity_native (import "env" "extern_ref_identity_native") (param externref) (result externref)) @@ -149,15 +151,16 @@ mod sys { (call $get_new_extern_ref_native)) )"#; let module = Module::new(&store, wat)?; + let env = FunctionEnv::new(&mut store, ()); let imports = imports! { "env" => { - "extern_ref_identity" => Function::new(&mut ctx, FunctionType::new([Type::ExternRef], [Type::ExternRef]), |_ctx, values| -> Result, _> { + "extern_ref_identity" => Function::new(&mut store, &env, FunctionType::new([Type::ExternRef], [Type::ExternRef]), |_ctx, values| -> Result, _> { Ok(vec![values[0].clone()]) }), - "extern_ref_identity_native" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>, er: ExternRef| -> ExternRef { + "extern_ref_identity_native" => Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<()>, er: ExternRef| -> ExternRef { er }), - "get_new_extern_ref" => Function::new(&mut ctx, FunctionType::new([], [Type::ExternRef]), |_ctx, _| -> Result, _> { + "get_new_extern_ref" => Function::new(&mut store, &env, FunctionType::new([], [Type::ExternRef]), |_ctx, _| -> Result, _> { let inner = [("hello".to_string(), "world".to_string()), ("color".to_string(), "orange".to_string())] @@ -167,7 +170,7 @@ mod sys { let new_extern_ref = ExternRef::new(&mut ctx, inner); Ok(vec![Value::ExternRef(new_extern_ref)]) }), - "get_new_extern_ref_native" => Function::new_native(&mut ctx, |_ctx| -> ExternRef { + "get_new_extern_ref_native" => Function::new_native(&mut store, &env,|_ctx| -> ExternRef { let inner = [("hello".to_string(), "world".to_string()), ("color".to_string(), "orange".to_string())] @@ -217,11 +220,11 @@ mod sys { Ok(()) } - #[test] + #[test] // TODO(reftypes): reenable this test #[ignore] fn extern_ref_ref_counting_basic() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (func (export "drop") (param $er externref) (result) (drop (local.get $er))) @@ -241,7 +244,7 @@ mod sys { #[test] fn refs_in_globals() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (global $er_global (export "er_global") (mut externref) (ref.null extern)) (global $fr_global (export "fr_global") (mut funcref) (ref.null func)) @@ -306,7 +309,7 @@ mod sys { #[test] fn extern_ref_ref_counting_table_basic() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (global $global (export "global") (mut externref) (ref.null extern)) (table $table (export "table") 4 4 externref) @@ -348,7 +351,7 @@ mod sys { // TODO(reftypes): reenable this test #[ignore] fn extern_ref_ref_counting_global_basic() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (global $global (export "global") (mut externref) (ref.null extern)) (func $get_from_global (export "get_from_global") (result externref) @@ -379,7 +382,7 @@ mod sys { // TODO(reftypes): reenable this test #[ignore] fn extern_ref_ref_counting_traps() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (func $pass_er (export "pass_extern_ref") (param externref) (local.get 0) @@ -403,7 +406,7 @@ mod sys { #[test] fn extern_ref_ref_counting_table_instructions() -> Result<()> { - let store = Store::default(); + let mut store = Store::default(); let wat = r#"(module (table $table1 (export "table1") 2 12 externref) (table $table2 (export "table2") 6 12 externref) diff --git a/lib/c-api/examples/deprecated-header.c b/lib/c-api/examples/deprecated-header.c index 8e28bd78ef0..ee425c7cc12 100644 --- a/lib/c-api/examples/deprecated-header.c +++ b/lib/c-api/examples/deprecated-header.c @@ -21,8 +21,6 @@ int main(int argc, const char *argv[]) { printf("Initializing...\n"); own wasm_engine_t* engine = wasm_engine_new(); own wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // ===================== wasm_limits_t limits1 = { diff --git a/lib/c-api/examples/early-exit.c b/lib/c-api/examples/early-exit.c index 5bff06f343b..d2410ca8baf 100644 --- a/lib/c-api/examples/early-exit.c +++ b/lib/c-api/examples/early-exit.c @@ -29,7 +29,7 @@ void print_frame(wasm_frame_t* frame) { wasm_store_t *store = NULL; -own wasm_trap_t* early_exit(wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results) { +own wasm_trap_t* early_exit(const wasm_val_vec_t* args, wasm_val_vec_t* results) { own wasm_message_t trap_message; wasm_name_new_from_string_nt(&trap_message, "trapping from a host import"); own wasm_trap_t *trap = wasm_trap_new(store, &trap_message); @@ -42,8 +42,6 @@ int main(int argc, const char *argv[]) { printf("Initializing...\n"); wasm_engine_t *engine = wasm_engine_new(); store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/examples/exports-function.c b/lib/c-api/examples/exports-function.c index e7feaf4cd8f..8c644638870 100644 --- a/lib/c-api/examples/exports-function.c +++ b/lib/c-api/examples/exports-function.c @@ -20,8 +20,6 @@ int main(int argc, const char* argv[]) { printf("Creating the store...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); printf("Compiling module...\n"); wasm_module_t* module = wasm_module_new(store, &wasm_bytes); diff --git a/lib/c-api/examples/exports-global.c b/lib/c-api/examples/exports-global.c index dbbac9e81d6..ff20dfdeff4 100644 --- a/lib/c-api/examples/exports-global.c +++ b/lib/c-api/examples/exports-global.c @@ -19,8 +19,6 @@ int main(int argc, const char* argv[]) { printf("Creating the store...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); printf("Compiling module...\n"); wasm_module_t* module = wasm_module_new(store, &wasm_bytes); diff --git a/lib/c-api/examples/features.c b/lib/c-api/examples/features.c index 6f472617267..c42215d1eb1 100644 --- a/lib/c-api/examples/features.c +++ b/lib/c-api/examples/features.c @@ -26,8 +26,6 @@ int main(int argc, const char* argv[]) { printf("Creating the store...\n"); wasm_engine_t* engine = wasm_engine_new_with_config(config); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); printf("Compiling module...\n"); wasm_module_t* module = wasm_module_new(store, &wasm_bytes); diff --git a/lib/c-api/examples/imports-exports.c b/lib/c-api/examples/imports-exports.c index dca1efa57f8..e56a7232735 100644 --- a/lib/c-api/examples/imports-exports.c +++ b/lib/c-api/examples/imports-exports.c @@ -1,7 +1,7 @@ #include #include "wasmer.h" -wasm_trap_t* host_func_callback(wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results) { +wasm_trap_t* host_func_callback(const wasm_val_vec_t* args, wasm_val_vec_t* results) { printf("Calling back...\n> "); wasm_val_t val = WASM_I32_VAL(42); @@ -31,8 +31,6 @@ int main(int argc, const char* argv[]) { printf("Creating the store...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); printf("Compiling module...\n"); wasm_module_t* module = wasm_module_new(store, &wasm_bytes); diff --git a/lib/c-api/examples/instance.c b/lib/c-api/examples/instance.c index 2c50efee73e..6eb867d4ce0 100644 --- a/lib/c-api/examples/instance.c +++ b/lib/c-api/examples/instance.c @@ -20,8 +20,6 @@ int main(int argc, const char* argv[]) { printf("Creating the store...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); printf("Compiling module...\n"); wasm_module_t* module = wasm_module_new(store, &wasm_bytes); diff --git a/lib/c-api/examples/memory.c b/lib/c-api/examples/memory.c index cf6343ac6f5..d33295147b6 100644 --- a/lib/c-api/examples/memory.c +++ b/lib/c-api/examples/memory.c @@ -28,8 +28,6 @@ int main(int argc, const char* argv[]) { printf("Creating the store...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); printf("Compiling module...\n"); wasm_module_t* module = wasm_module_new(store, &wasm_bytes); diff --git a/lib/c-api/examples/memory2.c b/lib/c-api/examples/memory2.c index c9c0af980d7..8c009bd1f94 100644 --- a/lib/c-api/examples/memory2.c +++ b/lib/c-api/examples/memory2.c @@ -20,8 +20,6 @@ int main(int argc, const char *argv[]) { printf("Initializing...\n"); own wasm_engine_t* engine = wasm_engine_new(); own wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // ===================== wasm_limits_t limits1 = { diff --git a/lib/c-api/examples/wasi.c b/lib/c-api/examples/wasi.c index 932e605f888..529268e8591 100644 --- a/lib/c-api/examples/wasi.c +++ b/lib/c-api/examples/wasi.c @@ -36,16 +36,6 @@ int main(int argc, const char* argv[]) { wasi_config_arg(config, js_string); wasi_config_capture_stdout(config); - wasi_env_t* wasi_env = wasi_env_new(config); - if (!wasi_env) { - printf("> Error building WASI env!\n"); - print_wasmer_error(); - return 1; - } - - wasm_context_t* ctx = wasm_context_new(store, wasi_env); - wasm_store_context_set(store, ctx); - // Load binary. printf("Loading binary...\n"); FILE* file = fopen("assets/qjs.wasm", "r"); @@ -73,10 +63,27 @@ int main(int argc, const char* argv[]) { } wasm_byte_vec_delete(&binary); + + printf("Setting up WASI...\n"); + config = wasi_config_new("example_program"); + // TODO: error checking + js_string = "function greet(name) { return JSON.stringify('Hello, ' + name); }; print(greet('World'));"; + wasi_config_arg(config, "--eval"); + wasi_config_arg(config, js_string); + wasi_config_capture_stdout(config); + + wasi_env_t* wasi_env = wasi_env_new(store, config); + + if (!wasi_env) { + printf("> Error building WASI env!\n"); + print_wasmer_error(); + return 1; + } + // Instantiate. printf("Instantiating module...\n"); wasm_extern_vec_t imports; - bool get_imports_result = wasi_get_imports(store, module, &imports); + bool get_imports_result = wasi_get_imports(store, wasi_env,module,&imports); if (!get_imports_result) { printf("> Error getting WASI imports!\n"); @@ -93,6 +100,12 @@ int main(int argc, const char* argv[]) { return 1; } + if (!wasi_env_initialize_instance(wasi_env, store, instance)) { + printf("> Error initializing wasi env memory!\n"); + print_wasmer_error(); + return 1; + } + // Extract export. printf("Extracting export...\n"); @@ -111,9 +124,6 @@ int main(int argc, const char* argv[]) { return 1; } - wasm_module_delete(module); - wasm_instance_delete(instance); - // Call. printf("Calling export...\n"); printf("Evaluating \"%s\"\n", js_string); @@ -170,6 +180,8 @@ int main(int argc, const char* argv[]) { printf("Shutting down...\n"); wasm_func_delete(run_func); wasi_env_delete(wasi_env); + wasm_module_delete(module); + wasm_instance_delete(instance); wasm_store_delete(store); wasm_engine_delete(engine); diff --git a/lib/c-api/src/wasm_c_api/context.rs b/lib/c-api/src/wasm_c_api/context.rs deleted file mode 100644 index cefc75076de..00000000000 --- a/lib/c-api/src/wasm_c_api/context.rs +++ /dev/null @@ -1,73 +0,0 @@ -use crate::wasm_c_api::store::wasm_store_t; -use libc::c_void; -use wasmer_api::{Context, ContextMut}; - -/// Opaque type representing a WebAssembly context. -#[allow(non_camel_case_types)] -pub struct wasm_context_t { - pub(crate) inner: Context<*mut c_void>, -} - -impl core::fmt::Debug for wasm_context_t { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(fmt, "wasm_context_t") - } -} - -/// Creates a new WebAssembly Context given a specific [engine][super::engine]. -/// -/// # Example -/// -/// See the module's documentation. -#[no_mangle] -pub unsafe extern "C" fn wasm_context_new( - store: Option<&wasm_store_t>, - data: *mut c_void, -) -> Option> { - let store = store?; - - Some(Box::new(wasm_context_t { - inner: Context::new(&store.inner, data), - })) -} - -/// Deletes a WebAssembly context. -/// -/// # Example -/// -/// See the module's documentation. -#[no_mangle] -pub unsafe extern "C" fn wasm_context_delete(_context: Option>) {} - -/// Opaque type representing a mut ref of a WebAssembly context. -#[allow(non_camel_case_types)] -pub struct wasm_context_ref_mut_t<'a> { - pub(crate) inner: ContextMut<'a, *mut c_void>, -} - -/// Get the value of `wasm_context_ref_mut_t` data. -#[no_mangle] -pub unsafe extern "C" fn wasm_context_ref_mut_get(ctx: &wasm_context_ref_mut_t) -> *mut c_void { - *ctx.inner.data() -} - -/// Set the value of [`ContextMut`] data. -/// -#[no_mangle] -pub unsafe extern "C" fn wasm_context_ref_mut_set( - ctx: &mut wasm_context_ref_mut_t, - new_val: *mut c_void, -) { - *ctx.inner.data_mut() = new_val; -} - -/// Deletes a WebAssembly context. -/// -/// # Example -/// -/// See the module's documentation. -#[no_mangle] -pub unsafe extern "C" fn wasm_context_ref_mut_delete( - _context: Option<&mut wasm_context_ref_mut_t>, -) { -} diff --git a/lib/c-api/src/wasm_c_api/externals/function.rs b/lib/c-api/src/wasm_c_api/externals/function.rs index ca580bad17f..7ed8fa1df11 100644 --- a/lib/c-api/src/wasm_c_api/externals/function.rs +++ b/lib/c-api/src/wasm_c_api/externals/function.rs @@ -1,59 +1,61 @@ -use super::super::context::{wasm_context_ref_mut_t, wasm_context_t}; use super::super::store::wasm_store_t; use super::super::trap::wasm_trap_t; use super::super::types::{wasm_functype_t, wasm_valkind_enum}; use super::super::value::{wasm_val_inner, wasm_val_t, wasm_val_vec_t}; -use super::CApiExternTag; -use std::cell::RefCell; +use super::wasm_extern_t; +use crate::wasm_c_api::function_env::FunctionCEnv; +use libc::c_void; use std::convert::TryInto; -use std::ffi::c_void; use std::mem::MaybeUninit; -use std::rc::Rc; -use wasmer_api::{Function, RuntimeError, Value}; +use std::sync::{Arc, Mutex}; +use wasmer_api::{Extern, Function, FunctionEnv, FunctionEnvMut, RuntimeError, Value}; -#[derive(Debug, Clone)] +#[derive(Clone)] #[allow(non_camel_case_types)] #[repr(C)] pub struct wasm_func_t { - pub(crate) tag: CApiExternTag, - pub(crate) inner: Box, - pub(crate) context: Option>>, + pub(crate) extern_: wasm_extern_t, } impl wasm_func_t { - pub(crate) fn new(function: Function) -> Self { - Self { - tag: CApiExternTag::Function, - inner: Box::new(function), - context: None, + pub(crate) fn try_from(e: &wasm_extern_t) -> Option<&wasm_func_t> { + match &e.inner { + Extern::Function(_) => Some(unsafe { &*(e as *const _ as *const _) }), + _ => None, } } } #[allow(non_camel_case_types)] pub type wasm_func_callback_t = unsafe extern "C" fn( - context: &mut wasm_context_ref_mut_t, args: &wasm_val_vec_t, results: &mut wasm_val_vec_t, ) -> Option>; +#[allow(non_camel_case_types)] +pub type wasm_func_callback_with_env_t = unsafe extern "C" fn( + env: *mut c_void, + args: &wasm_val_vec_t, + results: &mut wasm_val_vec_t, +) -> Option>; + +#[allow(non_camel_case_types)] +pub type wasm_env_finalizer_t = unsafe extern "C" fn(*mut c_void); + #[no_mangle] pub unsafe extern "C" fn wasm_func_new( - store: Option<&wasm_store_t>, + store: Option<&mut wasm_store_t>, function_type: Option<&wasm_functype_t>, callback: Option, ) -> Option> { let function_type = function_type?; let callback = callback?; let store = store?; - if store.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let mut ctx = store.context.as_ref()?.borrow_mut(); + let mut store_mut = store.inner.store_mut(); let func_sig = &function_type.inner().function_type; let num_rets = func_sig.results().len(); - let inner_callback = move |ctx: wasmer_api::ContextMut<'_, *mut c_void>, + let inner_callback = move |mut _ctx: FunctionEnvMut<'_, FunctionCEnv>, args: &[Value]| -> Result, RuntimeError> { let processed_args: wasm_val_vec_t = args @@ -72,11 +74,7 @@ pub unsafe extern "C" fn wasm_func_new( ] .into(); - let trap = callback( - &mut wasm_context_ref_mut_t { inner: ctx }, - &processed_args, - &mut results, - ); + let trap = callback(&processed_args, &mut results); if let Some(trap) = trap { return Err(trap.inner); @@ -91,12 +89,100 @@ pub unsafe extern "C" fn wasm_func_new( Ok(processed_results) }; - let function = Function::new(&mut ctx.inner, func_sig, inner_callback); - drop(ctx); - let mut retval = Box::new(wasm_func_t::new(function)); - retval.context = store.context.clone(); + let env = FunctionEnv::new(&mut store_mut, FunctionCEnv::default()); + let function = Function::new(&mut store_mut, &env, func_sig, inner_callback); + Some(Box::new(wasm_func_t { + extern_: wasm_extern_t::new(store.inner.clone(), function.into()), + })) +} + +#[no_mangle] +pub unsafe extern "C" fn wasm_func_new_with_env( + store: Option<&mut wasm_store_t>, + function_type: Option<&wasm_functype_t>, + callback: Option, + env: *mut c_void, + env_finalizer: Option, +) -> Option> { + let function_type = function_type?; + let callback = callback?; + let store = store?; + let mut store_mut = store.inner.store_mut(); - Some(retval) + let func_sig = &function_type.inner().function_type; + let num_rets = func_sig.results().len(); + + #[derive(Clone)] + #[repr(C)] + struct WrapperEnv { + env: FunctionCEnv, + env_finalizer: Arc>>, + } + + // Only relevant when using multiple threads in the C API; + // Synchronization will be done via the C API / on the C side. + unsafe impl Send for WrapperEnv {} + unsafe impl Sync for WrapperEnv {} + + impl Drop for WrapperEnv { + fn drop(&mut self) { + if let Ok(mut guard) = self.env_finalizer.lock() { + if Arc::strong_count(&self.env_finalizer) == 1 { + if let Some(env_finalizer) = guard.take() { + unsafe { (env_finalizer)(self.env.as_ptr()) }; + } + } + } + } + } + let inner_callback = move |env: FunctionEnvMut<'_, WrapperEnv>, + args: &[Value]| + -> Result, RuntimeError> { + let processed_args: wasm_val_vec_t = args + .iter() + .map(TryInto::try_into) + .collect::, _>>() + .expect("Argument conversion failed") + .into(); + + let mut results: wasm_val_vec_t = vec![ + wasm_val_t { + kind: wasm_valkind_enum::WASM_I64 as _, + of: wasm_val_inner { int64_t: 0 }, + }; + num_rets + ] + .into(); + + let trap = callback(env.data().env.as_ptr(), &processed_args, &mut results); + + if let Some(trap) = trap { + return Err(trap.inner); + } + + let processed_results = results + .take() + .into_iter() + .map(TryInto::try_into) + .collect::, _>>() + .expect("Result conversion failed"); + + Ok(processed_results) + }; + let env = FunctionEnv::new( + &mut store_mut, + WrapperEnv { + env: FunctionCEnv::new(c_try!( + std::ptr::NonNull::new(env), + "Function environment cannot be a null pointer." + )), + env_finalizer: Arc::new(Mutex::new(env_finalizer)), + }, + ); + let function = Function::new(&mut store_mut, &env, func_sig, inner_callback); + Some(Box::new(wasm_func_t { + extern_: wasm_extern_t::new(store.inner.clone(), function.into()), + })) } #[no_mangle] @@ -109,17 +195,14 @@ pub unsafe extern "C" fn wasm_func_delete(_func: Option>) {} #[no_mangle] pub unsafe extern "C" fn wasm_func_call( - func: Option<&wasm_func_t>, + func: Option<&mut wasm_func_t>, args: Option<&wasm_val_vec_t>, results: &mut wasm_val_vec_t, ) -> Option> { let func = func?; let args = args?; - if func.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let mut ctx = func.context.as_ref()?.borrow_mut(); - + let mut store = func.extern_.store.clone(); + let mut store_mut = store.store_mut(); let params = args .as_slice() .iter() @@ -128,7 +211,7 @@ pub unsafe extern "C" fn wasm_func_call( .collect::, _>>() .expect("Arguments conversion failed"); - match func.inner.call(&mut ctx.inner, ¶ms) { + match func.extern_.function().call(&mut store_mut, ¶ms) { Ok(wasm_results) => { for (slot, val) in results .as_uninit_slice() @@ -146,31 +229,28 @@ pub unsafe extern "C" fn wasm_func_call( #[no_mangle] pub unsafe extern "C" fn wasm_func_param_arity(func: &wasm_func_t) -> usize { - let ctx = func - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - func.inner.ty(&ctx.inner).params().len() + func.extern_ + .function() + .ty(&func.extern_.store.store()) + .params() + .len() } #[no_mangle] pub unsafe extern "C" fn wasm_func_result_arity(func: &wasm_func_t) -> usize { - let ctx = func - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - func.inner.ty(&ctx.inner).results().len() + func.extern_ + .function() + .ty(&func.extern_.store.store()) + .results() + .len() } #[no_mangle] -pub extern "C" fn wasm_func_type(func: Option<&wasm_func_t>) -> Option> { +pub unsafe extern "C" fn wasm_func_type( + func: Option<&wasm_func_t>, +) -> Option> { let func = func?; - if func.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let ctx = func.context.as_ref()?.borrow(); - - Some(Box::new(wasm_functype_t::new(func.inner.ty(&ctx.inner)))) + Some(Box::new(wasm_functype_t::new( + func.extern_.function().ty(&func.extern_.store.store()), + ))) } diff --git a/lib/c-api/src/wasm_c_api/externals/global.rs b/lib/c-api/src/wasm_c_api/externals/global.rs index 3bd251b1430..b6f8a4f74f5 100644 --- a/lib/c-api/src/wasm_c_api/externals/global.rs +++ b/lib/c-api/src/wasm_c_api/externals/global.rs @@ -1,58 +1,47 @@ -use super::super::context::wasm_context_t; use super::super::store::wasm_store_t; use super::super::types::wasm_globaltype_t; use super::super::value::wasm_val_t; -use super::CApiExternTag; -use crate::error::update_last_error; -use std::cell::RefCell; +use super::wasm_extern_t; use std::convert::TryInto; -use std::rc::Rc; -use wasmer_api::{Global, Value}; +use wasmer_api::{Extern, Global, Value}; #[allow(non_camel_case_types)] #[repr(C)] -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct wasm_global_t { - pub(crate) tag: CApiExternTag, - pub(crate) inner: Box, - pub(crate) context: Option>>, + pub(crate) extern_: wasm_extern_t, } impl wasm_global_t { - pub(crate) fn new(global: Global) -> Self { - Self { - tag: CApiExternTag::Global, - inner: Box::new(global), - context: None, + pub(crate) fn try_from(e: &wasm_extern_t) -> Option<&wasm_global_t> { + match &e.inner { + Extern::Global(_) => Some(unsafe { &*(e as *const _ as *const _) }), + _ => None, } } } #[no_mangle] pub unsafe extern "C" fn wasm_global_new( - store: Option<&wasm_store_t>, + store: Option<&mut wasm_store_t>, global_type: Option<&wasm_globaltype_t>, val: Option<&wasm_val_t>, ) -> Option> { let global_type = global_type?; let store = store?; - if store.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let mut ctx = store.context.as_ref()?.borrow_mut(); + let mut store_mut = store.inner.store_mut(); let val = val?; let global_type = &global_type.inner().global_type; let wasm_val = val.try_into().ok()?; let global = if global_type.mutability.is_mutable() { - Global::new_mut(&mut ctx.inner, wasm_val) + Global::new_mut(&mut store_mut, wasm_val) } else { - Global::new(&mut ctx.inner, wasm_val) + Global::new(&mut store_mut, wasm_val) }; - let mut retval = Box::new(wasm_global_t::new(global)); - retval.context = store.context.clone(); - - Some(retval) + Some(Box::new(wasm_global_t { + extern_: wasm_extern_t::new(store.inner.clone(), global.into()), + })) } #[no_mangle] @@ -61,42 +50,31 @@ pub unsafe extern "C" fn wasm_global_delete(_global: Option>) #[no_mangle] pub unsafe extern "C" fn wasm_global_copy(global: &wasm_global_t) -> Box { // do shallow copy - Box::new(wasm_global_t::new((&*global.inner).clone())) + Box::new(global.clone()) } #[no_mangle] pub unsafe extern "C" fn wasm_global_get( - global: &wasm_global_t, + global: &mut wasm_global_t, // own out: &mut wasm_val_t, ) { - match global.context.as_ref() { - Some(ctx) => { - let value = global.inner.get(&mut ctx.borrow_mut().inner); - *out = value.try_into().unwrap(); - } - None => { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - } + let value = global + .extern_ + .global() + .get(&mut global.extern_.store.store_mut()); + *out = value.try_into().unwrap(); } /// Note: This function returns nothing by design but it can raise an /// error if setting a new value fails. #[no_mangle] pub unsafe extern "C" fn wasm_global_set(global: &mut wasm_global_t, val: &wasm_val_t) { - match global.context.as_ref() { - Some(ctx) => { - let value: Value = val.try_into().unwrap(); - - if let Err(e) = global.inner.set(&mut ctx.borrow_mut().inner, value) { - update_last_error(e); - } - } - None => { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - } + let value: Value = val.try_into().unwrap(); + c_try!(global + .extern_ + .global() + .set(&mut global.extern_.store.store_mut(), value); otherwise ()); } #[no_mangle] @@ -104,20 +82,16 @@ pub unsafe extern "C" fn wasm_global_same( wasm_global1: &wasm_global_t, wasm_global2: &wasm_global_t, ) -> bool { - wasm_global1.inner == wasm_global2.inner + wasm_global1.extern_.global() == wasm_global2.extern_.global() } #[no_mangle] -pub extern "C" fn wasm_global_type( +pub unsafe extern "C" fn wasm_global_type( global: Option<&wasm_global_t>, ) -> Option> { let global = global?; - if global.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let ctx = global.context.as_ref()?.borrow(); Some(Box::new(wasm_globaltype_t::new( - global.inner.ty(&ctx.inner), + global.extern_.global().ty(&global.extern_.store.store()), ))) } @@ -133,8 +107,6 @@ mod tests { int main() { wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); wasm_val_t forty_two = WASM_F32_VAL(42); wasm_val_t forty_three = WASM_F32_VAL(43); @@ -167,8 +139,6 @@ mod tests { int main() { wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); wasm_byte_vec_t wat; wasmer_byte_vec_new_from_string(&wat, "(module (global $global (export \"global\") f32 (f32.const 1)))"); diff --git a/lib/c-api/src/wasm_c_api/externals/memory.rs b/lib/c-api/src/wasm_c_api/externals/memory.rs index 6252b438751..1b1bee25529 100644 --- a/lib/c-api/src/wasm_c_api/externals/memory.rs +++ b/lib/c-api/src/wasm_c_api/externals/memory.rs @@ -1,47 +1,36 @@ -use super::super::context::wasm_context_t; -use super::super::store::wasm_store_t; use super::super::types::wasm_memorytype_t; -use super::CApiExternTag; -use std::cell::RefCell; -use std::rc::Rc; -use wasmer_api::{Memory, Pages}; +use super::{super::store::wasm_store_t, wasm_extern_t}; +use wasmer_api::{Extern, Memory, Pages}; #[allow(non_camel_case_types)] #[repr(C)] -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct wasm_memory_t { - pub(crate) tag: CApiExternTag, - pub(crate) inner: Box, - pub(crate) context: Option>>, + pub(crate) extern_: wasm_extern_t, } impl wasm_memory_t { - pub(crate) fn new(memory: Memory) -> Self { - Self { - tag: CApiExternTag::Memory, - inner: Box::new(memory), - context: None, + pub(crate) fn try_from(e: &wasm_extern_t) -> Option<&wasm_memory_t> { + match &e.inner { + Extern::Memory(_) => Some(unsafe { &*(e as *const _ as *const _) }), + _ => None, } } } #[no_mangle] pub unsafe extern "C" fn wasm_memory_new( - store: Option<&wasm_store_t>, + store: Option<&mut wasm_store_t>, memory_type: Option<&wasm_memorytype_t>, ) -> Option> { let memory_type = memory_type?; let store = store?; - if store.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let mut ctx = store.context.as_ref()?.borrow_mut(); - + let mut store_mut = store.inner.store_mut(); let memory_type = memory_type.inner().memory_type; - let memory = c_try!(Memory::new(&mut ctx.inner, memory_type)); - let mut retval = Box::new(wasm_memory_t::new(memory)); - retval.context = store.context.clone(); - Some(retval) + let memory = c_try!(Memory::new(&mut store_mut, memory_type)); + Some(Box::new(wasm_memory_t { + extern_: wasm_extern_t::new(store.inner.clone(), memory.into()), + })) } #[no_mangle] @@ -50,7 +39,7 @@ pub unsafe extern "C" fn wasm_memory_delete(_memory: Option>) #[no_mangle] pub unsafe extern "C" fn wasm_memory_copy(memory: &wasm_memory_t) -> Box { // do shallow copy - Box::new(wasm_memory_t::new((&*memory.inner).clone())) + Box::new(memory.clone()) } #[no_mangle] @@ -58,7 +47,7 @@ pub unsafe extern "C" fn wasm_memory_same( wasm_memory1: &wasm_memory_t, wasm_memory2: &wasm_memory_t, ) -> bool { - wasm_memory1.inner == wasm_memory2.inner + wasm_memory1.extern_.memory() == wasm_memory2.extern_.memory() } #[no_mangle] @@ -66,56 +55,47 @@ pub unsafe extern "C" fn wasm_memory_type( memory: Option<&wasm_memory_t>, ) -> Option> { let memory = memory?; - if memory.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let ctx = memory.context.as_ref()?.borrow(); - Some(Box::new(wasm_memorytype_t::new( - memory.inner.ty(&ctx.inner), + memory.extern_.memory().ty(&memory.extern_.store.store()), ))) } // get a raw pointer into bytes #[no_mangle] pub unsafe extern "C" fn wasm_memory_data(memory: &mut wasm_memory_t) -> *mut u8 { - let ctx = memory - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - memory.inner.data_ptr(&ctx.inner) + memory + .extern_ + .memory() + .data_ptr(&memory.extern_.store.store()) } // size in bytes #[no_mangle] pub unsafe extern "C" fn wasm_memory_data_size(memory: &wasm_memory_t) -> usize { - let ctx = memory - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - memory.inner.size(&ctx.inner).bytes().0 + memory + .extern_ + .memory() + .size(&memory.extern_.store.store()) + .bytes() + .0 } // size in pages #[no_mangle] pub unsafe extern "C" fn wasm_memory_size(memory: &wasm_memory_t) -> u32 { - let ctx = memory - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - memory.inner.size(&ctx.inner).0 as _ + memory + .extern_ + .memory() + .size(&memory.extern_.store.store()) + .0 as _ } // delta is in pages #[no_mangle] pub unsafe extern "C" fn wasm_memory_grow(memory: &mut wasm_memory_t, delta: u32) -> bool { - let mut ctx = memory - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow_mut(); - memory.inner.grow(&mut ctx.inner, Pages(delta)).is_ok() + memory + .extern_ + .memory() + .grow(&mut memory.extern_.store.store_mut(), Pages(delta)) + .is_ok() } diff --git a/lib/c-api/src/wasm_c_api/externals/mod.rs b/lib/c-api/src/wasm_c_api/externals/mod.rs index 09d190c997f..9fe5eca1d4a 100644 --- a/lib/c-api/src/wasm_c_api/externals/mod.rs +++ b/lib/c-api/src/wasm_c_api/externals/mod.rs @@ -3,231 +3,77 @@ mod global; mod memory; mod table; -use super::context::wasm_context_t; -use super::store::wasm_store_t; +use super::store::StoreRef; +// use super::types::{wasm_externkind_enum, wasm_externkind_t}; pub use function::*; pub use global::*; pub use memory::*; -use std::cell::RefCell; -use std::mem::{self, ManuallyDrop}; -use std::rc::Rc; pub use table::*; -use wasmer_api::{Extern, ExternType}; +use wasmer_api::{Extern, ExternType, Function, Global, Memory, Table}; #[allow(non_camel_case_types)] -#[repr(transparent)] +#[derive(Clone)] pub struct wasm_extern_t { - pub(crate) inner: wasm_extern_inner, + pub(crate) inner: Extern, + pub(crate) store: StoreRef, } -/// All elements in this union must be `repr(C)` and have a -/// `CApiExternTag` as their first element. -#[allow(non_camel_case_types)] -pub(crate) union wasm_extern_inner { - function: mem::ManuallyDrop, - memory: mem::ManuallyDrop, - global: mem::ManuallyDrop, - table: mem::ManuallyDrop, -} - -#[cfg(test)] -mod extern_tests { - use super::*; - - #[test] - fn externs_are_the_same_size() { - use std::mem::{align_of, size_of}; - assert_eq!(size_of::(), size_of::()); - assert_eq!(size_of::(), size_of::()); - assert_eq!(size_of::(), size_of::()); - assert_eq!(size_of::(), size_of::()); - - assert_eq!(align_of::(), align_of::()); - assert_eq!(align_of::(), align_of::()); - assert_eq!(align_of::(), align_of::()); - assert_eq!(align_of::(), align_of::()); - } - - #[test] - fn tags_are_the_same_offset_away() { - use field_offset::offset_of; - - let func_tag_offset = offset_of!(wasm_func_t => tag).get_byte_offset(); - let memory_tag_offset = offset_of!(wasm_memory_t => tag).get_byte_offset(); - let global_tag_offset = offset_of!(wasm_global_t => tag).get_byte_offset(); - let table_tag_offset = offset_of!(wasm_table_t => tag).get_byte_offset(); - - assert_eq!(func_tag_offset, memory_tag_offset); - assert_eq!(global_tag_offset, table_tag_offset); - assert_eq!(func_tag_offset, global_tag_offset); +impl wasm_extern_t { + pub(crate) fn new(store: StoreRef, inner: Extern) -> Self { + Self { inner, store } } -} -impl Drop for wasm_extern_inner { - fn drop(&mut self) { - unsafe { - match self.function.tag { - CApiExternTag::Function => mem::ManuallyDrop::drop(&mut self.function), - CApiExternTag::Global => mem::ManuallyDrop::drop(&mut self.global), - CApiExternTag::Table => mem::ManuallyDrop::drop(&mut self.table), - CApiExternTag::Memory => mem::ManuallyDrop::drop(&mut self.memory), - } + pub(crate) fn global(&self) -> Global { + match &self.inner { + Extern::Global(g) => g.clone(), + _ => unsafe { std::hint::unreachable_unchecked() }, } } -} - -impl wasm_extern_t { - pub(crate) fn get_tag(&self) -> CApiExternTag { - unsafe { self.inner.function.tag } - } - pub(crate) fn ty(&self) -> ExternType { - match self.get_tag() { - CApiExternTag::Function => unsafe { - let ctx = self - .inner - .function - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - ExternType::Function(self.inner.function.inner.ty(&ctx.inner)) - }, - CApiExternTag::Memory => unsafe { - let ctx = self - .inner - .memory - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - ExternType::Memory(self.inner.memory.inner.ty(&ctx.inner)) - }, - CApiExternTag::Global => unsafe { - let ctx = self - .inner - .global - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - ExternType::Global(self.inner.global.inner.ty(&ctx.inner)) - }, - CApiExternTag::Table => unsafe { - let ctx = self - .inner - .table - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - ExternType::Table(self.inner.table.inner.ty(&ctx.inner)) - }, + pub(crate) fn function(&self) -> Function { + match &self.inner { + Extern::Function(f) => f.clone(), + _ => unsafe { std::hint::unreachable_unchecked() }, } } - pub(crate) fn set_context(&mut self, new_val: Option>>) { - match self.get_tag() { - CApiExternTag::Function => unsafe { - (*self.inner.function).context = new_val; - }, - CApiExternTag::Memory => unsafe { - (*self.inner.memory).context = new_val; - }, - CApiExternTag::Global => unsafe { - (*self.inner.global).context = new_val; - }, - CApiExternTag::Table => unsafe { - (*self.inner.table).context = new_val; - }, + pub(crate) fn table(&self) -> Table { + match &self.inner { + Extern::Table(t) => t.clone(), + _ => unsafe { std::hint::unreachable_unchecked() }, } } -} -impl Clone for wasm_extern_t { - fn clone(&self) -> Self { - match self.get_tag() { - CApiExternTag::Function => Self { - inner: wasm_extern_inner { - function: unsafe { self.inner.function.clone() }, - }, - }, - CApiExternTag::Memory => Self { - inner: wasm_extern_inner { - memory: unsafe { self.inner.memory.clone() }, - }, - }, - CApiExternTag::Global => Self { - inner: wasm_extern_inner { - global: unsafe { self.inner.global.clone() }, - }, - }, - CApiExternTag::Table => Self { - inner: wasm_extern_inner { - table: unsafe { self.inner.table.clone() }, - }, - }, + pub(crate) fn memory(&self) -> Memory { + match &self.inner { + Extern::Memory(m) => m.clone(), + _ => unsafe { std::hint::unreachable_unchecked() }, } } } -impl From for wasm_extern_t { - fn from(other: Extern) -> Self { - match other { - Extern::Function(function) => Self { - inner: wasm_extern_inner { - function: mem::ManuallyDrop::new(wasm_func_t::new(function)), - }, - }, - Extern::Memory(memory) => Self { - inner: wasm_extern_inner { - memory: mem::ManuallyDrop::new(wasm_memory_t::new(memory)), - }, - }, - Extern::Table(table) => Self { - inner: wasm_extern_inner { - table: mem::ManuallyDrop::new(wasm_table_t::new(table)), - }, - }, - Extern::Global(global) => Self { - inner: wasm_extern_inner { - global: mem::ManuallyDrop::new(wasm_global_t::new(global)), - }, - }, - } +// #[no_mangle] +// pub extern "C" fn wasm_extern_kind(e: &wasm_extern_t) -> wasm_externkind_t { +// (match e.inner { +// Extern::Function(_) => wasm_externkind_enum::WASM_EXTERN_FUNC, +// Extern::Table(_) => wasm_externkind_enum::WASM_EXTERN_TABLE, +// Extern::Global(_) => wasm_externkind_enum::WASM_EXTERN_GLOBAL, +// Extern::Memory(_) => wasm_externkind_enum::WASM_EXTERN_MEMORY, +// }) as wasm_externkind_t +// } + +impl wasm_extern_t { + pub(crate) unsafe fn ty(&self) -> ExternType { + self.inner.ty(&self.store.store()) } } impl From for Extern { - fn from(mut other: wasm_extern_t) -> Self { - let out = match other.get_tag() { - CApiExternTag::Function => unsafe { - (*ManuallyDrop::take(&mut other.inner.function).inner).into() - }, - CApiExternTag::Memory => unsafe { - (*ManuallyDrop::take(&mut other.inner.memory).inner).into() - }, - CApiExternTag::Table => unsafe { - (*ManuallyDrop::take(&mut other.inner.table).inner).into() - }, - CApiExternTag::Global => unsafe { - (*ManuallyDrop::take(&mut other.inner.global).inner).into() - }, - }; - mem::forget(other); - out + fn from(other: wasm_extern_t) -> Self { + other.inner } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[repr(C)] -pub(crate) enum CApiExternTag { - Function, - Global, - Table, - Memory, -} - wasm_declare_boxed_vec!(extern); /// Copy a `wasm_extern_t`. @@ -242,70 +88,46 @@ pub unsafe extern "C" fn wasm_extern_delete(_extern: Option>) #[no_mangle] pub extern "C" fn wasm_func_as_extern(func: Option<&wasm_func_t>) -> Option<&wasm_extern_t> { - unsafe { mem::transmute::, Option<&wasm_extern_t>>(func) } + Some(&func?.extern_) } #[no_mangle] pub extern "C" fn wasm_global_as_extern(global: Option<&wasm_global_t>) -> Option<&wasm_extern_t> { - unsafe { mem::transmute::, Option<&wasm_extern_t>>(global) } + Some(&global?.extern_) } #[no_mangle] pub extern "C" fn wasm_memory_as_extern(memory: Option<&wasm_memory_t>) -> Option<&wasm_extern_t> { - unsafe { mem::transmute::, Option<&wasm_extern_t>>(memory) } + Some(&memory?.extern_) } #[no_mangle] pub extern "C" fn wasm_table_as_extern(table: Option<&wasm_table_t>) -> Option<&wasm_extern_t> { - unsafe { mem::transmute::, Option<&wasm_extern_t>>(table) } + Some(&table?.extern_) } #[no_mangle] pub extern "C" fn wasm_extern_as_func(r#extern: Option<&wasm_extern_t>) -> Option<&wasm_func_t> { - let r#extern = r#extern?; - - if r#extern.get_tag() == CApiExternTag::Function { - Some(unsafe { mem::transmute::<&wasm_extern_t, &wasm_func_t>(r#extern) }) - } else { - None - } + wasm_func_t::try_from(r#extern?) } #[no_mangle] pub extern "C" fn wasm_extern_as_global( r#extern: Option<&wasm_extern_t>, ) -> Option<&wasm_global_t> { - let r#extern = r#extern?; - - if r#extern.get_tag() == CApiExternTag::Global { - Some(unsafe { mem::transmute::<&wasm_extern_t, &wasm_global_t>(r#extern) }) - } else { - None - } + wasm_global_t::try_from(r#extern?) } #[no_mangle] pub extern "C" fn wasm_extern_as_memory( r#extern: Option<&wasm_extern_t>, ) -> Option<&wasm_memory_t> { - let r#extern = r#extern?; - - if r#extern.get_tag() == CApiExternTag::Memory { - Some(unsafe { mem::transmute::<&wasm_extern_t, &wasm_memory_t>(r#extern) }) - } else { - None - } + wasm_memory_t::try_from(r#extern?) } #[no_mangle] pub extern "C" fn wasm_extern_as_table(r#extern: Option<&wasm_extern_t>) -> Option<&wasm_table_t> { - let r#extern = r#extern?; - - if r#extern.get_tag() == CApiExternTag::Table { - Some(unsafe { mem::transmute::<&wasm_extern_t, &wasm_table_t>(r#extern) }) - } else { - None - } + wasm_table_t::try_from(r#extern?) } #[cfg(test)] @@ -320,8 +142,6 @@ mod tests { int main() { wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); wasm_byte_vec_t wat; wasmer_byte_vec_new_from_string( diff --git a/lib/c-api/src/wasm_c_api/externals/table.rs b/lib/c-api/src/wasm_c_api/externals/table.rs index 300b91ee1c4..839cb447f14 100644 --- a/lib/c-api/src/wasm_c_api/externals/table.rs +++ b/lib/c-api/src/wasm_c_api/externals/table.rs @@ -1,26 +1,20 @@ -use super::super::context::wasm_context_t; use super::super::store::wasm_store_t; use super::super::types::{wasm_ref_t, wasm_table_size_t, wasm_tabletype_t}; -use super::CApiExternTag; -use std::cell::RefCell; -use std::rc::Rc; -use wasmer_api::Table; +use super::wasm_extern_t; +use wasmer_api::Extern; #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone)] pub struct wasm_table_t { - pub(crate) tag: CApiExternTag, - pub(crate) inner: Box
, - pub(crate) context: Option>>, + pub(crate) extern_: wasm_extern_t, } impl wasm_table_t { - pub(crate) fn new(table: Table) -> Self { - Self { - tag: CApiExternTag::Table, - inner: Box::new(table), - context: None, + pub(crate) fn try_from(e: &wasm_extern_t) -> Option<&wasm_table_t> { + match &e.inner { + Extern::Table(_) => Some(unsafe { &*(e as *const _ as *const _) }), + _ => None, } } } @@ -40,17 +34,12 @@ pub unsafe extern "C" fn wasm_table_delete(_table: Option>) {} #[no_mangle] pub unsafe extern "C" fn wasm_table_copy(table: &wasm_table_t) -> Box { // do shallow copy - Box::new(wasm_table_t::new((&*table.inner).clone())) + Box::new(table.clone()) } #[no_mangle] pub unsafe extern "C" fn wasm_table_size(table: &wasm_table_t) -> usize { - let ctx = table - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow(); - table.inner.size(&ctx.inner) as _ + table.extern_.table().size(&table.extern_.store.store()) as _ } #[no_mangle] @@ -58,7 +47,7 @@ pub unsafe extern "C" fn wasm_table_same( wasm_table1: &wasm_table_t, wasm_table2: &wasm_table_t, ) -> bool { - wasm_table1.inner == wasm_table2.inner + wasm_table1.extern_.table() == wasm_table2.extern_.table() } #[no_mangle] diff --git a/lib/c-api/src/wasm_c_api/function_env.rs b/lib/c-api/src/wasm_c_api/function_env.rs new file mode 100644 index 00000000000..a9e3910ab07 --- /dev/null +++ b/lib/c-api/src/wasm_c_api/function_env.rs @@ -0,0 +1,63 @@ +use crate::wasm_c_api::store::wasm_store_t; +use std::ffi::c_void; +use wasmer_api::FunctionEnv; + +#[derive(Clone, Copy)] +#[repr(C)] +pub struct FunctionCEnv { + #[allow(dead_code)] + inner: std::ptr::NonNull, +} + +impl FunctionCEnv { + #[allow(dead_code)] + pub(crate) fn as_ptr(&self) -> *mut c_void { + self.inner.as_ptr() + } +} + +static NULL_ENV_PLACEHOLDER: u32 = 42; + +impl FunctionCEnv { + pub(crate) fn new(inner: std::ptr::NonNull) -> Self { + Self { inner } + } +} + +impl Default for FunctionCEnv { + fn default() -> Self { + Self { + inner: unsafe { + std::ptr::NonNull::new_unchecked( + &NULL_ENV_PLACEHOLDER as *const u32 as *mut u32 as *mut c_void, + ) + }, + } + } +} + +unsafe impl Send for FunctionCEnv {} + +#[derive(Clone)] +#[allow(non_camel_case_types)] +#[repr(C)] +pub struct wasmer_funcenv_t { + inner: FunctionCEnv, +} + +#[no_mangle] +pub unsafe extern "C" fn wasmer_funcenv_new( + store: Option<&mut wasm_store_t>, + mut data: *mut c_void, +) -> Option> { + let store = store?; + if data.is_null() { + data = &NULL_ENV_PLACEHOLDER as *const u32 as *mut u32 as *mut c_void; + } + let inner = FunctionCEnv::new(std::ptr::NonNull::new_unchecked(data)); + let _ = FunctionEnv::new(&mut store.inner.store_mut(), inner); + Some(Box::new(wasmer_funcenv_t { inner })) +} + +#[no_mangle] +pub unsafe extern "C" fn wasmer_funcenv_delete(_funcenv: Option>) {} diff --git a/lib/c-api/src/wasm_c_api/instance.rs b/lib/c-api/src/wasm_c_api/instance.rs index 9d363815b4d..c32b44fbe93 100644 --- a/lib/c-api/src/wasm_c_api/instance.rs +++ b/lib/c-api/src/wasm_c_api/instance.rs @@ -1,18 +1,14 @@ -use super::context::wasm_context_t; use super::externals::{wasm_extern_t, wasm_extern_vec_t}; use super::module::wasm_module_t; -use super::store::wasm_store_t; +use super::store::{wasm_store_t, StoreRef}; use super::trap::wasm_trap_t; -use std::cell::RefCell; -use std::rc::Rc; -use std::sync::Arc; use wasmer_api::{Extern, Instance, InstantiationError}; /// Opaque type representing a WebAssembly instance. #[allow(non_camel_case_types)] pub struct wasm_instance_t { - pub(crate) inner: Arc, - pub(crate) context: Option>>, + pub(crate) store: StoreRef, + pub(crate) inner: Instance, } /// Creates a new instance from a WebAssembly module and a @@ -40,16 +36,13 @@ pub struct wasm_instance_t { /// See the module's documentation. #[no_mangle] pub unsafe extern "C" fn wasm_instance_new( - store: Option<&wasm_store_t>, + store: Option<&mut wasm_store_t>, module: Option<&wasm_module_t>, imports: Option<&wasm_extern_vec_t>, trap: Option<&mut *mut wasm_trap_t>, ) -> Option> { let store = store?; - if store.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let mut ctx = store.context.as_ref()?.borrow_mut(); + let mut store_mut = store.inner.store_mut(); let module = module?; let imports = imports?; @@ -63,8 +56,8 @@ pub unsafe extern "C" fn wasm_instance_new( .take(module_import_count) .collect::>(); - let instance = match Instance::new_by_index(&mut ctx.inner, wasm_module, &externs) { - Ok(instance) => Arc::new(instance), + let instance = match Instance::new_by_index(&mut store_mut, wasm_module, &externs) { + Ok(instance) => instance, Err(InstantiationError::Link(link_error)) => { crate::error::update_last_error(link_error); @@ -87,7 +80,7 @@ pub unsafe extern "C" fn wasm_instance_new( return None; } - Err(e @ InstantiationError::BadContext) => { + Err(e @ InstantiationError::DifferentStores) => { crate::error::update_last_error(e); return None; @@ -95,8 +88,8 @@ pub unsafe extern "C" fn wasm_instance_new( }; Some(Box::new(wasm_instance_t { + store: store.inner.clone(), inner: instance, - context: store.context.clone(), })) } @@ -122,8 +115,6 @@ pub unsafe extern "C" fn wasm_instance_delete(_instance: Option>> = instance + let extern_vec: Vec>> = instance .exports .iter() - .map(|(_name, r#extern)| Some(Box::new(r#extern.clone().into()))) + .map(|(_name, r#extern)| { + Some(Box::new(wasm_extern_t::new( + original_instance.store.clone(), + r#extern.clone(), + ))) + }) .collect(); - for ex in extern_vec.iter_mut().flatten() { - ex.set_context(original_instance.context.clone()); - } - out.set_buffer(extern_vec); } @@ -224,11 +216,9 @@ mod tests { // The `sum` host function implementation. wasm_trap_t* sum_callback( - wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* arguments, wasm_val_vec_t* results ) { - (void) ctx_mut; wasm_val_t sum = { .kind = WASM_I32, .of = { arguments->data[0].of.i32 + arguments->data[1].of.i32 }, @@ -242,8 +232,6 @@ mod tests { // Create the engine and the store. wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Create a WebAssembly module from a WAT definition. wasm_byte_vec_t wat; diff --git a/lib/c-api/src/wasm_c_api/macros.rs b/lib/c-api/src/wasm_c_api/macros.rs index 04aa90f3d60..c74187ddfda 100644 --- a/lib/c-api/src/wasm_c_api/macros.rs +++ b/lib/c-api/src/wasm_c_api/macros.rs @@ -297,6 +297,16 @@ macro_rules! wasm_impl_copy_delete { } macro_rules! c_try { + ($expr:expr; otherwise ()) => {{ + let res: Result<_, _> = $expr; + match res { + Ok(val) => val, + Err(err) => { + crate::error::update_last_error(err); + return; + } + } + }}; ($expr:expr; otherwise $return:expr) => {{ let res: Result<_, _> = $expr; match res { diff --git a/lib/c-api/src/wasm_c_api/mod.rs b/lib/c-api/src/wasm_c_api/mod.rs index 26fbd5f991b..5ec333e320a 100644 --- a/lib/c-api/src/wasm_c_api/mod.rs +++ b/lib/c-api/src/wasm_c_api/mod.rs @@ -22,7 +22,7 @@ //! discovery of this API. /// `Context`. -mod context; +mod function_env; /// Private Rust macros. #[macro_use] @@ -92,8 +92,6 @@ pub mod externals; /// // Create the engine and the store. /// wasm_engine_t* engine = wasm_engine_new(); /// wasm_store_t* store = wasm_store_new(engine); -/// wasm_context_t* ctx = wasm_context_new(store, 0); -/// wasm_store_context_set(store, ctx); /// /// // Create a WebAssembly module from a WAT definition. /// wasm_byte_vec_t wat; diff --git a/lib/c-api/src/wasm_c_api/module.rs b/lib/c-api/src/wasm_c_api/module.rs index 5eb0a716da0..26cbfd3fcb5 100644 --- a/lib/c-api/src/wasm_c_api/module.rs +++ b/lib/c-api/src/wasm_c_api/module.rs @@ -1,14 +1,13 @@ use super::store::wasm_store_t; use super::types::{wasm_byte_vec_t, wasm_exporttype_vec_t, wasm_importtype_vec_t}; -use crate::error::update_last_error; use std::ptr::NonNull; -use std::sync::Arc; use wasmer_api::Module; /// Opaque type representing a WebAssembly module. +#[derive(Clone)] #[allow(non_camel_case_types)] pub struct wasm_module_t { - pub(crate) inner: Arc, + pub(crate) inner: Module, } /// A WebAssembly module contains stateless WebAssembly code that has @@ -27,17 +26,15 @@ pub struct wasm_module_t { /// See the module's documentation. #[no_mangle] pub unsafe extern "C" fn wasm_module_new( - store: Option<&wasm_store_t>, + store: Option<&mut wasm_store_t>, bytes: Option<&wasm_byte_vec_t>, ) -> Option> { - let store = store?; + let store = store?.inner.store_mut(); let bytes = bytes?; - let module = c_try!(Module::from_binary(&store.inner, bytes.as_slice())); + let module = c_try!(Module::from_binary(&store, bytes.as_slice())); - Some(Box::new(wasm_module_t { - inner: Arc::new(module), - })) + Some(Box::new(wasm_module_t { inner: module })) } /// Deletes a WebAssembly module. @@ -91,11 +88,11 @@ pub unsafe extern "C" fn wasm_module_delete(_module: Option>) /// ``` #[no_mangle] pub unsafe extern "C" fn wasm_module_validate( - store: Option<&wasm_store_t>, + store: Option<&mut wasm_store_t>, bytes: Option<&wasm_byte_vec_t>, ) -> bool { let store = match store { - Some(store) => store, + Some(store) => store.inner.store_mut(), None => return false, }; let bytes = match bytes { @@ -103,13 +100,9 @@ pub unsafe extern "C" fn wasm_module_validate( None => return false, }; - if let Err(error) = Module::validate(&store.inner, bytes.as_slice()) { - update_last_error(error); - - false - } else { - true - } + Module::validate(&store, bytes.as_slice()) + .map(|_| true) + .unwrap_or(false) } /// Returns an array of the exported types in the module. @@ -465,12 +458,10 @@ pub unsafe extern "C" fn wasm_module_deserialize( ) -> Option> { let bytes = bytes?; - let module = c_try!(Module::deserialize(&store.inner, bytes.as_slice())); + let module = c_try!(Module::deserialize(&store.inner.store(), bytes.as_slice())); Some(NonNull::new_unchecked(Box::into_raw(Box::new( - wasm_module_t { - inner: Arc::new(module), - }, + wasm_module_t { inner: module }, )))) } @@ -483,13 +474,7 @@ pub unsafe extern "C" fn wasm_module_deserialize( /// See [`wasm_module_deserialize`]. #[no_mangle] pub unsafe extern "C" fn wasm_module_serialize(module: &wasm_module_t, out: &mut wasm_byte_vec_t) { - let byte_vec = match module.inner.serialize() { - Ok(byte_vec) => byte_vec, - Err(err) => { - crate::error::update_last_error(err); - return; - } - }; + let byte_vec = c_try!(module.inner.serialize(); otherwise ()); out.set_buffer(byte_vec); } diff --git a/lib/c-api/src/wasm_c_api/store.rs b/lib/c-api/src/wasm_c_api/store.rs index fe5eb89de21..d6bd5415ef5 100644 --- a/lib/c-api/src/wasm_c_api/store.rs +++ b/lib/c-api/src/wasm_c_api/store.rs @@ -1,20 +1,27 @@ -use super::context::wasm_context_t; use super::engine::wasm_engine_t; -use libc::c_void; -use std::cell::RefCell; -use std::rc::Rc; -use wasmer_api::Store; +use std::cell::UnsafeCell; +use std::sync::Arc; +use wasmer_api::{AsStoreMut, AsStoreRef, Store, StoreMut, StoreRef as BaseStoreRef}; + +#[derive(Clone)] +pub struct StoreRef { + inner: Arc>, +} + +impl StoreRef { + pub unsafe fn store(&self) -> BaseStoreRef<'_> { + (*self.inner.get()).as_store_ref() + } + + pub unsafe fn store_mut(&mut self) -> StoreMut<'_> { + (*self.inner.get()).as_store_mut() + } +} /// Opaque type representing a WebAssembly store. #[allow(non_camel_case_types)] pub struct wasm_store_t { - pub(crate) inner: Store, - pub(crate) context: Option>>, -} - -impl wasm_store_t { - pub(crate) const CTX_ERR_STR: &'static str = - "store used without a Context set; use wasm_store_context_set() after initializing your store."; + pub(crate) inner: StoreRef, } /// Creates a new WebAssembly store given a specific [engine][super::engine]. @@ -30,63 +37,12 @@ pub unsafe extern "C" fn wasm_store_new( let store = Store::new_with_engine(&*engine.inner); Some(Box::new(wasm_store_t { - inner: store, - context: None, + inner: StoreRef { + inner: Arc::new(UnsafeCell::new(store)), + }, })) } -/// Sets the context for this WebAssembly store. -/// -/// # Example -/// -/// See the module's documentation. -#[no_mangle] -pub unsafe extern "C" fn wasm_store_context_set( - store: Option<&mut wasm_store_t>, - context: Option>, -) { - let _result = (move |store: Option<&mut wasm_store_t>, - context: Option>| - -> Option<()> { - let mut store = store?; - let context = context?; - store.context = Some(Rc::new(RefCell::new(*context))); - Some(()) - })(store, context); -} - -/// Get the value of Context data. -/// -/// # Example -/// -/// See the module's documentation. -#[no_mangle] -pub unsafe extern "C" fn wasm_store_data_get(store: &wasm_store_t) -> *mut c_void { - *store - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow() - .inner - .data() -} - -/// Set the value of Context data. -/// -/// # Example -/// -/// See the module's documentation. -#[no_mangle] -pub unsafe extern "C" fn wasm_store_data_set(store: &mut wasm_store_t, new_val: *mut c_void) { - *store - .context - .as_mut() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow_mut() - .inner - .data_mut() = new_val; -} - /// Deletes a WebAssembly store. /// /// # Example diff --git a/lib/c-api/src/wasm_c_api/types/extern_.rs b/lib/c-api/src/wasm_c_api/types/extern_.rs index b97f4f54f15..4218c2a70d4 100644 --- a/lib/c-api/src/wasm_c_api/types/extern_.rs +++ b/lib/c-api/src/wasm_c_api/types/extern_.rs @@ -9,7 +9,7 @@ use thiserror::Error; use wasmer_api::ExternType; #[allow(non_camel_case_types)] -type wasm_externkind_t = u8; +pub type wasm_externkind_t = u8; #[allow(non_camel_case_types)] #[repr(u8)] diff --git a/lib/c-api/src/wasm_c_api/unstable/middlewares/metering.rs b/lib/c-api/src/wasm_c_api/unstable/middlewares/metering.rs index bc4eb715470..f46301e672f 100644 --- a/lib/c-api/src/wasm_c_api/unstable/middlewares/metering.rs +++ b/lib/c-api/src/wasm_c_api/unstable/middlewares/metering.rs @@ -45,8 +45,6 @@ //! // Create the engine and the store based on the configuration. //! wasm_engine_t* engine = wasm_engine_new_with_config(config); //! wasm_store_t* store = wasm_store_new(engine); -//! wasm_context_t* ctx = wasm_context_new(store, 0); -//! wasm_store_context_set(store, ctx); //! //! // Create the new WebAssembly module. //! wasm_byte_vec_t wat; @@ -134,7 +132,6 @@ //! ``` use super::super::super::instance::wasm_instance_t; -use super::super::super::store::wasm_store_t; use super::super::parser::operator::wasmer_parser_operator_t; use super::wasmer_middleware_t; use std::sync::Arc; @@ -204,13 +201,10 @@ pub extern "C" fn wasmer_metering_delete(_metering: Option u64 { - let mut ctx = instance - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow_mut(); - match get_remaining_points(&mut ctx.inner, &instance.inner) { +pub unsafe extern "C" fn wasmer_metering_get_remaining_points( + instance: &mut wasm_instance_t, +) -> u64 { + match get_remaining_points(&mut instance.store.store_mut(), &instance.inner) { MeteringPoints::Remaining(value) => value, MeteringPoints::Exhausted => std::u64::MAX, } @@ -222,14 +216,11 @@ pub extern "C" fn wasmer_metering_get_remaining_points(instance: &wasm_instance_ /// /// See module's documentation. #[no_mangle] -pub extern "C" fn wasmer_metering_points_are_exhausted(instance: &wasm_instance_t) -> bool { - let mut ctx = instance - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow_mut(); +pub unsafe extern "C" fn wasmer_metering_points_are_exhausted( + instance: &mut wasm_instance_t, +) -> bool { matches!( - get_remaining_points(&mut ctx.inner, &instance.inner), + get_remaining_points(&mut instance.store.store_mut(), &instance.inner), MeteringPoints::Exhausted, ) } @@ -271,8 +262,6 @@ pub extern "C" fn wasmer_metering_points_are_exhausted(instance: &wasm_instance_ /// wasm_engine_t* engine = wasm_engine_new_with_config(config); /// /// wasm_store_t* store = wasm_store_new(engine); -/// wasm_context_t* ctx = wasm_context_new(store, 0); -/// wasm_store_context_set(store, ctx); /// /// // Create the module and instantiate it. /// wasm_byte_vec_t wat; @@ -309,13 +298,11 @@ pub extern "C" fn wasmer_metering_points_are_exhausted(instance: &wasm_instance_ /// # } /// ``` #[no_mangle] -pub extern "C" fn wasmer_metering_set_remaining_points(instance: &wasm_instance_t, new_limit: u64) { - let mut ctx = instance - .context - .as_ref() - .expect(wasm_store_t::CTX_ERR_STR) - .borrow_mut(); - set_remaining_points(&mut ctx.inner, &instance.inner, new_limit); +pub unsafe extern "C" fn wasmer_metering_set_remaining_points( + instance: &mut wasm_instance_t, + new_limit: u64, +) { + set_remaining_points(&mut instance.store.store_mut(), &instance.inner, new_limit); } /// Transforms a [`wasmer_metering_t`] into a generic diff --git a/lib/c-api/src/wasm_c_api/unstable/module.rs b/lib/c-api/src/wasm_c_api/unstable/module.rs index 81528369bd0..b53e0b14608 100644 --- a/lib/c-api/src/wasm_c_api/unstable/module.rs +++ b/lib/c-api/src/wasm_c_api/unstable/module.rs @@ -4,7 +4,6 @@ use super::super::module::wasm_module_t; use super::super::types::wasm_name_t; use std::ptr; use std::str; -use std::sync::Arc; /// Unstable non-standard Wasmer-specific API to get the module's /// name, otherwise `out->size` is set to `0` and `out->data` to @@ -149,8 +148,5 @@ pub unsafe extern "C" fn wasmer_module_set_name( Err(_) => return false, // not ideal! }; - match Arc::get_mut(&mut module.inner) { - Some(module) => module.set_name(name), - None => false, - } + module.inner.set_name(name) } diff --git a/lib/c-api/src/wasm_c_api/unstable/wasi.rs b/lib/c-api/src/wasm_c_api/unstable/wasi.rs index 0abbf923267..f37a5e510f8 100644 --- a/lib/c-api/src/wasm_c_api/unstable/wasi.rs +++ b/lib/c-api/src/wasm_c_api/unstable/wasi.rs @@ -2,11 +2,8 @@ //! API. use super::super::{ - externals::wasm_extern_t, module::wasm_module_t, store::wasm_store_t, types::wasm_name_t, - wasi::wasi_env_t, + externals::wasm_extern_t, module::wasm_module_t, types::wasm_name_t, wasi::wasi_env_t, }; -use wasmer_api::{AsContextMut, Extern}; -use wasmer_wasi::{generate_import_object_from_ctx, get_wasi_version}; /// Unstable non-standard type wrapping `wasm_extern_t` with the /// addition of two `wasm_name_t` respectively for the module name and @@ -147,46 +144,36 @@ pub extern "C" fn wasmer_named_extern_unwrap( /// based on the `wasm_module_t` requirements. #[no_mangle] pub unsafe extern "C" fn wasi_get_unordered_imports( - store: Option<&wasm_store_t>, + wasi_env: Option<&mut wasi_env_t>, module: Option<&wasm_module_t>, - wasi_env: Option<&wasi_env_t>, imports: &mut wasmer_named_extern_vec_t, ) -> bool { - wasi_get_unordered_imports_inner(store, module, wasi_env, imports).is_some() + wasi_get_unordered_imports_inner(wasi_env, module, imports).is_some() } -fn wasi_get_unordered_imports_inner( - store: Option<&wasm_store_t>, +unsafe fn wasi_get_unordered_imports_inner( + wasi_env: Option<&mut wasi_env_t>, module: Option<&wasm_module_t>, - wasi_env: Option<&wasi_env_t>, imports: &mut wasmer_named_extern_vec_t, ) -> Option<()> { - let store = store?; - if store.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let mut ctx = store.context.as_ref()?.borrow_mut(); + let wasi_env = wasi_env?; + let store = &mut wasi_env.store; + let mut store_mut = store.store_mut(); let module = module?; - let _wasi_env = wasi_env?; - - let version = c_try!(get_wasi_version(&module.inner, false) - .ok_or("could not detect a WASI version on the given module")); - let inner = unsafe { ctx.inner.transmute_data::() }; - let import_object = generate_import_object_from_ctx(&mut inner.as_context_mut(), version); + let import_object = c_try!(wasi_env.inner.import_object(&mut store_mut, &module.inner)); imports.set_buffer( import_object .into_iter() - .map(|((module, name), extern_)| { + .map(move |((module, name), extern_)| { let module = module.into(); let name = name.into(); - let extern_inner = Extern::from_vm_extern(&mut ctx.inner, extern_.to_vm_extern()); Some(Box::new(wasmer_named_extern_t { module, name, - r#extern: Box::new(extern_inner.into()), + r#extern: Box::new(wasm_extern_t::new(store.clone(), extern_)), })) }) .collect::>(), diff --git a/lib/c-api/src/wasm_c_api/value.rs b/lib/c-api/src/wasm_c_api/value.rs index db07a813b4c..130bb9782dd 100644 --- a/lib/c-api/src/wasm_c_api/value.rs +++ b/lib/c-api/src/wasm_c_api/value.rs @@ -1,5 +1,4 @@ use super::types::{wasm_ref_t, wasm_valkind_enum}; -use crate::error::update_last_error; use std::convert::{TryFrom, TryInto}; use wasmer_api::Value; @@ -137,8 +136,8 @@ pub unsafe extern "C" fn wasm_val_copy( val: &wasm_val_t, ) { out.kind = val.kind; - out.of = match val.kind.try_into() { - Ok(kind) => match kind { + out.of = c_try!(val.kind.try_into().map(|kind| { + match kind { wasm_valkind_enum::WASM_I32 => wasm_val_inner { int32_t: val.of.int32_t, }, @@ -153,14 +152,8 @@ pub unsafe extern "C" fn wasm_val_copy( }, wasm_valkind_enum::WASM_ANYREF => wasm_val_inner { wref: val.of.wref }, wasm_valkind_enum::WASM_FUNCREF => wasm_val_inner { wref: val.of.wref }, - }, - - Err(e) => { - update_last_error(e); - - return; } - }; + }); otherwise ()); } #[no_mangle] diff --git a/lib/c-api/src/wasm_c_api/wasi/mod.rs b/lib/c-api/src/wasm_c_api/wasi/mod.rs index 1e7dc61a0b7..54ed50ed46b 100644 --- a/lib/c-api/src/wasm_c_api/wasi/mod.rs +++ b/lib/c-api/src/wasm_c_api/wasi/mod.rs @@ -4,20 +4,18 @@ pub use super::unstable::wasi::wasi_get_unordered_imports; use super::{ - externals::{wasm_extern_vec_t, wasm_func_t}, + externals::{wasm_extern_t, wasm_extern_vec_t, wasm_func_t}, instance::wasm_instance_t, module::wasm_module_t, - store::wasm_store_t, + store::{wasm_store_t, StoreRef}, }; use crate::error::update_last_error; use std::convert::TryFrom; use std::ffi::CStr; use std::os::raw::c_char; use std::slice; -use wasmer_api::{AsContextMut, Extern}; use wasmer_wasi::{ - generate_import_object_from_ctx, get_wasi_version, Pipe, WasiEnv, WasiFile, WasiState, - WasiStateBuilder, WasiVersion, + get_wasi_version, Pipe, WasiFile, WasiFunctionEnv, WasiState, WasiStateBuilder, WasiVersion, }; #[derive(Debug)] @@ -163,14 +161,20 @@ pub extern "C" fn wasi_config_inherit_stdin(config: &mut wasi_config_t) { #[allow(non_camel_case_types)] pub struct wasi_env_t { /// cbindgen:ignore - pub(super) inner: WasiEnv, + pub(super) inner: WasiFunctionEnv, + pub(super) store: StoreRef, } /// Create a new WASI environment. /// /// It take ownership over the `wasi_config_t`. #[no_mangle] -pub extern "C" fn wasi_env_new(mut config: Box) -> Option> { +pub unsafe extern "C" fn wasi_env_new( + store: Option<&mut wasm_store_t>, + mut config: Box, +) -> Option> { + let store = &mut store?.inner; + let mut store_mut = store.store_mut(); if !config.inherit_stdout { config.state_builder.stdout(Box::new(Pipe::new())); } @@ -181,10 +185,11 @@ pub extern "C" fn wasi_env_new(mut config: Box) -> Option isize { let inner_buffer = slice::from_raw_parts_mut(buffer as *mut _, buffer_len as usize); - let state = env.inner.state(); + let mut store_mut = env.store.store_mut(); + let state = env.inner.data_mut(&mut store_mut).state(); if let Ok(mut stdout) = state.stdout() { if let Some(stdout) = stdout.as_mut() { @@ -221,7 +227,8 @@ pub unsafe extern "C" fn wasi_env_read_stderr( buffer_len: usize, ) -> isize { let inner_buffer = slice::from_raw_parts_mut(buffer as *mut _, buffer_len as usize); - let state = env.inner.state(); + let mut store_mut = env.store.store_mut(); + let state = env.inner.data_mut(&mut store_mut).state(); if let Ok(mut stderr) = state.stderr() { if let Some(stderr) = stderr.as_mut() { read_inner(stderr, inner_buffer) @@ -320,30 +327,25 @@ pub unsafe extern "C" fn wasi_get_wasi_version(module: &wasm_module_t) -> wasi_v /// implementation ordered as expected by the `wasm_module_t`. #[no_mangle] pub unsafe extern "C" fn wasi_get_imports( - store: Option<&wasm_store_t>, + _store: Option<&wasm_store_t>, + wasi_env: Option<&mut wasi_env_t>, module: Option<&wasm_module_t>, imports: &mut wasm_extern_vec_t, ) -> bool { - wasi_get_imports_inner(store, module, imports).is_some() + wasi_get_imports_inner(wasi_env, module, imports).is_some() } -fn wasi_get_imports_inner( - store: Option<&wasm_store_t>, +unsafe fn wasi_get_imports_inner( + wasi_env: Option<&mut wasi_env_t>, module: Option<&wasm_module_t>, imports: &mut wasm_extern_vec_t, ) -> Option<()> { - let store = store?; - if store.context.is_none() { - crate::error::update_last_error(wasm_store_t::CTX_ERR_STR); - } - let mut ctx = store.context.as_ref()?.borrow_mut(); + let wasi_env = wasi_env?; + let store = &mut wasi_env.store; + let mut store_mut = store.store_mut(); let module = module?; - let version = c_try!(get_wasi_version(&module.inner, false) - .ok_or("could not detect a WASI version on the given module")); - - let inner = unsafe { ctx.inner.transmute_data::() }; - let import_object = generate_import_object_from_ctx(&mut inner.as_context_mut(), version); + let import_object = c_try!(wasi_env.inner.import_object(&mut store_mut, &module.inner)); imports.set_buffer(c_try!(module .inner @@ -358,22 +360,37 @@ fn wasi_get_imports_inner( import_type.name() ) })?; - let inner = Extern::from_vm_extern(&mut ctx.inner, ext.to_vm_extern()); - Ok(Some(Box::new(inner.into()))) + Ok(Some(Box::new(wasm_extern_t::new(store.clone(), ext)))) }) .collect::, String>>())); Some(()) } +#[no_mangle] +pub unsafe extern "C" fn wasi_env_initialize_instance( + wasi_env: &mut wasi_env_t, + store: &mut wasm_store_t, + instance: &mut wasm_instance_t, +) -> bool { + let mem = c_try!(instance.inner.exports.get_memory("memory"); otherwise false); + wasi_env + .inner + .data_mut(&mut store.inner.store_mut()) + .set_memory(mem.clone()); + true +} + #[no_mangle] pub unsafe extern "C" fn wasi_get_start_function( instance: &mut wasm_instance_t, ) -> Option> { let start = c_try!(instance.inner.exports.get_function("_start")); - Some(Box::new(wasm_func_t::new(start.clone()))) + Some(Box::new(wasm_func_t { + extern_: wasm_extern_t::new(instance.store.clone(), start.clone().into()), + })) } #[cfg(test)] @@ -388,7 +405,7 @@ mod tests { int main() { wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); + wasmer_funcenv_t* env = wasmer_funcenv_new(store, 0); wasm_byte_vec_t wat; wasmer_byte_vec_new_from_string(&wat, "(module (import \"wasi_unstable\" \"args_get\" (func (param i32 i32) (result i32))))"); @@ -403,7 +420,7 @@ mod tests { wasm_module_delete(module); wasm_byte_vec_delete(&wasm); wasm_byte_vec_delete(&wat); - wasm_context_delete(ctx); + wasmer_funcenv_delete(env); wasm_store_delete(store); wasm_engine_delete(engine); @@ -421,7 +438,7 @@ mod tests { int main() { wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); + wasmer_funcenv_t* env = wasmer_funcenv_new(store, 0); wasm_byte_vec_t wat; wasmer_byte_vec_new_from_string(&wat, "(module (import \"wasi_snapshot_preview1\" \"args_get\" (func (param i32 i32) (result i32))))"); @@ -436,7 +453,7 @@ mod tests { wasm_module_delete(module); wasm_byte_vec_delete(&wasm); wasm_byte_vec_delete(&wat); - wasm_context_delete(ctx); + wasmer_funcenv_delete(env); wasm_store_delete(store); wasm_engine_delete(engine); @@ -454,7 +471,7 @@ mod tests { int main() { wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); + wasmer_funcenv_t* env = wasmer_funcenv_new(store, 0); wasm_byte_vec_t wat; wasmer_byte_vec_new_from_string(&wat, "(module (import \"wasi_snpsht_prvw1\" \"args_get\" (func (param i32 i32) (result i32))))"); @@ -469,7 +486,7 @@ mod tests { wasm_module_delete(module); wasm_byte_vec_delete(&wasm); wasm_byte_vec_delete(&wat); - wasm_context_delete(ctx); + wasmer_funcenv_delete(env); wasm_store_delete(store); wasm_engine_delete(engine); diff --git a/lib/c-api/tests/wasm-c-api/example/callback.c b/lib/c-api/tests/wasm-c-api/example/callback.c index 977ca727a4f..2fddb1634ff 100644 --- a/lib/c-api/tests/wasm-c-api/example/callback.c +++ b/lib/c-api/tests/wasm-c-api/example/callback.c @@ -35,7 +35,7 @@ void wasm_val_print(wasm_val_t val) { // A function to be called from Wasm code. own wasm_trap_t* print_callback( - wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results + const wasm_val_vec_t* args, wasm_val_vec_t* results ) { printf("Calling back...\n> "); wasm_val_print(args->data[0]); @@ -48,9 +48,9 @@ own wasm_trap_t* print_callback( // A function closure. own wasm_trap_t* closure_callback( - wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results + void* env, const wasm_val_vec_t* args, wasm_val_vec_t* results ) { - int i = *(int*) wasm_context_ref_mut_get(ctx_mut); + int i = *(int*)env; printf("Calling back closure...\n"); printf("> %d\n", i); @@ -65,9 +65,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - int i = 42; - wasm_context_t* ctx = wasm_context_new(store, &i); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); @@ -102,8 +99,9 @@ int main(int argc, const char* argv[]) { own wasm_functype_t* print_type = wasm_functype_new_1_1(wasm_valtype_new_i32(), wasm_valtype_new_i32()); own wasm_func_t* print_func = wasm_func_new(store, print_type, print_callback); + int i = 42; own wasm_functype_t* closure_type = wasm_functype_new_0_1(wasm_valtype_new_i32()); - own wasm_func_t* closure_func = wasm_func_new(store, closure_type, closure_callback); + own wasm_func_t* closure_func = wasm_func_new_with_env(store, closure_type, closure_callback, &i, NULL); wasm_functype_delete(print_type); wasm_functype_delete(closure_type); diff --git a/lib/c-api/tests/wasm-c-api/example/callback.cc b/lib/c-api/tests/wasm-c-api/example/callback.cc index 27c1b6545d3..957629cabc8 100644 --- a/lib/c-api/tests/wasm-c-api/example/callback.cc +++ b/lib/c-api/tests/wasm-c-api/example/callback.cc @@ -7,22 +7,22 @@ #include "wasm.hh" // Print a Wasm value -auto operator<<(std::ostream& out, const wasm::Value& val) -> std::ostream& { +auto operator<<(std::ostream& out, const wasm::Val& val) -> std::ostream& { switch (val.kind()) { - case wasm::ValueKind::I32: { + case wasm::ValKind::I32: { out << val.i32(); } break; - case wasm::ValueKind::I64: { + case wasm::ValKind::I64: { out << val.i64(); } break; - case wasm::ValueKind::F32: { + case wasm::ValKind::F32: { out << val.f32(); } break; - case wasm::ValueKind::F64: { + case wasm::ValKind::F64: { out << val.f64(); } break; - case wasm::ValueKind::ANYREF: - case wasm::ValueKind::FUNCREF: { + case wasm::ValKind::ANYREF: + case wasm::ValKind::FUNCREF: { if (val.ref() == nullptr) { out << "null"; } else { @@ -35,7 +35,7 @@ auto operator<<(std::ostream& out, const wasm::Value& val) -> std::ostream& { // A function to be called from Wasm code. auto print_callback( - const wasm::vec& args, wasm::vec& results + const wasm::vec& args, wasm::vec& results ) -> wasm::own { std::cout << "Calling back..." << std::endl << "> " << args[0] << std::endl; results[0] = args[0].copy(); @@ -45,12 +45,12 @@ auto print_callback( // A function closure. auto closure_callback( - void* env, const wasm::vec& args, wasm::vec& results + void* env, const wasm::vec& args, wasm::vec& results ) -> wasm::own { auto i = *reinterpret_cast(env); std::cout << "Calling back closure..." << std::endl; std::cout << "> " << i << std::endl; - results[0] = wasm::Value::i32(static_cast(i)); + results[0] = wasm::Val::i32(static_cast(i)); return nullptr; } @@ -87,8 +87,8 @@ void run() { // Create external print functions. std::cout << "Creating callback..." << std::endl; auto print_type = wasm::FuncType::make( - wasm::ownvec::make(wasm::ValueType::make(wasm::ValueKind::I32)), - wasm::ownvec::make(wasm::ValueType::make(wasm::ValueKind::I32)) + wasm::ownvec::make(wasm::ValType::make(wasm::ValKind::I32)), + wasm::ownvec::make(wasm::ValType::make(wasm::ValKind::I32)) ); auto print_func = wasm::Func::make(store, print_type.get(), print_callback); @@ -96,8 +96,8 @@ void run() { std::cout << "Creating closure..." << std::endl; int i = 42; auto closure_type = wasm::FuncType::make( - wasm::ownvec::make(), - wasm::ownvec::make(wasm::ValueType::make(wasm::ValueKind::I32)) + wasm::ownvec::make(), + wasm::ownvec::make(wasm::ValType::make(wasm::ValKind::I32)) ); auto closure_func = wasm::Func::make(store, closure_type.get(), closure_callback, &i); @@ -122,8 +122,8 @@ void run() { // Call. std::cout << "Calling export..." << std::endl; - auto args = wasm::vec::make(wasm::Value::i32(3), wasm::Value::i32(4)); - auto results = wasm::vec::make_uninitialized(1); + auto args = wasm::vec::make(wasm::Val::i32(3), wasm::Val::i32(4)); + auto results = wasm::vec::make_uninitialized(1); if (run_func->call(args, results)) { std::cout << "> Error calling function!" << std::endl; exit(1); diff --git a/lib/c-api/tests/wasm-c-api/example/finalize.c b/lib/c-api/tests/wasm-c-api/example/finalize.c index 6532c3a6bdb..4f2efc598a2 100644 --- a/lib/c-api/tests/wasm-c-api/example/finalize.c +++ b/lib/c-api/tests/wasm-c-api/example/finalize.c @@ -12,8 +12,8 @@ const int iterations = 100000; int live_count = 0; void finalize(void* data) { - int i = (int)data; - if (i % (iterations / 10) == 0) printf("Finalizing #%d...\n", i); + intptr_t i = (intptr_t)data; + if (i % (iterations / 10) == 0) printf("Finalizing #%" PRIdPTR "...\n", i); --live_count; } @@ -74,8 +74,6 @@ int main(int argc, const char* argv[]) { printf("Live count %d\n", live_count); printf("Creating store 1...\n"); wasm_store_t* store1 = wasm_store_new(engine); - wasm_context_t* ctx1 = wasm_context_new(store1, 0); - wasm_store_context_set(store1, ctx1); printf("Running in store 1...\n"); run_in_store(store1); @@ -83,8 +81,6 @@ int main(int argc, const char* argv[]) { printf("Creating store 2...\n"); wasm_store_t* store2 = wasm_store_new(engine); - wasm_context_t* ctx2 = wasm_context_new(store2, 0); - wasm_store_context_set(store2, ctx2); printf("Running in store 2...\n"); run_in_store(store2); diff --git a/lib/c-api/tests/wasm-c-api/example/global.c b/lib/c-api/tests/wasm-c-api/example/global.c index 2187c5cdd63..5bd403369c3 100644 --- a/lib/c-api/tests/wasm-c-api/example/global.c +++ b/lib/c-api/tests/wasm-c-api/example/global.c @@ -52,8 +52,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/global.cc b/lib/c-api/tests/wasm-c-api/example/global.cc index a1770ef82d1..178eb61f8b7 100644 --- a/lib/c-api/tests/wasm-c-api/example/global.cc +++ b/lib/c-api/tests/wasm-c-api/example/global.cc @@ -31,9 +31,9 @@ void check(T actual, U expected) { } } -auto call(const wasm::Func* func) -> wasm::Value { - auto args = wasm::vec::make(); - auto results = wasm::vec::make_uninitialized(1); +auto call(const wasm::Func* func) -> wasm::Val { + auto args = wasm::vec::make(); + auto results = wasm::vec::make_uninitialized(1); if (func->call(args, results)) { std::cout << "> Error calling function!" << std::endl; exit(1); @@ -41,9 +41,9 @@ auto call(const wasm::Func* func) -> wasm::Value { return results[0].copy(); } -void call(const wasm::Func* func, wasm::Value&& arg) { - auto args = wasm::vec::make(std::move(arg)); - auto results = wasm::vec::make(); +void call(const wasm::Func* func, wasm::Val&& arg) { + auto args = wasm::vec::make(std::move(arg)); + auto results = wasm::vec::make(); if (func->call(args, results)) { std::cout << "> Error calling function!" << std::endl; exit(1); @@ -83,17 +83,17 @@ void run() { // Create external globals. std::cout << "Creating globals..." << std::endl; auto const_f32_type = wasm::GlobalType::make( - wasm::ValueType::make(wasm::ValueKind::F32), wasm::Mutability::CONST); + wasm::ValType::make(wasm::ValKind::F32), wasm::Mutability::CONST); auto const_i64_type = wasm::GlobalType::make( - wasm::ValueType::make(wasm::ValueKind::I64), wasm::Mutability::CONST); + wasm::ValType::make(wasm::ValKind::I64), wasm::Mutability::CONST); auto var_f32_type = wasm::GlobalType::make( - wasm::ValueType::make(wasm::ValueKind::F32), wasm::Mutability::VAR); + wasm::ValType::make(wasm::ValKind::F32), wasm::Mutability::VAR); auto var_i64_type = wasm::GlobalType::make( - wasm::ValueType::make(wasm::ValueKind::I64), wasm::Mutability::VAR); - auto const_f32_import = wasm::Global::make(store, const_f32_type.get(), wasm::Value::f32(1)); - auto const_i64_import = wasm::Global::make(store, const_i64_type.get(), wasm::Value::i64(2)); - auto var_f32_import = wasm::Global::make(store, var_f32_type.get(), wasm::Value::f32(3)); - auto var_i64_import = wasm::Global::make(store, var_i64_type.get(), wasm::Value::i64(4)); + wasm::ValType::make(wasm::ValKind::I64), wasm::Mutability::VAR); + auto const_f32_import = wasm::Global::make(store, const_f32_type.get(), wasm::Val::f32(1)); + auto const_i64_import = wasm::Global::make(store, const_i64_type.get(), wasm::Val::i64(2)); + auto var_f32_import = wasm::Global::make(store, var_f32_type.get(), wasm::Val::f32(3)); + auto var_i64_import = wasm::Global::make(store, var_i64_type.get(), wasm::Val::i64(4)); // Instantiate. std::cout << "Instantiating module..." << std::endl; @@ -154,10 +154,10 @@ void run() { check(call(get_var_i64_export).i64(), 8); // Modify variables through API and check again. - var_f32_import->set(wasm::Value::f32(33)); - var_i64_import->set(wasm::Value::i64(34)); - var_f32_export->set(wasm::Value::f32(37)); - var_i64_export->set(wasm::Value::i64(38)); + var_f32_import->set(wasm::Val::f32(33)); + var_i64_import->set(wasm::Val::i64(34)); + var_f32_export->set(wasm::Val::f32(37)); + var_i64_export->set(wasm::Val::i64(38)); check(var_f32_import->get().f32(), 33); check(var_i64_import->get().i64(), 34); @@ -170,10 +170,10 @@ void run() { check(call(get_var_i64_export).i64(), 38); // Modify variables through calls and check again. - call(set_var_f32_import, wasm::Value::f32(73)); - call(set_var_i64_import, wasm::Value::i64(74)); - call(set_var_f32_export, wasm::Value::f32(77)); - call(set_var_i64_export, wasm::Value::i64(78)); + call(set_var_f32_import, wasm::Val::f32(73)); + call(set_var_i64_import, wasm::Val::i64(74)); + call(set_var_f32_export, wasm::Val::f32(77)); + call(set_var_i64_export, wasm::Val::i64(78)); check(var_f32_import->get().f32(), 73); check(var_i64_import->get().i64(), 74); diff --git a/lib/c-api/tests/wasm-c-api/example/hello.c b/lib/c-api/tests/wasm-c-api/example/hello.c index 555cd0a16e1..712f4593140 100644 --- a/lib/c-api/tests/wasm-c-api/example/hello.c +++ b/lib/c-api/tests/wasm-c-api/example/hello.c @@ -9,7 +9,7 @@ // A function to be called from Wasm code. own wasm_trap_t* hello_callback( - wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results + const wasm_val_vec_t* args, wasm_val_vec_t* results ) { printf("Calling back...\n"); printf("> Hello World!\n"); @@ -22,8 +22,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); @@ -43,6 +41,13 @@ int main(int argc, const char* argv[]) { } fclose(file); + // Validate. + printf("Validating module...\n"); + if (!wasm_module_validate(store, &binary)) { + printf("> Error validating module!\n"); + return 1; + } + // Compile. printf("Compiling module...\n"); own wasm_module_t* module = wasm_module_new(store, &binary); diff --git a/lib/c-api/tests/wasm-c-api/example/hello.cc b/lib/c-api/tests/wasm-c-api/example/hello.cc index 94eb567b8c8..c2a73c8745b 100644 --- a/lib/c-api/tests/wasm-c-api/example/hello.cc +++ b/lib/c-api/tests/wasm-c-api/example/hello.cc @@ -38,6 +38,13 @@ void run() { exit(1); } + // Validate. + std::cout << "Validating module..." << std::endl; + if (!wasm::Module::validate(store, binary)) { + std::cout << "> Error validating module!" << std::endl; + exit(1); + } + // Compile. std::cout << "Compiling module..." << std::endl; auto module = wasm::Module::make(store, binary); diff --git a/lib/c-api/tests/wasm-c-api/example/hostref.c b/lib/c-api/tests/wasm-c-api/example/hostref.c index d392e2c9b9c..1e787ab1902 100644 --- a/lib/c-api/tests/wasm-c-api/example/hostref.c +++ b/lib/c-api/tests/wasm-c-api/example/hostref.c @@ -10,7 +10,7 @@ // A function to be called from Wasm code. own wasm_trap_t* callback( - wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results + const wasm_val_vec_t* args, wasm_val_vec_t* results ) { printf("Calling back...\n> "); printf("> %p\n", @@ -127,8 +127,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/hostref.cc b/lib/c-api/tests/wasm-c-api/example/hostref.cc index f9747b91060..09c239e0c91 100644 --- a/lib/c-api/tests/wasm-c-api/example/hostref.cc +++ b/lib/c-api/tests/wasm-c-api/example/hostref.cc @@ -9,7 +9,7 @@ // A function to be called from Wasm code. auto callback( - const wasm::vec& args, wasm::vec& results + const wasm::vec& args, wasm::vec& results ) -> wasm::own { std::cout << "Calling back..." << std::endl; std::cout << "> " << (args[0].ref() ? args[0].ref()->get_host_info() : nullptr) << std::endl; @@ -45,8 +45,8 @@ auto get_export_table(wasm::ownvec& exports, size_t i) -> wasm::Ta void call_r_v(const wasm::Func* func, const wasm::Ref* ref) { std::cout << "call_r_v... " << std::flush; - auto args = wasm::vec::make(wasm::Value::ref(ref ? ref->copy() : wasm::own())); - auto results = wasm::vec::make(); + auto args = wasm::vec::make(wasm::Val::ref(ref ? ref->copy() : wasm::own())); + auto results = wasm::vec::make(); if (func->call(args, results)) { std::cout << "> Error calling function!" << std::endl; exit(1); @@ -56,8 +56,8 @@ void call_r_v(const wasm::Func* func, const wasm::Ref* ref) { auto call_v_r(const wasm::Func* func) -> wasm::own { std::cout << "call_v_r... " << std::flush; - auto args = wasm::vec::make(); - auto results = wasm::vec::make_uninitialized(1); + auto args = wasm::vec::make(); + auto results = wasm::vec::make_uninitialized(1); if (func->call(args, results)) { std::cout << "> Error calling function!" << std::endl; exit(1); @@ -68,8 +68,8 @@ auto call_v_r(const wasm::Func* func) -> wasm::own { auto call_r_r(const wasm::Func* func, const wasm::Ref* ref) -> wasm::own { std::cout << "call_r_r... " << std::flush; - auto args = wasm::vec::make(wasm::Value::ref(ref ? ref->copy() : wasm::own())); - auto results = wasm::vec::make_uninitialized(1); + auto args = wasm::vec::make(wasm::Val::ref(ref ? ref->copy() : wasm::own())); + auto results = wasm::vec::make_uninitialized(1); if (func->call(args, results)) { std::cout << "> Error calling function!" << std::endl; exit(1); @@ -80,9 +80,9 @@ auto call_r_r(const wasm::Func* func, const wasm::Ref* ref) -> wasm::own::make( - wasm::Value::i32(i), wasm::Value::ref(ref ? ref->copy() : wasm::own())); - auto results = wasm::vec::make(); + auto args = wasm::vec::make( + wasm::Val::i32(i), wasm::Val::ref(ref ? ref->copy() : wasm::own())); + auto results = wasm::vec::make(); if (func->call(args, results)) { std::cout << "> Error calling function!" << std::endl; exit(1); @@ -92,8 +92,8 @@ void call_ir_v(const wasm::Func* func, int32_t i, const wasm::Ref* ref) { auto call_i_r(const wasm::Func* func, int32_t i) -> wasm::own { std::cout << "call_i_r... " << std::flush; - auto args = wasm::vec::make(wasm::Value::i32(i)); - auto results = wasm::vec::make_uninitialized(1); + auto args = wasm::vec::make(wasm::Val::i32(i)); + auto results = wasm::vec::make_uninitialized(1); if (func->call(args, results)) { std::cout << "> Error calling function!" << std::endl; exit(1); @@ -144,8 +144,8 @@ void run() { // Create external callback function. std::cout << "Creating callback..." << std::endl; auto callback_type = wasm::FuncType::make( - wasm::ownvec::make(wasm::ValueType::make(wasm::ValueKind::ANYREF)), - wasm::ownvec::make(wasm::ValueType::make(wasm::ValueKind::ANYREF)) + wasm::ownvec::make(wasm::ValType::make(wasm::ValKind::ANYREF)), + wasm::ownvec::make(wasm::ValType::make(wasm::ValKind::ANYREF)) ); auto callback_func = wasm::Func::make(store, callback_type.get(), callback); @@ -182,7 +182,7 @@ void run() { check(host1->copy(), host1.get()); check(host2->copy(), host2.get()); - wasm::Value val = wasm::Value::ref(host1->copy()); + wasm::Val val = wasm::Val::ref(host1->copy()); check(val.ref()->copy(), host1.get()); auto ref = val.release_ref(); assert(val.ref() == nullptr); @@ -199,7 +199,7 @@ void run() { check(call_v_r(global_get), nullptr); check(global->get().release_ref(), nullptr); - global->set(wasm::Value(host2->copy())); + global->set(wasm::Val(host2->copy())); check(call_v_r(global_get), host2.get()); check(global->get().release_ref(), host2.get()); diff --git a/lib/c-api/tests/wasm-c-api/example/memory.c b/lib/c-api/tests/wasm-c-api/example/memory.c index 9380a52ab4a..edd4ebadd0b 100644 --- a/lib/c-api/tests/wasm-c-api/example/memory.c +++ b/lib/c-api/tests/wasm-c-api/example/memory.c @@ -98,8 +98,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/memory.cc b/lib/c-api/tests/wasm-c-api/example/memory.cc index 4f0bf20f3e7..6cc36192a85 100644 --- a/lib/c-api/tests/wasm-c-api/example/memory.cc +++ b/lib/c-api/tests/wasm-c-api/example/memory.cc @@ -33,8 +33,8 @@ void check(T actual, U expected) { template void check_ok(const wasm::Func* func, Args... xs) { - auto args = wasm::vec::make(wasm::Value::i32(xs)...); - auto results = wasm::vec::make(); + auto args = wasm::vec::make(wasm::Val::i32(xs)...); + auto results = wasm::vec::make(); if (func->call(args, results)) { std::cout << "> Error on result, expected return" << std::endl; exit(1); @@ -43,8 +43,8 @@ void check_ok(const wasm::Func* func, Args... xs) { template void check_trap(const wasm::Func* func, Args... xs) { - auto args = wasm::vec::make(wasm::Value::i32(xs)...); - auto results = wasm::vec::make(); + auto args = wasm::vec::make(wasm::Val::i32(xs)...); + auto results = wasm::vec::make(); if (! func->call(args, results)) { std::cout << "> Error on result, expected trap" << std::endl; exit(1); @@ -53,8 +53,8 @@ void check_trap(const wasm::Func* func, Args... xs) { template auto call(const wasm::Func* func, Args... xs) -> int32_t { - auto args = wasm::vec::make(wasm::Value::i32(xs)...); - auto results = wasm::vec::make_uninitialized(1); + auto args = wasm::vec::make(wasm::Val::i32(xs)...); + auto results = wasm::vec::make_uninitialized(1); if (func->call(args, results)) { std::cout << "> Error on result, expected return" << std::endl; exit(1); diff --git a/lib/c-api/tests/wasm-c-api/example/multi.c b/lib/c-api/tests/wasm-c-api/example/multi.c index 517429d240b..4a31e7e4da5 100644 --- a/lib/c-api/tests/wasm-c-api/example/multi.c +++ b/lib/c-api/tests/wasm-c-api/example/multi.c @@ -9,7 +9,7 @@ // A function to be called from Wasm code. own wasm_trap_t* callback( - wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results + const wasm_val_vec_t* args, wasm_val_vec_t* results ) { printf("Calling back...\n> "); printf("> %"PRIu32" %"PRIu64" %"PRIu64" %"PRIu32"\n", @@ -44,8 +44,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/multi.cc b/lib/c-api/tests/wasm-c-api/example/multi.cc index 7c167a727e1..6d083557114 100644 --- a/lib/c-api/tests/wasm-c-api/example/multi.cc +++ b/lib/c-api/tests/wasm-c-api/example/multi.cc @@ -8,7 +8,7 @@ // A function to be called from Wasm code. auto callback( - const wasm::vec& args, wasm::vec& results + const wasm::vec& args, wasm::vec& results ) -> wasm::own { std::cout << "Calling back..." << std::endl; std::cout << "> " << args[0].i32(); @@ -54,11 +54,11 @@ void run() { // Create external print functions. std::cout << "Creating callback..." << std::endl; - auto tuple = wasm::ownvec::make( - wasm::ValueType::make(wasm::ValueKind::I32), - wasm::ValueType::make(wasm::ValueKind::I64), - wasm::ValueType::make(wasm::ValueKind::I64), - wasm::ValueType::make(wasm::ValueKind::I32) + auto tuple = wasm::ownvec::make( + wasm::ValType::make(wasm::ValKind::I32), + wasm::ValType::make(wasm::ValKind::I64), + wasm::ValType::make(wasm::ValKind::I64), + wasm::ValType::make(wasm::ValKind::I32) ); auto callback_type = wasm::FuncType::make(tuple.deep_copy(), tuple.deep_copy()); @@ -84,10 +84,10 @@ void run() { // Call. std::cout << "Calling export..." << std::endl; - auto args = wasm::vec::make( - wasm::Value::i32(1), wasm::Value::i64(2), wasm::Value::i64(3), wasm::Value::i32(4) + auto args = wasm::vec::make( + wasm::Val::i32(1), wasm::Val::i64(2), wasm::Val::i64(3), wasm::Val::i32(4) ); - auto results = wasm::vec::make_uninitialized(4); + auto results = wasm::vec::make_uninitialized(4); if (wasm::own trap = run_func->call(args, results)) { std::cout << "> Error calling function! " << trap->message().get() << std::endl; exit(1); diff --git a/lib/c-api/tests/wasm-c-api/example/reflect.c b/lib/c-api/tests/wasm-c-api/example/reflect.c index 8dc80ef571a..d4383185ff0 100644 --- a/lib/c-api/tests/wasm-c-api/example/reflect.c +++ b/lib/c-api/tests/wasm-c-api/example/reflect.c @@ -87,8 +87,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/serialize.c b/lib/c-api/tests/wasm-c-api/example/serialize.c index 2e28300e9d9..8ea1a379af6 100644 --- a/lib/c-api/tests/wasm-c-api/example/serialize.c +++ b/lib/c-api/tests/wasm-c-api/example/serialize.c @@ -9,7 +9,7 @@ // A function to be called from Wasm code. own wasm_trap_t* hello_callback( - wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results + const wasm_val_vec_t* args, wasm_val_vec_t* results ) { printf("Calling back...\n"); printf("> Hello World!\n"); @@ -22,8 +22,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/start.c b/lib/c-api/tests/wasm-c-api/example/start.c index 9f2e96f4acd..f60c03c6468 100644 --- a/lib/c-api/tests/wasm-c-api/example/start.c +++ b/lib/c-api/tests/wasm-c-api/example/start.c @@ -23,8 +23,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/table.c b/lib/c-api/tests/wasm-c-api/example/table.c index 5aa5b96d929..5e91a34a45d 100644 --- a/lib/c-api/tests/wasm-c-api/example/table.c +++ b/lib/c-api/tests/wasm-c-api/example/table.c @@ -9,7 +9,7 @@ // A function to be called from Wasm code. own wasm_trap_t* neg_callback( - wasm_context_ref_mut_t* ctx_mut, const wasm_val_vec_t* args, wasm_val_vec_t* results + const wasm_val_vec_t* args, wasm_val_vec_t* results ) { printf("Calling back...\n"); results->data[0].kind = WASM_I32; @@ -78,8 +78,6 @@ int main(int argc, const char* argv[]) { printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); // Load binary. printf("Loading binary...\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/table.cc b/lib/c-api/tests/wasm-c-api/example/table.cc index d937ec9038a..9ddf1d902bf 100644 --- a/lib/c-api/tests/wasm-c-api/example/table.cc +++ b/lib/c-api/tests/wasm-c-api/example/table.cc @@ -9,10 +9,10 @@ // A function to be called from Wasm code. auto neg_callback( - const wasm::vec& args, wasm::vec& results + const wasm::vec& args, wasm::vec& results ) -> wasm::own { std::cout << "Calling back..." << std::endl; - results[0] = wasm::Value(-args[0].i32()); + results[0] = wasm::Val(-args[0].i32()); return nullptr; } @@ -49,10 +49,10 @@ void check(bool success) { } auto call( - const wasm::Func* func, wasm::Value&& arg1, wasm::Value&& arg2 -) -> wasm::Value { - auto args = wasm::vec::make(std::move(arg1), std::move(arg2)); - auto results = wasm::vec::make_uninitialized(1); + const wasm::Func* func, wasm::Val&& arg1, wasm::Val&& arg2 +) -> wasm::Val { + auto args = wasm::vec::make(std::move(arg1), std::move(arg2)); + auto results = wasm::vec::make_uninitialized(1); if (func->call(args, results)) { std::cout << "> Error on result, expected return" << std::endl; exit(1); @@ -60,9 +60,9 @@ auto call( return results[0].copy(); } -void check_trap(const wasm::Func* func, wasm::Value&& arg1, wasm::Value&& arg2) { - auto args = wasm::vec::make(std::move(arg1), std::move(arg2)); - auto results = wasm::vec::make_uninitialized(1); +void check_trap(const wasm::Func* func, wasm::Val&& arg1, wasm::Val&& arg2) { + auto args = wasm::vec::make(std::move(arg1), std::move(arg2)); + auto results = wasm::vec::make_uninitialized(1); if (! func->call(args, results)) { std::cout << "> Error on result, expected trap" << std::endl; exit(1); @@ -119,8 +119,8 @@ void run() { // Create external function. std::cout << "Creating callback..." << std::endl; auto neg_type = wasm::FuncType::make( - wasm::ownvec::make(wasm::ValueType::make(wasm::ValueKind::I32)), - wasm::ownvec::make(wasm::ValueType::make(wasm::ValueKind::I32)) + wasm::ownvec::make(wasm::ValType::make(wasm::ValKind::I32)), + wasm::ownvec::make(wasm::ValType::make(wasm::ValKind::I32)) ); auto h = wasm::Func::make(store, neg_type.get(), neg_callback); @@ -132,9 +132,9 @@ void run() { check(table->size(), 2u); check(table->get(0) == nullptr); check(table->get(1) != nullptr); - check_trap(call_indirect, wasm::Value::i32(0), wasm::Value::i32(0)); - check(call(call_indirect, wasm::Value::i32(7), wasm::Value::i32(1)).i32(), 7); - check_trap(call_indirect, wasm::Value::i32(0), wasm::Value::i32(2)); + check_trap(call_indirect, wasm::Val::i32(0), wasm::Val::i32(0)); + check(call(call_indirect, wasm::Val::i32(7), wasm::Val::i32(1)).i32(), 7); + check_trap(call_indirect, wasm::Val::i32(0), wasm::Val::i32(2)); // Mutate table. std::cout << "Mutating table..." << std::endl; @@ -143,9 +143,9 @@ void run() { check(! table->set(2, f)); check(table->get(0) != nullptr); check(table->get(1) == nullptr); - check(call(call_indirect, wasm::Value::i32(7), wasm::Value::i32(0)).i32(), 666); - check_trap(call_indirect, wasm::Value::i32(0), wasm::Value::i32(1)); - check_trap(call_indirect, wasm::Value::i32(0), wasm::Value::i32(2)); + check(call(call_indirect, wasm::Val::i32(7), wasm::Val::i32(0)).i32(), 666); + check_trap(call_indirect, wasm::Val::i32(0), wasm::Val::i32(1)); + check_trap(call_indirect, wasm::Val::i32(0), wasm::Val::i32(2)); // Grow table. std::cout << "Growing table..." << std::endl; @@ -157,10 +157,10 @@ void run() { check(table->get(2) != nullptr); check(table->get(3) != nullptr); check(table->get(4) == nullptr); - check(call(call_indirect, wasm::Value::i32(5), wasm::Value::i32(2)).i32(), 5); - check(call(call_indirect, wasm::Value::i32(6), wasm::Value::i32(3)).i32(), -6); - check_trap(call_indirect, wasm::Value::i32(0), wasm::Value::i32(4)); - check_trap(call_indirect, wasm::Value::i32(0), wasm::Value::i32(5)); + check(call(call_indirect, wasm::Val::i32(5), wasm::Val::i32(2)).i32(), 5); + check(call(call_indirect, wasm::Val::i32(6), wasm::Val::i32(3)).i32(), -6); + check_trap(call_indirect, wasm::Val::i32(0), wasm::Val::i32(4)); + check_trap(call_indirect, wasm::Val::i32(0), wasm::Val::i32(5)); check(table->grow(2, f)); check(table->size(), 7u); @@ -175,7 +175,7 @@ void run() { // TODO(wasm+): Once Wasm allows multiple tables, turn this into import. std::cout << "Creating stand-alone table..." << std::endl; auto tabletype = wasm::TableType::make( - wasm::ValueType::make(wasm::ValueKind::FUNCREF), wasm::Limits(5, 5)); + wasm::ValType::make(wasm::ValKind::FUNCREF), wasm::Limits(5, 5)); auto table2 = wasm::Table::make(store, tabletype.get()); check(table2->size() == 5); check(! table2->grow(1)); diff --git a/lib/c-api/tests/wasm-c-api/example/threads.c b/lib/c-api/tests/wasm-c-api/example/threads.c index ec68abb8930..d70bd1ae55c 100644 --- a/lib/c-api/tests/wasm-c-api/example/threads.c +++ b/lib/c-api/tests/wasm-c-api/example/threads.c @@ -13,7 +13,7 @@ const int N_THREADS = 10; const int N_REPS = 3; // A function to be called from Wasm code. -own wasm_trap_t* callback(wasm_context_ref_mut_t* ctx, const wasm_val_vec_t* args, wasm_val_vec_t* results) { +own wasm_trap_t* callback(const wasm_val_vec_t* args, wasm_val_vec_t* results) { assert(args->data[0].kind == WASM_I32); printf("> Thread %d running\n", args->data[0].of.i32); return NULL; @@ -31,8 +31,6 @@ void* run(void* args_abs) { // Rereate store and module. own wasm_store_t* store = wasm_store_new(args->engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); own wasm_module_t* module = wasm_module_obtain(store, args->module); // Run the example N times. @@ -121,9 +119,6 @@ int main(int argc, const char *argv[]) { // Compile and share. own wasm_store_t* store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); - own wasm_module_t* module = wasm_module_new(store, &binary); if (!module) { printf("> Error compiling module!\n"); diff --git a/lib/c-api/tests/wasm-c-api/example/threads.cc b/lib/c-api/tests/wasm-c-api/example/threads.cc index cde5f3a3676..e130717a0cf 100644 --- a/lib/c-api/tests/wasm-c-api/example/threads.cc +++ b/lib/c-api/tests/wasm-c-api/example/threads.cc @@ -10,9 +10,9 @@ const int N_REPS = 3; // A function to be called from Wasm code. auto callback( - void* env, const wasm::vec& args, wasm::vec& results + void* env, const wasm::vec& args, wasm::vec& results ) -> wasm::own { - assert(args[0].kind() == wasm::ValueKind::I32); + assert(args[0].kind() == wasm::ValKind::I32); std::lock_guard lock(*reinterpret_cast(env)); std::cout << "Thread " << args[0].i32() << " running..." << std::endl; std::cout.flush(); @@ -42,15 +42,15 @@ void run( // Create imports. auto func_type = wasm::FuncType::make( - wasm::ownvec::make(wasm::ValueType::make(wasm::ValueKind::I32)), - wasm::ownvec::make() + wasm::ownvec::make(wasm::ValType::make(wasm::ValKind::I32)), + wasm::ownvec::make() ); auto func = wasm::Func::make(store, func_type.get(), callback, mutex); auto global_type = wasm::GlobalType::make( - wasm::ValueType::make(wasm::ValueKind::I32), wasm::Mutability::CONST); + wasm::ValType::make(wasm::ValKind::I32), wasm::Mutability::CONST); auto global = wasm::Global::make( - store, global_type.get(), wasm::Value::i32(i)); + store, global_type.get(), wasm::Val::i32(i)); // Instantiate. auto imports = wasm::vec::make(func.get(), global.get()); @@ -71,7 +71,7 @@ void run( auto run_func = exports[0]->func(); // Call. - auto empty = wasm::vec::make(); + auto empty = wasm::vec::make(); run_func->call(empty, empty); } } diff --git a/lib/c-api/tests/wasm-c-api/example/trap.c b/lib/c-api/tests/wasm-c-api/example/trap.c index 974100d9818..e53e29b233b 100644 --- a/lib/c-api/tests/wasm-c-api/example/trap.c +++ b/lib/c-api/tests/wasm-c-api/example/trap.c @@ -7,16 +7,14 @@ #define own -wasm_store_t* store = NULL; - // A function to be called from Wasm code. own wasm_trap_t* fail_callback( - wasm_context_ref_mut_t* ctx, const wasm_val_vec_t* args, wasm_val_vec_t* results + void* env, const wasm_val_vec_t* args, wasm_val_vec_t* results ) { printf("Calling back...\n"); own wasm_name_t message; wasm_name_new_from_string_nt(&message, "callback abort"); - own wasm_trap_t* trap = wasm_trap_new(store, &message); + own wasm_trap_t* trap = wasm_trap_new((wasm_store_t*)env, &message); wasm_name_delete(&message); return trap; } @@ -36,9 +34,7 @@ int main(int argc, const char* argv[]) { // Initialize. printf("Initializing...\n"); wasm_engine_t* engine = wasm_engine_new(); - store = wasm_store_new(engine); - wasm_context_t* ctx = wasm_context_new(store, 0); - wasm_store_context_set(store, ctx); + wasm_store_t* store = wasm_store_new(engine); // Load binary. printf("Loading binary...\n"); @@ -73,7 +69,12 @@ int main(int argc, const char* argv[]) { own wasm_functype_t* fail_type = wasm_functype_new_0_1(wasm_valtype_new_i32()); own wasm_func_t* fail_func = - wasm_func_new(store, fail_type, fail_callback); + wasm_func_new_with_env(store, fail_type, fail_callback, store, NULL); + + if (!fail_func) { + printf("> Error compiling fail_func!\n"); + return 1; + } wasm_functype_delete(fail_type); diff --git a/lib/c-api/tests/wasm-c-api/include/wasm.h b/lib/c-api/tests/wasm-c-api/include/wasm.h index 3c163d890f5..78c9e727586 100644 --- a/lib/c-api/tests/wasm-c-api/include/wasm.h +++ b/lib/c-api/tests/wasm-c-api/include/wasm.h @@ -143,15 +143,6 @@ WASM_DECLARE_OWN(store) WASM_API_EXTERN own wasm_store_t* wasm_store_new(wasm_engine_t*); -// Context - -WASM_DECLARE_OWN(context) -WASM_DECLARE_OWN(context_ref_mut) - -WASM_API_EXTERN own void wasm_store_context_set(own wasm_store_t*, own wasm_context_t*); -WASM_API_EXTERN own void wasm_store_data_set(own wasm_store_t*, own void*); -WASM_API_EXTERN own void* wasm_store_data_get(own wasm_store_t*); - /////////////////////////////////////////////////////////////////////////////// // Type Representations @@ -422,10 +413,15 @@ WASM_API_EXTERN own wasm_module_t* wasm_module_deserialize(wasm_store_t*, const WASM_DECLARE_REF(func) typedef own wasm_trap_t* (*wasm_func_callback_t)( - wasm_context_ref_mut_t*, const wasm_val_vec_t* args, own wasm_val_vec_t* results); + const wasm_val_vec_t* args, own wasm_val_vec_t* results); +typedef own wasm_trap_t* (*wasm_func_callback_with_env_t)( + void* env, const wasm_val_vec_t* args, wasm_val_vec_t* results); WASM_API_EXTERN own wasm_func_t* wasm_func_new( wasm_store_t*, const wasm_functype_t*, wasm_func_callback_t); +WASM_API_EXTERN own wasm_func_t* wasm_func_new_with_env( + wasm_store_t*, const wasm_functype_t* type, wasm_func_callback_with_env_t, + void* env, void (*finalizer)(void*)); WASM_API_EXTERN own wasm_functype_t* wasm_func_type(const wasm_func_t*); WASM_API_EXTERN size_t wasm_func_param_arity(const wasm_func_t*); diff --git a/lib/cli/src/commands/run.rs b/lib/cli/src/commands/run.rs index fc9a29fb374..c93a2829a88 100644 --- a/lib/cli/src/commands/run.rs +++ b/lib/cli/src/commands/run.rs @@ -7,7 +7,7 @@ use crate::warning; use anyhow::{anyhow, Context, Result}; use std::path::PathBuf; use std::str::FromStr; -use wasmer::Context as WasmerContext; +use wasmer::FunctionEnv; use wasmer::*; #[cfg(feature = "cache")] use wasmer_cache::{Cache, FileSystemCache, Hash}; @@ -97,21 +97,17 @@ impl Run { }) } - fn inner_run(&self, mut ctx: WasmerContext, instance: Instance) -> Result<()> { - let module = self.get_module()?; + fn inner_module_run(&self, mut store: Store, instance: Instance) -> Result<()> { // If this module exports an _initialize function, run that first. if let Ok(initialize) = instance.exports.get_function("_initialize") { initialize - .call(&mut ctx, &[]) + .call(&mut store, &[]) .with_context(|| "failed to run _initialize function")?; } // Do we want to invoke a function? if let Some(ref invoke) = self.invoke { - let imports = imports! {}; - let instance = Instance::new(&mut ctx, &module, &imports)?; - let result = - self.invoke_function(&mut ctx.as_context_mut(), &instance, invoke, &self.args)?; + let result = self.invoke_function(&mut store, &instance, invoke, &self.args)?; println!( "{}", result @@ -122,7 +118,7 @@ impl Run { ); } else { let start: Function = self.try_find_function(&instance, "_start", &[])?; - let result = start.call(&mut ctx, &[]); + let result = start.call(&mut store, &[]); #[cfg(feature = "wasi")] self.wasi.handle_result(result)?; #[cfg(not(feature = "wasi"))] @@ -133,7 +129,7 @@ impl Run { } fn inner_execute(&self) -> Result<()> { - let module = self.get_module()?; + let (mut store, module) = self.get_store_module()?; #[cfg(feature = "emscripten")] { use wasmer_emscripten::{ @@ -146,18 +142,14 @@ impl Run { bail!("--invoke is not supported with emscripten modules"); } // create an EmEnv with default global - let mut ctx = WasmerContext::new(module.store(), EmEnv::new()); - let mut emscripten_globals = EmscriptenGlobals::new(ctx.as_context_mut(), &module) + let env = FunctionEnv::new(&mut store, EmEnv::new()); + let mut emscripten_globals = EmscriptenGlobals::new(&mut store, &env, &module) .map_err(|e| anyhow!("{}", e))?; - ctx.data_mut() + env.as_mut(&mut store) .set_data(&emscripten_globals.data, Default::default()); let import_object = - generate_emscripten_env(&mut ctx.as_context_mut(), &mut emscripten_globals); - let mut instance = match Instance::new( - &mut ctx.as_context_mut(), - &module, - &import_object, - ) { + generate_emscripten_env(&mut store, &env, &mut emscripten_globals); + let mut instance = match Instance::new(&mut store, &module, &import_object) { Ok(instance) => instance, Err(e) => { let err: Result<(), _> = Err(e); @@ -173,7 +165,7 @@ impl Run { run_emscripten_instance( &mut instance, - ctx.as_context_mut(), + env.into_mut(&mut store), &mut emscripten_globals, if let Some(cn) = &self.command_name { cn @@ -222,37 +214,35 @@ impl Run { .map(|f| f.to_string_lossy().to_string()) }) .unwrap_or_default(); - let (ctx, instance) = self + let (_ctx, instance) = self .wasi - .instantiate(&module, program_name, self.args.clone()) + .instantiate(&mut store, &module, program_name, self.args.clone()) .with_context(|| "failed to instantiate WASI module")?; - self.inner_run(ctx, instance) + self.inner_module_run(store, instance) } // not WASI _ => { - let mut ctx = WasmerContext::new(module.store(), ()); - let instance = Instance::new(&mut ctx, &module, &imports! {})?; - self.inner_run(ctx, instance) + let instance = Instance::new(&mut store, &module, &imports! {})?; + self.inner_module_run(store, instance) } } }; #[cfg(not(feature = "wasi"))] let ret = { - let mut ctx = WasmerContext::new(module.store(), ()); - let instance = Instance::new(&mut ctx, &module, &imports! {})?; + let instance = Instance::new(&mut store, &module, &imports! {})?; self.inner_run(ctx, instance) }; ret } - fn get_module(&self) -> Result { + fn get_store_module(&self) -> Result<(Store, Module)> { let contents = std::fs::read(self.path.clone())?; if wasmer_compiler::UniversalArtifact::is_deserializable(&contents) { let engine = wasmer_compiler::Universal::headless().engine(); let store = Store::new_with_engine(&engine); let module = unsafe { Module::deserialize_from_file(&store, &self.path)? }; - return Ok(module); + return Ok((store, module)); } let (store, compiler_type) = self.store.get_store()?; #[cfg(feature = "cache")] @@ -273,7 +263,7 @@ impl Run { // We set the name outside the cache, to make sure we dont cache the name module.set_name(&self.path.file_name().unwrap_or_default().to_string_lossy()); - Ok(module) + Ok((store, module)) } #[cfg(feature = "cache")] @@ -378,7 +368,7 @@ impl Run { fn invoke_function( &self, - ctx: &mut impl AsContextMut, + ctx: &mut impl AsStoreMut, instance: &Instance, invoke: &str, args: &[String], diff --git a/lib/cli/src/commands/run/wasi.rs b/lib/cli/src/commands/run/wasi.rs index 5cf8287edde..3a0121a2069 100644 --- a/lib/cli/src/commands/run/wasi.rs +++ b/lib/cli/src/commands/run/wasi.rs @@ -2,7 +2,7 @@ use crate::utils::{parse_envvar, parse_mapdir}; use anyhow::Result; use std::collections::BTreeSet; use std::path::PathBuf; -use wasmer::{AsContextMut, Context, Instance, Module, RuntimeError, Value}; +use wasmer::{AsStoreMut, FunctionEnv, Instance, Module, RuntimeError, Value}; use wasmer_wasi::{ get_wasi_versions, import_object_for_all_wasi_versions, is_wasix_module, WasiEnv, WasiError, WasiState, WasiVersion, @@ -78,10 +78,11 @@ impl Wasi { /// Helper function for instantiating a module with Wasi imports for the `Run` command. pub fn instantiate( &self, + store: &mut impl AsStoreMut, module: &Module, program_name: String, args: Vec, - ) -> Result<(Context, Instance)> { + ) -> Result<(FunctionEnv, Instance)> { let args = args.iter().cloned().map(|arg| arg.into_bytes()); let mut wasi_state_builder = WasiState::new(program_name); @@ -99,17 +100,16 @@ impl Wasi { } } - let wasi_env = wasi_state_builder.finalize()?; - wasi_env.state.fs.is_wasix.store( + let wasi_env = wasi_state_builder.finalize(store)?; + wasi_env.env.as_mut(store).state.fs.is_wasix.store( is_wasix_module(module), std::sync::atomic::Ordering::Release, ); - let mut ctx = Context::new(module.store(), wasi_env); - let import_object = import_object_for_all_wasi_versions(&mut ctx.as_context_mut()); - let instance = Instance::new(&mut ctx, module, &import_object)?; + let import_object = import_object_for_all_wasi_versions(store, &wasi_env.env); + let instance = Instance::new(store, module, &import_object)?; let memory = instance.exports.get_memory("memory")?; - ctx.data_mut().set_memory(memory.clone()); - Ok((ctx, instance)) + wasi_env.data_mut(store).set_memory(memory.clone()); + Ok((wasi_env.env, instance)) } /// Helper function for handling the result of a Wasi _start function. diff --git a/lib/cli/src/commands/wast.rs b/lib/cli/src/commands/wast.rs index 5dd0352c4d1..580bdb205e1 100644 --- a/lib/cli/src/commands/wast.rs +++ b/lib/cli/src/commands/wast.rs @@ -3,7 +3,6 @@ use crate::store::StoreOptions; use anyhow::{Context, Result}; use std::path::PathBuf; use structopt::StructOpt; -use wasmer::Context as WasmerContext; use wasmer_wast::Wast as WastSpectest; #[derive(Debug, StructOpt)] @@ -29,8 +28,7 @@ impl Wast { } fn inner_execute(&self) -> Result<()> { let (store, _compiler_name) = self.store.get_store()?; - let ctx = WasmerContext::new(&store, ()); - let mut wast = WastSpectest::new_with_spectest(ctx); + let mut wast = WastSpectest::new_with_spectest(store); wast.fail_fast = self.fail_fast; wast.run_file(&self.path).with_context(|| "tests failed")?; eprintln!("Wast tests succeeded for `{}`.", self.path.display()); diff --git a/lib/compiler-cranelift/README.md b/lib/compiler-cranelift/README.md index 716e9ddea47..f05e66420d3 100644 --- a/lib/compiler-cranelift/README.md +++ b/lib/compiler-cranelift/README.md @@ -10,7 +10,7 @@ use wasmer_compiler_cranelift::Cranelift; let compiler = Cranelift::new(); // Put it into an engine and add it to the store -let store = Store::new_with_engine(&Universal::new(compiler).engine()); +let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); ``` *Note: you can find a [full working example using Cranelift compiler diff --git a/lib/compiler-cranelift/src/translator/func_environ.rs b/lib/compiler-cranelift/src/translator/func_environ.rs index dbd83d00217..0ca674269ca 100644 --- a/lib/compiler-cranelift/src/translator/func_environ.rs +++ b/lib/compiler-cranelift/src/translator/func_environ.rs @@ -2,7 +2,7 @@ // Attributions: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md //! All the runtime support necessary for the wasm to cranelift translation is formalized by the -//! traits `FunctionEnvironment`. +//! traits `FunctionEnvMutironment`. use super::func_state::FuncTranslationState; use super::translation_utils::reference_type; @@ -449,7 +449,7 @@ pub trait FuncEnvironment: TargetEnvironment { Ok(()) } - /// Optional callback for the `FunctionEnvironment` performing this translation to maintain + /// Optional callback for the `FunctionEnvMutironment` performing this translation to maintain /// internal state or prepare custom state for the operator to translate fn before_translate_operator( &mut self, @@ -460,7 +460,7 @@ pub trait FuncEnvironment: TargetEnvironment { Ok(()) } - /// Optional callback for the `FunctionEnvironment` performing this translation to maintain + /// Optional callback for the `FunctionEnvMutironment` performing this translation to maintain /// internal state or finalize custom state for the operator that was translated fn after_translate_operator( &mut self, diff --git a/lib/compiler-llvm/README.md b/lib/compiler-llvm/README.md index 782784b0b11..664b80e090e 100644 --- a/lib/compiler-llvm/README.md +++ b/lib/compiler-llvm/README.md @@ -10,7 +10,7 @@ use wasmer_compiler_llvm::LLVM; let compiler = LLVM::new(); // Put it into an engine and add it to the store -let store = Store::new_with_engine(&Universal::new(compiler).engine()); +let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); ``` *Note: you can find a [full working example using LLVM compiler here][example].* diff --git a/lib/compiler-llvm/src/translator/intrinsics.rs b/lib/compiler-llvm/src/translator/intrinsics.rs index 9b3c6ba8be3..7a1d1ebb9ba 100644 --- a/lib/compiler-llvm/src/translator/intrinsics.rs +++ b/lib/compiler-llvm/src/translator/intrinsics.rs @@ -1686,7 +1686,7 @@ pub fn tbaa_label<'ctx>( let context = module.get_context(); - // TODO: ContextRef can't return us the lifetime from module through Deref. + // TODO: StoreRef can't return us the lifetime from module through Deref. // This could be fixed once generic_associated_types is stable. let context = { let context2 = &*context; diff --git a/lib/compiler-singlepass/README.md b/lib/compiler-singlepass/README.md index 56226839c84..84ff8430b81 100644 --- a/lib/compiler-singlepass/README.md +++ b/lib/compiler-singlepass/README.md @@ -10,7 +10,7 @@ use wasmer_compiler_singlepass::Singlepass; let compiler = Singlepass::new(); // Put it into an engine and add it to the store -let store = Store::new_with_engine(&Universal::new(compiler).engine()); +let mut store = Store::new_with_engine(&Universal::new(compiler).engine()); ``` *Note: you can find a [full working example using Singlepass compiler diff --git a/lib/compiler/src/engine/artifact.rs b/lib/compiler/src/engine/artifact.rs index 00d3924f585..f557bc5ca64 100644 --- a/lib/compiler/src/engine/artifact.rs +++ b/lib/compiler/src/engine/artifact.rs @@ -4,7 +4,7 @@ use crate::{ArtifactCreate, Upcastable}; use wasmer_types::entity::BoxedSlice; use wasmer_types::{DataInitializer, FunctionIndex, LocalFunctionIndex, SignatureIndex}; use wasmer_vm::{ - ContextObjects, FunctionBodyPtr, InstanceAllocator, InstanceHandle, TrapHandler, VMExtern, + FunctionBodyPtr, InstanceAllocator, InstanceHandle, StoreObjects, TrapHandlerFn, VMExtern, VMSharedSignatureIndex, VMTrampoline, }; @@ -51,7 +51,7 @@ pub trait Artifact: Send + Sync + Upcastable + ArtifactCreate { &self, tunables: &dyn Tunables, imports: &[VMExtern], - context: &mut ContextObjects, + context: &mut StoreObjects, ) -> Result { // Validate the CPU features this module was compiled with against the // host CPU features. @@ -128,7 +128,7 @@ pub trait Artifact: Send + Sync + Upcastable + ArtifactCreate { /// See [`InstanceHandle::finish_instantiation`]. unsafe fn finish_instantiation( &self, - trap_handler: &(dyn TrapHandler + 'static), + trap_handler: Option<*const TrapHandlerFn<'static>>, handle: &mut InstanceHandle, ) -> Result<(), InstantiationError> { let data_initializers = self diff --git a/lib/compiler/src/engine/resolver.rs b/lib/compiler/src/engine/resolver.rs index 3835766aa19..a97044adb8b 100644 --- a/lib/compiler/src/engine/resolver.rs +++ b/lib/compiler/src/engine/resolver.rs @@ -8,7 +8,7 @@ use wasmer_types::{ }; use wasmer_vm::{ - ContextObjects, FunctionBodyPtr, Imports, MemoryStyle, TableStyle, VMExtern, VMFunctionBody, + FunctionBodyPtr, Imports, MemoryStyle, StoreObjects, TableStyle, VMExtern, VMFunctionBody, VMFunctionImport, VMFunctionKind, VMGlobalImport, VMMemoryImport, VMTableImport, }; @@ -35,7 +35,7 @@ fn get_extern_from_import(module: &ModuleInfo, import_index: &ImportIndex) -> Ex } /// Get an `ExternType` given an export (and Engine signatures in case is a function). -fn get_extern_type(context: &ContextObjects, extern_: &VMExtern) -> ExternType { +fn get_extern_type(context: &StoreObjects, extern_: &VMExtern) -> ExternType { match extern_ { VMExtern::Function(f) => ExternType::Function(f.get(context).signature.clone()), VMExtern::Table(t) => ExternType::Table(*t.get(context).ty()), @@ -54,7 +54,7 @@ fn get_extern_type(context: &ContextObjects, extern_: &VMExtern) -> ExternType { pub fn resolve_imports( module: &ModuleInfo, imports: &[VMExtern], - context: &ContextObjects, + context: &StoreObjects, finished_dynamic_function_trampolines: &BoxedSlice, memory_styles: &PrimaryMap, _table_styles: &PrimaryMap, diff --git a/lib/compiler/src/engine/tunables.rs b/lib/compiler/src/engine/tunables.rs index 43d7c1a2d39..207ceec9dca 100644 --- a/lib/compiler/src/engine/tunables.rs +++ b/lib/compiler/src/engine/tunables.rs @@ -5,7 +5,7 @@ use wasmer_types::{ GlobalType, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, MemoryType, ModuleInfo, TableIndex, TableType, }; -use wasmer_vm::{ContextObjects, InternalContextHandle, MemoryError}; +use wasmer_vm::{InternalStoreHandle, MemoryError, StoreObjects}; use wasmer_vm::{MemoryStyle, TableStyle}; use wasmer_vm::{VMGlobal, VMMemory, VMTable}; use wasmer_vm::{VMMemoryDefinition, VMTableDefinition}; @@ -62,11 +62,11 @@ pub trait Tunables { /// - `memory_definition_locations` must point to a valid locations in VM memory. unsafe fn create_memories( &self, - context: &mut ContextObjects, + context: &mut StoreObjects, module: &ModuleInfo, memory_styles: &PrimaryMap, memory_definition_locations: &[NonNull], - ) -> Result>, LinkError> { + ) -> Result>, LinkError> { let num_imports = module.num_imported_memories; let mut memories: PrimaryMap = PrimaryMap::with_capacity(module.memories.len() - num_imports); @@ -79,7 +79,7 @@ pub trait Tunables { let mi = MemoryIndex::new(index); let ty = &module.memories[mi]; let style = &memory_styles[mi]; - memories.push(InternalContextHandle::new( + memories.push(InternalStoreHandle::new( context, self.create_vm_memory(ty, style, *mdl) .map_err(|e| LinkError::Resource(format!("Failed to create memory: {}", e)))?, @@ -95,11 +95,11 @@ pub trait Tunables { /// To be done unsafe fn create_tables( &self, - context: &mut ContextObjects, + context: &mut StoreObjects, module: &ModuleInfo, table_styles: &PrimaryMap, table_definition_locations: &[NonNull], - ) -> Result>, LinkError> { + ) -> Result>, LinkError> { let num_imports = module.num_imported_tables; let mut tables: PrimaryMap = PrimaryMap::with_capacity(module.tables.len() - num_imports); @@ -112,7 +112,7 @@ pub trait Tunables { let ti = TableIndex::new(index); let ty = &module.tables[ti]; let style = &table_styles[ti]; - tables.push(InternalContextHandle::new( + tables.push(InternalStoreHandle::new( context, self.create_vm_table(ty, style, *tdl) .map_err(LinkError::Resource)?, @@ -125,14 +125,14 @@ pub trait Tunables { /// with initializers applied. fn create_globals( &self, - context: &mut ContextObjects, + context: &mut StoreObjects, module: &ModuleInfo, - ) -> Result>, LinkError> { + ) -> Result>, LinkError> { let num_imports = module.num_imported_globals; let mut vmctx_globals = PrimaryMap::with_capacity(module.globals.len() - num_imports); for &global_type in module.globals.values().skip(num_imports) { - vmctx_globals.push(InternalContextHandle::new( + vmctx_globals.push(InternalStoreHandle::new( context, self.create_global(global_type) .map_err(LinkError::Resource)?, diff --git a/lib/emscripten/src/bitwise.rs b/lib/emscripten/src/bitwise.rs index be6ee40be01..d912fda7daa 100644 --- a/lib/emscripten/src/bitwise.rs +++ b/lib/emscripten/src/bitwise.rs @@ -1,9 +1,9 @@ use crate::emscripten_target; use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; ///emscripten: _llvm_bswap_i64 -pub fn _llvm_bswap_i64(ctx: ContextMut<'_, EmEnv>, _low: i32, high: i32) -> i32 { +pub fn _llvm_bswap_i64(ctx: FunctionEnvMut, _low: i32, high: i32) -> i32 { debug!("emscripten::_llvm_bswap_i64"); emscripten_target::setTempRet0(ctx, _low.swap_bytes()); high.swap_bytes() diff --git a/lib/emscripten/src/emscripten_target.rs b/lib/emscripten/src/emscripten_target.rs index 4bf614c40f1..736313d638d 100644 --- a/lib/emscripten/src/emscripten_target.rs +++ b/lib/emscripten/src/emscripten_target.rs @@ -4,33 +4,33 @@ use crate::env::{get_emscripten_data, get_emscripten_funcs}; use crate::EmEnv; #[cfg(target_os = "linux")] use libc::getdtablesize; -use wasmer::{AsContextMut, ContextMut}; +use wasmer::FunctionEnvMut; -pub fn asm_const_i(_ctx: ContextMut<'_, EmEnv>, _val: i32) -> i32 { +pub fn asm_const_i(_ctx: FunctionEnvMut, _val: i32) -> i32 { debug!("emscripten::asm_const_i: {}", _val); 0 } -pub fn exit_with_live_runtime(_ctx: ContextMut<'_, EmEnv>) { +pub fn exit_with_live_runtime(_ctx: FunctionEnvMut) { debug!("emscripten::exit_with_live_runtime"); } -pub fn setTempRet0(ctx: ContextMut<'_, EmEnv>, val: i32) { +pub fn setTempRet0(ctx: FunctionEnvMut, val: i32) { trace!("emscripten::setTempRet0: {}", val); get_emscripten_data(&ctx).as_mut().unwrap().temp_ret_0 = val; } -pub fn getTempRet0(ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn getTempRet0(ctx: FunctionEnvMut) -> i32 { trace!("emscripten::getTempRet0"); get_emscripten_data(&ctx).as_ref().unwrap().temp_ret_0 } -pub fn _alarm(_ctx: ContextMut<'_, EmEnv>, _seconds: u32) -> i32 { +pub fn _alarm(_ctx: FunctionEnvMut, _seconds: u32) -> i32 { debug!("emscripten::_alarm({})", _seconds); 0 } -pub fn _atexit(_ctx: ContextMut<'_, EmEnv>, _func: i32) -> i32 { +pub fn _atexit(_ctx: FunctionEnvMut, _func: i32) -> i32 { debug!("emscripten::_atexit"); // TODO: implement atexit properly // __ATEXIT__.unshift({ @@ -39,38 +39,38 @@ pub fn _atexit(_ctx: ContextMut<'_, EmEnv>, _func: i32) -> i32 { // }); 0 } -pub fn __Unwind_Backtrace(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn __Unwind_Backtrace(_ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::__Unwind_Backtrace"); 0 } -pub fn __Unwind_FindEnclosingFunction(_ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn __Unwind_FindEnclosingFunction(_ctx: FunctionEnvMut, _a: i32) -> i32 { debug!("emscripten::__Unwind_FindEnclosingFunction"); 0 } -pub fn __Unwind_GetIPInfo(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn __Unwind_GetIPInfo(_ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::__Unwind_GetIPInfo"); 0 } -pub fn ___cxa_find_matching_catch_2(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn ___cxa_find_matching_catch_2(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::___cxa_find_matching_catch_2"); 0 } -pub fn ___cxa_find_matching_catch_3(_ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn ___cxa_find_matching_catch_3(_ctx: FunctionEnvMut, _a: i32) -> i32 { debug!("emscripten::___cxa_find_matching_catch_3"); 0 } -pub fn ___cxa_free_exception(_ctx: ContextMut<'_, EmEnv>, _a: i32) { +pub fn ___cxa_free_exception(_ctx: FunctionEnvMut, _a: i32) { debug!("emscripten::___cxa_free_exception"); } -pub fn ___resumeException(_ctx: ContextMut<'_, EmEnv>, _a: i32) { +pub fn ___resumeException(_ctx: FunctionEnvMut, _a: i32) { debug!("emscripten::___resumeException"); } -pub fn _dladdr(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _dladdr(_ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::_dladdr"); 0 } pub fn ___gxx_personality_v0( - _ctx: ContextMut<'_, EmEnv>, + _ctx: FunctionEnvMut, _a: i32, _b: i32, _c: i32, @@ -83,25 +83,25 @@ pub fn ___gxx_personality_v0( } #[cfg(target_os = "linux")] -pub fn _getdtablesize(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn _getdtablesize(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::getdtablesize"); unsafe { getdtablesize() } } #[cfg(not(target_os = "linux"))] -pub fn _getdtablesize(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn _getdtablesize(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::getdtablesize"); -1 } -pub fn _gethostbyaddr(_ctx: ContextMut<'_, EmEnv>, _addr: i32, _addrlen: i32, _atype: i32) -> i32 { +pub fn _gethostbyaddr(_ctx: FunctionEnvMut, _addr: i32, _addrlen: i32, _atype: i32) -> i32 { debug!("emscripten::gethostbyaddr"); 0 } -pub fn _gethostbyname(_ctx: ContextMut<'_, EmEnv>, _name: i32) -> i32 { +pub fn _gethostbyname(_ctx: FunctionEnvMut, _name: i32) -> i32 { debug!("emscripten::gethostbyname_r"); 0 } pub fn _gethostbyname_r( - _ctx: ContextMut<'_, EmEnv>, + _ctx: FunctionEnvMut, _name: i32, _ret: i32, _buf: i32, @@ -113,13 +113,13 @@ pub fn _gethostbyname_r( 0 } // NOTE: php.js has proper impl; libc has proper impl for linux -pub fn _getloadavg(_ctx: ContextMut<'_, EmEnv>, _loadavg: i32, _nelem: i32) -> i32 { +pub fn _getloadavg(_ctx: FunctionEnvMut, _loadavg: i32, _nelem: i32) -> i32 { debug!("emscripten::getloadavg"); 0 } #[allow(clippy::too_many_arguments)] pub fn _getnameinfo( - _ctx: ContextMut<'_, EmEnv>, + _ctx: FunctionEnvMut, _addr: i32, _addrlen: i32, _host: i32, @@ -142,7 +142,7 @@ pub fn _getnameinfo( macro_rules! invoke { ($ctx: ident, $name:ident, $name_ref:ident, $( $arg:ident ),*) => {{ let funcs = get_emscripten_funcs(&$ctx).clone(); - let sp = funcs.stack_save_ref().expect("stack_save is None").call(&mut $ctx.as_context_mut()).expect("stack_save call failed"); + let sp = funcs.stack_save_ref().expect("stack_save is None").call(&mut $ctx).expect("stack_save call failed"); let call = funcs.$name_ref().expect(concat!("Dynamic call is None: ", stringify!($name))).clone(); match call.call(&mut $ctx, $($arg),*) { Ok(v) => v, @@ -183,50 +183,50 @@ macro_rules! invoke_no_stack_save { let funcs = get_emscripten_funcs(&$ctx).clone(); let call = funcs.$name_ref().expect(concat!(stringify!($name), " is set to None")).clone(); - call.call(&mut $ctx.as_context_mut(), $($arg),*).unwrap() + call.call(&mut $ctx, $($arg),*).unwrap() }} } // Invoke functions -pub fn invoke_i(mut ctx: ContextMut<'_, EmEnv>, index: i32) -> i32 { +pub fn invoke_i(mut ctx: FunctionEnvMut, index: i32) -> i32 { debug!("emscripten::invoke_i"); invoke!(ctx, dyn_call_i, dyn_call_i_ref, index) } -pub fn invoke_ii(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32) -> i32 { +pub fn invoke_ii(mut ctx: FunctionEnvMut, index: i32, a1: i32) -> i32 { debug!("emscripten::invoke_ii"); invoke!(ctx, dyn_call_ii, dyn_call_ii_ref, index, a1) } -pub fn invoke_iii(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32) -> i32 { +pub fn invoke_iii(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32) -> i32 { debug!("emscripten::invoke_iii"); invoke!(ctx, dyn_call_iii, dyn_call_iii_ref, index, a1, a2) } -pub fn invoke_iiii(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: i32) -> i32 { +pub fn invoke_iiii(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: i32) -> i32 { debug!("emscripten::invoke_iiii"); invoke!(ctx, dyn_call_iiii, dyn_call_iiii_ref, index, a1, a2, a3) } -pub fn invoke_iifi(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: f64, a3: i32) -> i32 { +pub fn invoke_iifi(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: f64, a3: i32) -> i32 { debug!("emscripten::invoke_iifi"); invoke!(ctx, dyn_call_iifi, dyn_call_iifi_ref, index, a1, a2, a3) } -pub fn invoke_v(mut ctx: ContextMut<'_, EmEnv>, index: i32) { +pub fn invoke_v(mut ctx: FunctionEnvMut, index: i32) { debug!("emscripten::invoke_v"); invoke_no_return!(ctx, dyn_call_v, dyn_call_v_ref, index); } -pub fn invoke_vi(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32) { +pub fn invoke_vi(mut ctx: FunctionEnvMut, index: i32, a1: i32) { debug!("emscripten::invoke_vi"); invoke_no_return!(ctx, dyn_call_vi, dyn_call_vi_ref, index, a1); } -pub fn invoke_vii(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32) { +pub fn invoke_vii(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32) { debug!("emscripten::invoke_vii"); invoke_no_return!(ctx, dyn_call_vii, dyn_call_vii_ref, index, a1, a2); } -pub fn invoke_viii(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: i32) { +pub fn invoke_viii(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: i32) { debug!("emscripten::invoke_viii"); invoke_no_return!(ctx, dyn_call_viii, dyn_call_viii_ref, index, a1, a2, a3); } pub fn invoke_viiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -245,12 +245,12 @@ pub fn invoke_viiii( a4 ); } -pub fn invoke_dii(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32) -> f64 { +pub fn invoke_dii(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32) -> f64 { debug!("emscripten::invoke_dii"); invoke!(ctx, dyn_call_dii, dyn_call_dii_ref, index, a1, a2) } pub fn invoke_diiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -270,7 +270,7 @@ pub fn invoke_diiii( ) } pub fn invoke_iiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -290,7 +290,7 @@ pub fn invoke_iiiii( ) } pub fn invoke_iiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -313,7 +313,7 @@ pub fn invoke_iiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -338,7 +338,7 @@ pub fn invoke_iiiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -365,7 +365,7 @@ pub fn invoke_iiiiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -394,7 +394,7 @@ pub fn invoke_iiiiiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -425,7 +425,7 @@ pub fn invoke_iiiiiiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_iiiiiiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -456,12 +456,12 @@ pub fn invoke_iiiiiiiiiii( a10 ) } -pub fn invoke_vd(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: f64) { +pub fn invoke_vd(mut ctx: FunctionEnvMut, index: i32, a1: f64) { debug!("emscripten::invoke_vd"); invoke_no_return!(ctx, dyn_call_vd, dyn_call_vd_ref, index, a1) } pub fn invoke_viiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -484,7 +484,7 @@ pub fn invoke_viiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_viiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -509,7 +509,7 @@ pub fn invoke_viiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_viiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -536,7 +536,7 @@ pub fn invoke_viiiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_viiiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -565,7 +565,7 @@ pub fn invoke_viiiiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_viiiiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -596,7 +596,7 @@ pub fn invoke_viiiiiiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_viiiiiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -628,18 +628,18 @@ pub fn invoke_viiiiiiiiii( ) } -pub fn invoke_iij(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: i32) -> i32 { +pub fn invoke_iij(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: i32) -> i32 { debug!("emscripten::invoke_iij"); invoke!(ctx, dyn_call_iij, dyn_call_iij_ref, index, a1, a2, a3) } -pub fn invoke_iji(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: i32) -> i32 { +pub fn invoke_iji(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: i32) -> i32 { debug!("emscripten::invoke_iji"); invoke!(ctx, dyn_call_iji, dyn_call_iji_ref, index, a1, a2, a3) } pub fn invoke_iiji( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -652,7 +652,7 @@ pub fn invoke_iiji( #[allow(clippy::too_many_arguments)] pub fn invoke_iiijj( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -675,25 +675,25 @@ pub fn invoke_iiijj( a6 ) } -pub fn invoke_j(mut ctx: ContextMut<'_, EmEnv>, index: i32) -> i32 { +pub fn invoke_j(mut ctx: FunctionEnvMut, index: i32) -> i32 { debug!("emscripten::invoke_j"); invoke_no_stack_save!(ctx, dyn_call_j, dyn_call_j_ref, index) } -pub fn invoke_ji(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32) -> i32 { +pub fn invoke_ji(mut ctx: FunctionEnvMut, index: i32, a1: i32) -> i32 { debug!("emscripten::invoke_ji"); invoke_no_stack_save!(ctx, dyn_call_ji, dyn_call_ji_ref, index, a1) } -pub fn invoke_jii(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32) -> i32 { +pub fn invoke_jii(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32) -> i32 { debug!("emscripten::invoke_jii"); invoke_no_stack_save!(ctx, dyn_call_jii, dyn_call_jii_ref, index, a1, a2) } -pub fn invoke_jij(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: i32) -> i32 { +pub fn invoke_jij(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: i32) -> i32 { debug!("emscripten::invoke_jij"); invoke_no_stack_save!(ctx, dyn_call_jij, dyn_call_jij_ref, index, a1, a2, a3) } pub fn invoke_jjj( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -704,7 +704,7 @@ pub fn invoke_jjj( invoke_no_stack_save!(ctx, dyn_call_jjj, dyn_call_jjj_ref, index, a1, a2, a3, a4) } pub fn invoke_viiij( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -727,7 +727,7 @@ pub fn invoke_viiij( } #[allow(clippy::too_many_arguments)] pub fn invoke_viiijiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -758,7 +758,7 @@ pub fn invoke_viiijiiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_viiijiiiiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -791,12 +791,12 @@ pub fn invoke_viiijiiiiii( a11 ) } -pub fn invoke_viij(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: i32, a4: i32) { +pub fn invoke_viij(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: i32, a4: i32) { debug!("emscripten::invoke_viij"); invoke_no_stack_save!(ctx, dyn_call_viij, dyn_call_viij_ref, index, a1, a2, a3, a4) } pub fn invoke_viiji( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -819,7 +819,7 @@ pub fn invoke_viiji( } #[allow(clippy::too_many_arguments)] pub fn invoke_viijiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -846,7 +846,7 @@ pub fn invoke_viijiii( } #[allow(clippy::too_many_arguments)] pub fn invoke_viijj( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -869,12 +869,12 @@ pub fn invoke_viijj( a6 ) } -pub fn invoke_vj(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32) { +pub fn invoke_vj(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32) { debug!("emscripten::invoke_vj"); invoke_no_stack_save!(ctx, dyn_call_vj, dyn_call_vj_ref, index, a1, a2) } pub fn invoke_vjji( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -895,17 +895,17 @@ pub fn invoke_vjji( a5 ) } -pub fn invoke_vij(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: i32) { +pub fn invoke_vij(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: i32) { debug!("emscripten::invoke_vij"); invoke_no_stack_save!(ctx, dyn_call_vij, dyn_call_vij_ref, index, a1, a2, a3) } -pub fn invoke_viji(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: i32, a4: i32) { +pub fn invoke_viji(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: i32, a4: i32) { debug!("emscripten::invoke_viji"); invoke_no_stack_save!(ctx, dyn_call_viji, dyn_call_viji_ref, index, a1, a2, a3, a4) } #[allow(clippy::too_many_arguments)] pub fn invoke_vijiii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -929,7 +929,7 @@ pub fn invoke_vijiii( ) } pub fn invoke_vijj( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -950,16 +950,16 @@ pub fn invoke_vijj( a5 ) } -pub fn invoke_vidd(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: f64, a3: f64) { +pub fn invoke_vidd(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: f64, a3: f64) { debug!("emscripten::invoke_viid"); invoke_no_return!(ctx, dyn_call_vidd, dyn_call_vidd_ref, index, a1, a2, a3); } -pub fn invoke_viid(mut ctx: ContextMut<'_, EmEnv>, index: i32, a1: i32, a2: i32, a3: f64) { +pub fn invoke_viid(mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, a3: f64) { debug!("emscripten::invoke_viid"); invoke_no_return!(ctx, dyn_call_viid, dyn_call_viid_ref, index, a1, a2, a3); } pub fn invoke_viidii( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, @@ -982,7 +982,7 @@ pub fn invoke_viidii( } #[allow(clippy::too_many_arguments)] pub fn invoke_viidddddddd( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, index: i32, a1: i32, a2: i32, diff --git a/lib/emscripten/src/env/mod.rs b/lib/emscripten/src/env/mod.rs index fa7c1ab1edc..645f989f3b3 100644 --- a/lib/emscripten/src/env/mod.rs +++ b/lib/emscripten/src/env/mod.rs @@ -19,65 +19,68 @@ use std::sync::MutexGuard; use crate::EmEnv; use wasmer::ValueType; -use wasmer::{AsContextMut, ContextMut, WasmPtr}; +use wasmer::{FunctionEnvMut, WasmPtr}; -pub fn call_malloc(mut ctx: ContextMut<'_, EmEnv>, size: u32) -> u32 { - let malloc_ref = get_emscripten_funcs(&ctx).malloc_ref().unwrap().clone(); - malloc_ref.call(&mut ctx.as_context_mut(), size).unwrap() +pub fn call_malloc(mut ctx: &mut FunctionEnvMut, size: u32) -> u32 { + let malloc_ref = get_emscripten_funcs(ctx).malloc_ref().unwrap().clone(); + malloc_ref.call(&mut ctx, size).unwrap() } #[warn(dead_code)] -pub fn call_malloc_with_cast(ctx: ContextMut<'_, EmEnv>, size: u32) -> WasmPtr { +pub fn call_malloc_with_cast(ctx: &mut FunctionEnvMut, size: u32) -> WasmPtr { WasmPtr::new(call_malloc(ctx, size)) } -pub fn call_memalign(mut ctx: ContextMut<'_, EmEnv>, alignment: u32, size: u32) -> u32 { - let memalign_ref = get_emscripten_funcs(&ctx).memalign_ref().unwrap().clone(); +pub fn call_memalign(mut ctx: &mut FunctionEnvMut, alignment: u32, size: u32) -> u32 { + let memalign_ref = get_emscripten_funcs(ctx).memalign_ref().unwrap().clone(); memalign_ref.call(&mut ctx, alignment, size).unwrap() } -pub fn call_memset(mut ctx: ContextMut<'_, EmEnv>, pointer: u32, value: u32, size: u32) -> u32 { - let memset_ref = get_emscripten_funcs(&ctx).memset_ref().unwrap().clone(); - memset_ref - .call(&mut ctx.as_context_mut(), pointer, value, size) - .unwrap() +pub fn call_memset( + mut ctx: &mut FunctionEnvMut, + pointer: u32, + value: u32, + size: u32, +) -> u32 { + let memset_ref = get_emscripten_funcs(ctx).memset_ref().unwrap().clone(); + memset_ref.call(&mut ctx, pointer, value, size).unwrap() } pub(crate) fn get_emscripten_data<'a>( - ctx: &'a ContextMut<'_, EmEnv>, + ctx: &'a FunctionEnvMut, ) -> MutexGuard<'a, Option> { ctx.data().data.lock().unwrap() } pub(crate) fn get_emscripten_funcs<'a>( - ctx: &'a ContextMut<'_, EmEnv>, + ctx: &'a FunctionEnvMut, ) -> MutexGuard<'a, EmscriptenFunctions> { ctx.data().funcs.lock().unwrap() } -pub fn _getpagesize(_ctx: ContextMut<'_, EmEnv>) -> u32 { +pub fn _getpagesize(_ctx: FunctionEnvMut) -> u32 { debug!("emscripten::_getpagesize"); 16384 } -pub fn _times(ctx: ContextMut<'_, EmEnv>, buffer: u32) -> u32 { +pub fn _times(mut ctx: FunctionEnvMut, buffer: u32) -> u32 { if buffer != 0 { - call_memset(ctx, buffer, 0, 16); + call_memset(&mut ctx, buffer, 0, 16); } 0 } #[allow(clippy::cast_ptr_alignment)] -pub fn ___build_environment(mut ctx: ContextMut<'_, EmEnv>, environ: c_int) { +pub fn ___build_environment(mut ctx: FunctionEnvMut, environ: c_int) { debug!("emscripten::___build_environment {}", environ); const MAX_ENV_VALUES: u32 = 64; const TOTAL_ENV_SIZE: u32 = 1024; let environment = emscripten_memory_pointer!(ctx, ctx.data().memory(0), environ) as *mut c_int; let (mut pool_offset, env_ptr, mut pool_ptr) = unsafe { let (pool_offset, _pool_slice): (u32, &mut [u8]) = - allocate_on_stack(&mut ctx.as_context_mut(), TOTAL_ENV_SIZE as u32); + allocate_on_stack(&mut ctx, TOTAL_ENV_SIZE as u32); let (env_offset, _env_slice): (u32, &mut [u8]) = - allocate_on_stack(&mut ctx.as_context_mut(), (MAX_ENV_VALUES * 4) as u32); + allocate_on_stack(&mut ctx, (MAX_ENV_VALUES * 4) as u32); let env_ptr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), env_offset) as *mut c_int; let pool_ptr = @@ -122,13 +125,13 @@ pub fn ___build_environment(mut ctx: ContextMut<'_, EmEnv>, environ: c_int) { } } -pub fn ___assert_fail(_ctx: ContextMut<'_, EmEnv>, _a: c_int, _b: c_int, _c: c_int, _d: c_int) { +pub fn ___assert_fail(_ctx: FunctionEnvMut, _a: c_int, _b: c_int, _c: c_int, _d: c_int) { debug!("emscripten::___assert_fail {} {} {} {}", _a, _b, _c, _d); // TODO: Implement like emscripten expects regarding memory/page size // TODO raise an error } -pub fn _pathconf(ctx: ContextMut<'_, EmEnv>, path_addr: c_int, name: c_int) -> c_int { +pub fn _pathconf(ctx: FunctionEnvMut, path_addr: c_int, name: c_int) -> c_int { debug!( "emscripten::_pathconf {} {} - UNIMPLEMENTED", path_addr, name @@ -149,7 +152,7 @@ pub fn _pathconf(ctx: ContextMut<'_, EmEnv>, path_addr: c_int, name: c_int) -> c } } -pub fn _fpathconf(_ctx: ContextMut<'_, EmEnv>, _fildes: c_int, name: c_int) -> c_int { +pub fn _fpathconf(_ctx: FunctionEnvMut, _fildes: c_int, name: c_int) -> c_int { debug!("emscripten::_fpathconf {} {}", _fildes, name); match name { 0 => 32000, diff --git a/lib/emscripten/src/env/unix/mod.rs b/lib/emscripten/src/env/unix/mod.rs index 9ef7e59a024..66d6c64434e 100644 --- a/lib/emscripten/src/env/unix/mod.rs +++ b/lib/emscripten/src/env/unix/mod.rs @@ -10,11 +10,11 @@ use std::os::raw::c_char; use crate::env::{call_malloc, call_malloc_with_cast, EmAddrInfo, EmSockAddr}; use crate::utils::{copy_cstr_into_wasm, copy_terminated_array_of_cstrs}; use crate::EmEnv; -use wasmer::{AsContextMut, ContextMut, WasmPtr}; +use wasmer::{FunctionEnvMut, WasmPtr}; // #[no_mangle] /// emscripten: _getenv // (name: *const char) -> *const c_char; -pub fn _getenv(ctx: ContextMut<'_, EmEnv>, name: i32) -> u32 { +pub fn _getenv(mut ctx: FunctionEnvMut, name: i32) -> u32 { debug!("emscripten::_getenv"); let name_addr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), name) as *const c_char; @@ -26,11 +26,11 @@ pub fn _getenv(ctx: ContextMut<'_, EmEnv>, name: i32) -> u32 { return 0; } - unsafe { copy_cstr_into_wasm(ctx, c_str) } + unsafe { copy_cstr_into_wasm(&mut ctx, c_str) } } /// emscripten: _setenv // (name: *const char, name: *const value, overwrite: int); -pub fn _setenv(ctx: ContextMut<'_, EmEnv>, name: c_int, value: c_int, overwrite: c_int) -> c_int { +pub fn _setenv(ctx: FunctionEnvMut, name: c_int, value: c_int, overwrite: c_int) -> c_int { debug!("emscripten::_setenv"); let name_addr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), name) as *const c_char; @@ -43,7 +43,7 @@ pub fn _setenv(ctx: ContextMut<'_, EmEnv>, name: c_int, value: c_int, overwrite: } /// emscripten: _putenv // (name: *const char); -pub fn _putenv(ctx: ContextMut<'_, EmEnv>, name: c_int) -> c_int { +pub fn _putenv(ctx: FunctionEnvMut, name: c_int) -> c_int { debug!("emscripten::_putenv"); let name_addr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), name) as *const c_char; @@ -54,7 +54,7 @@ pub fn _putenv(ctx: ContextMut<'_, EmEnv>, name: c_int) -> c_int { } /// emscripten: _unsetenv // (name: *const char); -pub fn _unsetenv(ctx: ContextMut<'_, EmEnv>, name: c_int) -> c_int { +pub fn _unsetenv(ctx: FunctionEnvMut, name: c_int) -> c_int { debug!("emscripten::_unsetenv"); let name_addr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), name) as *const c_char; @@ -65,7 +65,7 @@ pub fn _unsetenv(ctx: ContextMut<'_, EmEnv>, name: c_int) -> c_int { } #[allow(clippy::cast_ptr_alignment)] -pub fn _getpwnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { +pub fn _getpwnam(mut ctx: FunctionEnvMut, name_ptr: c_int) -> c_int { debug!("emscripten::_getpwnam {}", name_ptr); #[cfg(feature = "debug")] let _ = name_ptr; @@ -89,18 +89,16 @@ pub fn _getpwnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { unsafe { let passwd = &*libc_getpwnam(name.as_ptr()); - let passwd_struct_offset = - call_malloc(ctx.as_context_mut(), mem::size_of::() as _); + let passwd_struct_offset = call_malloc(&mut ctx, mem::size_of::() as _); let memory = ctx.data().memory(0); let passwd_struct_ptr = emscripten_memory_pointer!(ctx, memory, passwd_struct_offset) as *mut GuestPasswd; - (*passwd_struct_ptr).pw_name = copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_name); - (*passwd_struct_ptr).pw_passwd = - copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_passwd); - (*passwd_struct_ptr).pw_gecos = copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_gecos); - (*passwd_struct_ptr).pw_dir = copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_dir); - (*passwd_struct_ptr).pw_shell = copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_shell); + (*passwd_struct_ptr).pw_name = copy_cstr_into_wasm(&mut ctx, passwd.pw_name); + (*passwd_struct_ptr).pw_passwd = copy_cstr_into_wasm(&mut ctx, passwd.pw_passwd); + (*passwd_struct_ptr).pw_gecos = copy_cstr_into_wasm(&mut ctx, passwd.pw_gecos); + (*passwd_struct_ptr).pw_dir = copy_cstr_into_wasm(&mut ctx, passwd.pw_dir); + (*passwd_struct_ptr).pw_shell = copy_cstr_into_wasm(&mut ctx, passwd.pw_shell); (*passwd_struct_ptr).pw_uid = passwd.pw_uid; (*passwd_struct_ptr).pw_gid = passwd.pw_gid; @@ -109,7 +107,7 @@ pub fn _getpwnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { } #[allow(clippy::cast_ptr_alignment)] -pub fn _getgrnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { +pub fn _getgrnam(mut ctx: FunctionEnvMut, name_ptr: c_int) -> c_int { debug!("emscripten::_getgrnam {}", name_ptr); #[repr(C)] @@ -128,14 +126,13 @@ pub fn _getgrnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { unsafe { let group = &*libc_getgrnam(name.as_ptr()); - let group_struct_offset = - call_malloc(ctx.as_context_mut(), mem::size_of::() as _); + let group_struct_offset = call_malloc(&mut ctx, mem::size_of::() as _); let group_struct_ptr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), group_struct_offset) as *mut GuestGroup; - (*group_struct_ptr).gr_name = copy_cstr_into_wasm(ctx.as_context_mut(), group.gr_name); - (*group_struct_ptr).gr_passwd = copy_cstr_into_wasm(ctx.as_context_mut(), group.gr_passwd); + (*group_struct_ptr).gr_name = copy_cstr_into_wasm(&mut ctx, group.gr_name); + (*group_struct_ptr).gr_passwd = copy_cstr_into_wasm(&mut ctx, group.gr_passwd); (*group_struct_ptr).gr_gid = group.gr_gid; (*group_struct_ptr).gr_mem = copy_terminated_array_of_cstrs(ctx, group.gr_mem); @@ -143,20 +140,19 @@ pub fn _getgrnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { } } -pub fn _sysconf(_ctx: ContextMut<'_, EmEnv>, name: c_int) -> i32 { +pub fn _sysconf(_ctx: FunctionEnvMut, name: c_int) -> i32 { debug!("emscripten::_sysconf {}", name); // TODO: Implement like emscripten expects regarding memory/page size unsafe { sysconf(name) as i32 } // TODO review i64 } // this may be a memory leak, probably not though because emscripten does the same thing -pub fn _gai_strerror(mut ctx: ContextMut<'_, EmEnv>, ecode: i32) -> i32 { +pub fn _gai_strerror(mut ctx: FunctionEnvMut, ecode: i32) -> i32 { debug!("emscripten::_gai_strerror({})", ecode); let cstr = unsafe { std::ffi::CStr::from_ptr(libc::gai_strerror(ecode)) }; let bytes = cstr.to_bytes_with_nul(); - let string_on_guest: WasmPtr = - call_malloc_with_cast(ctx.as_context_mut(), bytes.len() as _); + let string_on_guest: WasmPtr = call_malloc_with_cast(&mut ctx, bytes.len() as _); let memory = ctx.data().memory(0); let writer = string_on_guest @@ -170,7 +166,7 @@ pub fn _gai_strerror(mut ctx: ContextMut<'_, EmEnv>, ecode: i32) -> i32 { } pub fn _getaddrinfo( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, node_ptr: WasmPtr, service_str_ptr: WasmPtr, hints_ptr: WasmPtr, @@ -244,7 +240,7 @@ pub fn _getaddrinfo( while !current_host_node.is_null() { let current_guest_node_ptr: WasmPtr = - call_malloc_with_cast(ctx.as_context_mut(), std::mem::size_of::() as _); + call_malloc_with_cast(&mut ctx, std::mem::size_of::() as _); if head_of_list.is_none() { head_of_list = Some(current_guest_node_ptr); } @@ -264,7 +260,7 @@ pub fn _getaddrinfo( let guest_sockaddr_ptr = { let host_sockaddr_ptr = (*current_host_node).ai_addr; let guest_sockaddr_ptr: WasmPtr = - call_malloc_with_cast(ctx.as_context_mut(), host_addrlen as _); + call_malloc_with_cast(&mut ctx, host_addrlen as _); let derefed_guest_sockaddr = guest_sockaddr_ptr.deref(&ctx, &memory); let mut gs = derefed_guest_sockaddr.read().unwrap(); @@ -283,7 +279,7 @@ pub fn _getaddrinfo( let canonname_bytes = canonname_cstr.to_bytes_with_nul(); let str_size = canonname_bytes.len(); let guest_canonname: WasmPtr = - call_malloc_with_cast(ctx.as_context_mut(), str_size as _); + call_malloc_with_cast(&mut ctx, str_size as _); let guest_canonname_writer = guest_canonname.slice(&ctx, &memory, str_size as _).unwrap(); diff --git a/lib/emscripten/src/env/windows/mod.rs b/lib/emscripten/src/env/windows/mod.rs index dce90272874..8b35528496c 100644 --- a/lib/emscripten/src/env/windows/mod.rs +++ b/lib/emscripten/src/env/windows/mod.rs @@ -8,7 +8,7 @@ use std::os::raw::c_char; use crate::env::{call_malloc, EmAddrInfo}; use crate::utils::{copy_cstr_into_wasm, read_string_from_wasm}; use crate::EmEnv; -use wasmer::{AsContextMut, ContextMut, WasmPtr}; +use wasmer::{FunctionEnvMut, WasmPtr}; extern "C" { #[link_name = "_putenv"] @@ -17,24 +17,24 @@ extern "C" { // #[no_mangle] /// emscripten: _getenv // (name: *const char) -> *const c_char; -pub fn _getenv(mut ctx: ContextMut<'_, EmEnv>, name: u32) -> u32 { +pub fn _getenv(mut ctx: FunctionEnvMut, name: u32) -> u32 { debug!("emscripten::_getenv"); let memory = ctx.data().memory(0); - let name_string = read_string_from_wasm(ctx.as_context_mut(), &memory, name); + let name_string = read_string_from_wasm(ctx.as_mut(), &memory, name); debug!("=> name({:?})", name_string); let c_str = unsafe { getenv(name_string.as_ptr() as *const libc::c_char) }; if c_str.is_null() { return 0; } - unsafe { copy_cstr_into_wasm(ctx, c_str as *const c_char) } + unsafe { copy_cstr_into_wasm(&mut ctx, c_str as *const c_char) } } /// emscripten: _setenv // (name: *const char, name: *const value, overwrite: int); -pub fn _setenv(mut ctx: ContextMut<'_, EmEnv>, name: u32, value: u32, _overwrite: u32) -> c_int { +pub fn _setenv(mut ctx: FunctionEnvMut, name: u32, value: u32, _overwrite: u32) -> c_int { debug!("emscripten::_setenv"); let memory = ctx.data().memory(0); // setenv does not exist on windows, so we hack it with _putenv - let name = read_string_from_wasm(ctx.as_context_mut(), &memory, name); + let name = read_string_from_wasm(ctx.as_mut(), &memory, name); let value = read_string_from_wasm(ctx, &memory, value); let putenv_string = format!("{}={}", name, value); let putenv_cstring = CString::new(putenv_string).unwrap(); @@ -45,7 +45,7 @@ pub fn _setenv(mut ctx: ContextMut<'_, EmEnv>, name: u32, value: u32, _overwrite } /// emscripten: _putenv // (name: *const char); -pub fn _putenv(ctx: ContextMut<'_, EmEnv>, name: c_int) -> c_int { +pub fn _putenv(ctx: FunctionEnvMut, name: c_int) -> c_int { debug!("emscripten::_putenv"); let memory = ctx.data().memory(0); let name_addr = emscripten_memory_pointer!(ctx, &memory, name) as *const c_char; @@ -56,7 +56,7 @@ pub fn _putenv(ctx: ContextMut<'_, EmEnv>, name: c_int) -> c_int { } /// emscripten: _unsetenv // (name: *const char); -pub fn _unsetenv(ctx: ContextMut<'_, EmEnv>, name: u32) -> c_int { +pub fn _unsetenv(ctx: FunctionEnvMut, name: u32) -> c_int { debug!("emscripten::_unsetenv"); let memory = ctx.data().memory(0); let name = read_string_from_wasm(ctx, &memory, name); @@ -69,7 +69,7 @@ pub fn _unsetenv(ctx: ContextMut<'_, EmEnv>, name: u32) -> c_int { } #[allow(clippy::cast_ptr_alignment)] -pub fn _getpwnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { +pub fn _getpwnam(mut ctx: FunctionEnvMut, name_ptr: c_int) -> c_int { debug!("emscripten::_getpwnam {}", name_ptr); #[cfg(not(feature = "debug"))] let _ = name_ptr; @@ -88,8 +88,7 @@ pub fn _getpwnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { // stub this in windows as it is not valid unsafe { - let passwd_struct_offset = - call_malloc(ctx.as_context_mut(), mem::size_of::() as _); + let passwd_struct_offset = call_malloc(&mut ctx, mem::size_of::() as _); let passwd_struct_ptr = emscripten_memory_pointer!(ctx, memory, passwd_struct_offset) as *mut GuestPasswd; (*passwd_struct_ptr).pw_name = 0; @@ -105,7 +104,7 @@ pub fn _getpwnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { } #[allow(clippy::cast_ptr_alignment)] -pub fn _getgrnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { +pub fn _getgrnam(mut ctx: FunctionEnvMut, name_ptr: c_int) -> c_int { debug!("emscripten::_getgrnam {}", name_ptr); #[cfg(not(feature = "debug"))] let _ = name_ptr; @@ -121,8 +120,7 @@ pub fn _getgrnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { // stub the group struct as it is not supported on windows unsafe { - let group_struct_offset = - call_malloc(ctx.as_context_mut(), mem::size_of::() as _); + let group_struct_offset = call_malloc(&mut ctx, mem::size_of::() as _); let group_struct_ptr = emscripten_memory_pointer!(ctx, memory, group_struct_offset) as *mut GuestGroup; (*group_struct_ptr).gr_name = 0; @@ -133,7 +131,7 @@ pub fn _getgrnam(mut ctx: ContextMut<'_, EmEnv>, name_ptr: c_int) -> c_int { } } -pub fn _sysconf(_ctx: ContextMut<'_, EmEnv>, name: c_int) -> c_long { +pub fn _sysconf(_ctx: FunctionEnvMut, name: c_int) -> c_long { debug!("emscripten::_sysconf {}", name); #[cfg(not(feature = "debug"))] let _ = name; @@ -141,13 +139,13 @@ pub fn _sysconf(_ctx: ContextMut<'_, EmEnv>, name: c_int) -> c_long { 0 } -pub fn _gai_strerror(_ctx: ContextMut<'_, EmEnv>, _ecode: i32) -> i32 { +pub fn _gai_strerror(_ctx: FunctionEnvMut, _ecode: i32) -> i32 { debug!("emscripten::_gai_strerror({}) - stub", _ecode); -1 } pub fn _getaddrinfo( - _ctx: ContextMut<'_, EmEnv>, + _ctx: FunctionEnvMut, _node_ptr: WasmPtr, _service_str_ptr: WasmPtr, _hints_ptr: WasmPtr, diff --git a/lib/emscripten/src/errno.rs b/lib/emscripten/src/errno.rs index fb5681de7c8..99c78bf8c15 100644 --- a/lib/emscripten/src/errno.rs +++ b/lib/emscripten/src/errno.rs @@ -1,8 +1,8 @@ // use std::collections::HashMap; use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; -pub fn ___seterrno(mut _ctx: ContextMut<'_, EmEnv>, _value: i32) { +pub fn ___seterrno(mut _ctx: FunctionEnvMut, _value: i32) { debug!("emscripten::___seterrno {}", _value); // TODO: Incomplete impl eprintln!("failed to set errno!"); diff --git a/lib/emscripten/src/exception.rs b/lib/emscripten/src/exception.rs index c260f1a51d3..c3c8353d4af 100644 --- a/lib/emscripten/src/exception.rs +++ b/lib/emscripten/src/exception.rs @@ -1,57 +1,57 @@ use super::env; use super::process::_abort; use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; /// emscripten: ___cxa_allocate_exception -pub fn ___cxa_allocate_exception(ctx: ContextMut<'_, EmEnv>, size: u32) -> u32 { +pub fn ___cxa_allocate_exception(mut ctx: FunctionEnvMut, size: u32) -> u32 { debug!("emscripten::___cxa_allocate_exception"); - env::call_malloc(ctx, size as _) + env::call_malloc(&mut ctx.as_mut(), size as _) } -pub fn ___cxa_current_primary_exception(_ctx: ContextMut<'_, EmEnv>) -> u32 { +pub fn ___cxa_current_primary_exception(_ctx: FunctionEnvMut) -> u32 { debug!("emscripten::___cxa_current_primary_exception"); unimplemented!("emscripten::___cxa_current_primary_exception") } -pub fn ___cxa_decrement_exception_refcount(_ctx: ContextMut<'_, EmEnv>, _a: u32) { +pub fn ___cxa_decrement_exception_refcount(_ctx: FunctionEnvMut, _a: u32) { debug!("emscripten::___cxa_decrement_exception_refcount({})", _a); unimplemented!("emscripten::___cxa_decrement_exception_refcount({})", _a) } -pub fn ___cxa_increment_exception_refcount(_ctx: ContextMut<'_, EmEnv>, _a: u32) { +pub fn ___cxa_increment_exception_refcount(_ctx: FunctionEnvMut, _a: u32) { debug!("emscripten::___cxa_increment_exception_refcount({})", _a); unimplemented!("emscripten::___cxa_increment_exception_refcount({})", _a) } -pub fn ___cxa_rethrow_primary_exception(_ctx: ContextMut<'_, EmEnv>, _a: u32) { +pub fn ___cxa_rethrow_primary_exception(_ctx: FunctionEnvMut, _a: u32) { debug!("emscripten::___cxa_rethrow_primary_exception({})", _a); unimplemented!("emscripten::___cxa_rethrow_primary_exception({})", _a) } /// emscripten: ___cxa_throw /// TODO: We don't have support for exceptions yet -pub fn ___cxa_throw(ctx: ContextMut<'_, EmEnv>, _ptr: u32, _ty: u32, _destructor: u32) { +pub fn ___cxa_throw(ctx: FunctionEnvMut, _ptr: u32, _ty: u32, _destructor: u32) { debug!("emscripten::___cxa_throw"); eprintln!("Throwing exceptions not yet implemented: aborting!"); _abort(ctx); } -pub fn ___cxa_begin_catch(_ctx: ContextMut<'_, EmEnv>, _exception_object_ptr: u32) -> i32 { +pub fn ___cxa_begin_catch(_ctx: FunctionEnvMut, _exception_object_ptr: u32) -> i32 { debug!("emscripten::___cxa_begin_catch"); -1 } -pub fn ___cxa_end_catch(_ctx: ContextMut<'_, EmEnv>) { +pub fn ___cxa_end_catch(_ctx: FunctionEnvMut) { debug!("emscripten::___cxa_end_catch"); } -pub fn ___cxa_uncaught_exception(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn ___cxa_uncaught_exception(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::___cxa_uncaught_exception"); -1 } -pub fn ___cxa_pure_virtual(_ctx: ContextMut<'_, EmEnv>) { +pub fn ___cxa_pure_virtual(_ctx: FunctionEnvMut) { debug!("emscripten::___cxa_pure_virtual"); // ABORT = true panic!("Pure virtual function called!"); diff --git a/lib/emscripten/src/exec.rs b/lib/emscripten/src/exec.rs index 2b2485a224d..5a159debe3e 100644 --- a/lib/emscripten/src/exec.rs +++ b/lib/emscripten/src/exec.rs @@ -3,9 +3,9 @@ use crate::EmEnv; use libc::c_char; use libc::execvp as libc_execvp; use std::ffi::CString; -use wasmer::{ContextMut, WasmPtr}; +use wasmer::{FunctionEnvMut, WasmPtr}; -pub fn execvp(ctx: ContextMut<'_, EmEnv>, command_name_offset: u32, argv_offset: u32) -> i32 { +pub fn execvp(ctx: FunctionEnvMut, command_name_offset: u32, argv_offset: u32) -> i32 { // a single reference to re-use let emscripten_memory = ctx.data().memory(0); @@ -41,7 +41,7 @@ pub fn execvp(ctx: ContextMut<'_, EmEnv>, command_name_offset: u32, argv_offset: /// execl pub fn execl( - _ctx: ContextMut<'_, EmEnv>, + _ctx: FunctionEnvMut, _path_ptr: i32, _arg0_ptr: i32, _varargs: VarArgs, @@ -52,7 +52,7 @@ pub fn execl( /// execle pub fn execle( - _ctx: ContextMut<'_, EmEnv>, + _ctx: FunctionEnvMut, _path_ptr: i32, _arg0_ptr: i32, _varargs: VarArgs, diff --git a/lib/emscripten/src/exit.rs b/lib/emscripten/src/exit.rs index 8ef28cceb56..907bb66c3cb 100644 --- a/lib/emscripten/src/exit.rs +++ b/lib/emscripten/src/exit.rs @@ -1,8 +1,8 @@ use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; // __exit -pub fn exit(mut _ctx: ContextMut<'_, EmEnv>, value: i32) { +pub fn exit(mut _ctx: FunctionEnvMut, value: i32) { debug!("emscripten::exit {}", value); ::std::process::exit(value); } diff --git a/lib/emscripten/src/inet.rs b/lib/emscripten/src/inet.rs index b1a59a0feaf..863a6bc2c8a 100644 --- a/lib/emscripten/src/inet.rs +++ b/lib/emscripten/src/inet.rs @@ -1,7 +1,7 @@ use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; -pub fn addr(mut _ctx: ContextMut<'_, EmEnv>, _cp: i32) -> i32 { +pub fn addr(mut _ctx: FunctionEnvMut, _cp: i32) -> i32 { debug!("inet::addr({})", _cp); 0 } diff --git a/lib/emscripten/src/io/mod.rs b/lib/emscripten/src/io/mod.rs index 0971c10d716..7f5db3b27d2 100644 --- a/lib/emscripten/src/io/mod.rs +++ b/lib/emscripten/src/io/mod.rs @@ -11,22 +11,22 @@ pub use self::unix::*; pub use self::windows::*; use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; /// getprotobyname -pub fn getprotobyname(_ctx: ContextMut<'_, EmEnv>, _name_ptr: i32) -> i32 { +pub fn getprotobyname(_ctx: FunctionEnvMut, _name_ptr: i32) -> i32 { debug!("emscripten::getprotobyname"); unimplemented!("emscripten::getprotobyname") } /// getprotobynumber -pub fn getprotobynumber(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn getprotobynumber(_ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::getprotobynumber"); unimplemented!("emscripten::getprotobynumber") } /// sigdelset -pub fn sigdelset(ctx: ContextMut<'_, EmEnv>, set: i32, signum: i32) -> i32 { +pub fn sigdelset(ctx: FunctionEnvMut, set: i32, signum: i32) -> i32 { debug!("emscripten::sigdelset"); let memory = ctx.data().memory(0); #[allow(clippy::cast_ptr_alignment)] @@ -38,7 +38,7 @@ pub fn sigdelset(ctx: ContextMut<'_, EmEnv>, set: i32, signum: i32) -> i32 { } /// sigfillset -pub fn sigfillset(ctx: ContextMut<'_, EmEnv>, set: i32) -> i32 { +pub fn sigfillset(ctx: FunctionEnvMut, set: i32) -> i32 { debug!("emscripten::sigfillset"); let memory = ctx.data().memory(0); #[allow(clippy::cast_ptr_alignment)] @@ -52,13 +52,13 @@ pub fn sigfillset(ctx: ContextMut<'_, EmEnv>, set: i32) -> i32 { } /// tzset -pub fn tzset(_ctx: ContextMut<'_, EmEnv>) { +pub fn tzset(_ctx: FunctionEnvMut) { debug!("emscripten::tzset - stub"); //unimplemented!("emscripten::tzset - stub") } /// strptime -pub fn strptime(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32) -> i32 { +pub fn strptime(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32) -> i32 { debug!("emscripten::strptime"); unimplemented!("emscripten::strptime") } diff --git a/lib/emscripten/src/io/unix.rs b/lib/emscripten/src/io/unix.rs index 0e01580778b..996ebe68e44 100644 --- a/lib/emscripten/src/io/unix.rs +++ b/lib/emscripten/src/io/unix.rs @@ -4,15 +4,15 @@ use libc::{chroot as _chroot, getpwuid as _getpwuid, printf as _printf}; use std::mem; use crate::EmEnv; -use wasmer::{AsContextMut, ContextMut}; +use wasmer::FunctionEnvMut; /// putchar -pub fn putchar(_ctx: ContextMut<'_, EmEnv>, chr: i32) { +pub fn putchar(_ctx: FunctionEnvMut, chr: i32) { unsafe { libc::putchar(chr) }; } /// printf -pub fn printf(ctx: ContextMut<'_, EmEnv>, memory_offset: i32, extra: i32) -> i32 { +pub fn printf(ctx: FunctionEnvMut, memory_offset: i32, extra: i32) -> i32 { debug!("emscripten::printf {}, {}", memory_offset, extra); unsafe { let addr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), memory_offset) as _; @@ -21,7 +21,7 @@ pub fn printf(ctx: ContextMut<'_, EmEnv>, memory_offset: i32, extra: i32) -> i32 } /// chroot -pub fn chroot(ctx: ContextMut<'_, EmEnv>, name_ptr: i32) -> i32 { +pub fn chroot(ctx: FunctionEnvMut, name_ptr: i32) -> i32 { debug!("emscripten::chroot"); let name = emscripten_memory_pointer!(ctx, ctx.data().memory(0), name_ptr) as *const i8; unsafe { _chroot(name as *const _) } @@ -29,7 +29,7 @@ pub fn chroot(ctx: ContextMut<'_, EmEnv>, name_ptr: i32) -> i32 { /// getpwuid #[allow(clippy::cast_ptr_alignment)] -pub fn getpwuid(mut ctx: ContextMut<'_, EmEnv>, uid: i32) -> i32 { +pub fn getpwuid(mut ctx: FunctionEnvMut, uid: i32) -> i32 { debug!("emscripten::getpwuid {}", uid); #[repr(C)] @@ -45,8 +45,7 @@ pub fn getpwuid(mut ctx: ContextMut<'_, EmEnv>, uid: i32) -> i32 { unsafe { let passwd = &*_getpwuid(uid as _); - let passwd_struct_offset = - call_malloc(ctx.as_context_mut(), mem::size_of::() as _); + let passwd_struct_offset = call_malloc(&mut ctx, mem::size_of::() as _); let passwd_struct_ptr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), passwd_struct_offset) as *mut GuestPasswd; @@ -54,12 +53,11 @@ pub fn getpwuid(mut ctx: ContextMut<'_, EmEnv>, uid: i32) -> i32 { passwd_struct_ptr as usize % std::mem::align_of::(), 0 ); - (*passwd_struct_ptr).pw_name = copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_name); - (*passwd_struct_ptr).pw_passwd = - copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_passwd); - (*passwd_struct_ptr).pw_gecos = copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_gecos); - (*passwd_struct_ptr).pw_dir = copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_dir); - (*passwd_struct_ptr).pw_shell = copy_cstr_into_wasm(ctx.as_context_mut(), passwd.pw_shell); + (*passwd_struct_ptr).pw_name = copy_cstr_into_wasm(&mut ctx, passwd.pw_name); + (*passwd_struct_ptr).pw_passwd = copy_cstr_into_wasm(&mut ctx, passwd.pw_passwd); + (*passwd_struct_ptr).pw_gecos = copy_cstr_into_wasm(&mut ctx, passwd.pw_gecos); + (*passwd_struct_ptr).pw_dir = copy_cstr_into_wasm(&mut ctx, passwd.pw_dir); + (*passwd_struct_ptr).pw_shell = copy_cstr_into_wasm(&mut ctx, passwd.pw_shell); (*passwd_struct_ptr).pw_uid = passwd.pw_uid; (*passwd_struct_ptr).pw_gid = passwd.pw_gid; diff --git a/lib/emscripten/src/io/windows.rs b/lib/emscripten/src/io/windows.rs index 0bd1d8fbc31..c9b00e575d2 100644 --- a/lib/emscripten/src/io/windows.rs +++ b/lib/emscripten/src/io/windows.rs @@ -1,5 +1,5 @@ use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; // This may be problematic for msvc which uses inline functions for the printf family // this cfg_attr will try to link with the legacy lib that does not inline printf @@ -15,12 +15,12 @@ use wasmer::ContextMut; //} /// putchar -pub fn putchar(_ctx: ContextMut<'_, EmEnv>, chr: i32) { +pub fn putchar(_ctx: FunctionEnvMut, chr: i32) { unsafe { libc::putchar(chr) }; } /// printf -pub fn printf(_ctx: ContextMut<'_, EmEnv>, memory_offset: i32, extra: i32) -> i32 { +pub fn printf(_ctx: FunctionEnvMut, memory_offset: i32, extra: i32) -> i32 { debug!("emscripten::printf {}, {}", memory_offset, extra); #[cfg(not(feature = "debug"))] { @@ -35,13 +35,13 @@ pub fn printf(_ctx: ContextMut<'_, EmEnv>, memory_offset: i32, extra: i32) -> i3 } /// chroot -pub fn chroot(_ctx: ContextMut<'_, EmEnv>, _name_ptr: i32) -> i32 { +pub fn chroot(_ctx: FunctionEnvMut, _name_ptr: i32) -> i32 { debug!("emscripten::chroot"); unimplemented!("emscripten::chroot") } /// getpwuid -pub fn getpwuid(_ctx: ContextMut<'_, EmEnv>, _uid: i32) -> i32 { +pub fn getpwuid(_ctx: FunctionEnvMut, _uid: i32) -> i32 { debug!("emscripten::getpwuid"); unimplemented!("emscripten::getpwuid") } diff --git a/lib/emscripten/src/jmp.rs b/lib/emscripten/src/jmp.rs index 9ac824577cc..903a4720787 100644 --- a/lib/emscripten/src/jmp.rs +++ b/lib/emscripten/src/jmp.rs @@ -5,10 +5,10 @@ use libc::c_int; use crate::EmEnv; use std::error::Error; use std::fmt; -use wasmer::{AsContextMut, ContextMut}; +use wasmer::FunctionEnvMut; /// setjmp -pub fn __setjmp(ctx: ContextMut<'_, EmEnv>, _env_addr: u32) -> c_int { +pub fn __setjmp(ctx: FunctionEnvMut, _env_addr: u32) -> c_int { debug!("emscripten::__setjmp (setjmp)"); abort_with_message(ctx, "missing function: _setjmp"); unreachable!() @@ -31,7 +31,7 @@ pub fn __setjmp(ctx: ContextMut<'_, EmEnv>, _env_addr: u32) -> c_int { /// longjmp #[allow(unreachable_code)] -pub fn __longjmp(ctx: ContextMut<'_, EmEnv>, _env_addr: u32, _val: c_int) { +pub fn __longjmp(ctx: FunctionEnvMut, _env_addr: u32, _val: c_int) { debug!("emscripten::__longjmp (longmp)"); abort_with_message(ctx, "missing function: _longjmp"); // unsafe { @@ -59,7 +59,7 @@ impl Error for LongJumpRet {} // This function differs from the js implementation, it should return Result<(), &'static str> #[allow(unreachable_code)] pub fn _longjmp( - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, env_addr: i32, val: c_int, ) -> Result<(), LongJumpRet> { @@ -69,7 +69,7 @@ pub fn _longjmp( .expect("set_threw is None") .clone(); threw - .call(&mut ctx.as_context_mut(), env_addr, val) + .call(&mut ctx, env_addr, val) .expect("set_threw failed to call"); Err(LongJumpRet) } diff --git a/lib/emscripten/src/lib.rs b/lib/emscripten/src/lib.rs index edc36d170f3..6f840b1703d 100644 --- a/lib/emscripten/src/lib.rs +++ b/lib/emscripten/src/lib.rs @@ -23,9 +23,9 @@ use std::f64; use std::path::PathBuf; use std::sync::{Arc, Mutex, RwLock}; use wasmer::{ - imports, namespace, AsContextMut, ContextMut, Exports, Function, FunctionType, Global, Imports, - Instance, Memory, MemoryType, Module, Pages, RuntimeError, Table, TableType, TypedFunction, - Value, WasmPtr, + imports, namespace, AsStoreMut, Exports, Function, FunctionEnv, FunctionEnvMut, FunctionType, + Global, Imports, Instance, Memory, MemoryType, Module, Pages, RuntimeError, Table, TableType, + TypedFunction, Value, WasmPtr, }; use wasmer_types::Type as ValType; @@ -491,20 +491,20 @@ impl EmscriptenFunctions { /// before calling this function, please initialize `Ctx::data` with a pointer /// to [`EmscriptenData`]. pub fn set_up_emscripten( - ctx: &mut ContextMut<'_, EmEnv>, + store: &mut impl AsStoreMut, instance: &mut Instance, ) -> Result<(), RuntimeError> { // ATINIT // (used by C++) if let Ok(func) = instance.exports.get_function("globalCtors") { - func.call(&mut ctx.as_context_mut(), &[])?; + func.call(store, &[])?; } if let Ok(func) = instance .exports .get_function("___emscripten_environ_constructor") { - func.call(&mut ctx.as_context_mut(), &[])?; + func.call(store, &[])?; } Ok(()) } @@ -515,7 +515,7 @@ pub fn set_up_emscripten( /// If you don't want to set it up yourself, consider using [`run_emscripten_instance`]. pub fn emscripten_call_main( instance: &mut Instance, - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, path: &str, args: &[&str], ) -> Result<(), RuntimeError> { @@ -532,7 +532,7 @@ pub fn emscripten_call_main( 2 => { let mut new_args = vec![path]; new_args.extend(args); - let (argc, argv) = store_module_arguments(ctx.as_context_mut(), new_args); + let (argc, argv) = store_module_arguments(&mut ctx, new_args); let func: &Function = instance .exports .get(function_name) @@ -563,7 +563,7 @@ pub fn emscripten_call_main( /// Top level function to execute emscripten pub fn run_emscripten_instance( instance: &mut Instance, - mut ctx: ContextMut<'_, EmEnv>, + mut ctx: FunctionEnvMut, globals: &mut EmscriptenGlobals, path: &str, args: Vec<&str>, @@ -788,7 +788,7 @@ pub fn run_emscripten_instance( if let Ok(func) = instance.exports.get_typed_function(&ctx, "stackSave") { emfuncs.stack_save = Some(func); } - if let Ok(func) = instance.exports.get_typed_function(&ctx, "stackRestore") { + if let Ok(func) = instance.exports.get_typed_function(&ctx, "stackRe&mut ctx") { emfuncs.stack_restore = Some(func); } if let Ok(func) = instance.exports.get_typed_function(&ctx, "setThrew") { @@ -796,13 +796,13 @@ pub fn run_emscripten_instance( } ctx.data_mut().set_functions(emfuncs); - set_up_emscripten(&mut ctx.as_context_mut(), instance)?; + set_up_emscripten(&mut ctx, instance)?; // println!("running emscripten instance"); if let Some(ep) = entrypoint { debug!("Running entry point: {}", &ep); - let arg = unsafe { allocate_cstr_on_stack(&mut ctx.as_context_mut(), args[0]).0 }; + let arg = unsafe { allocate_cstr_on_stack(&mut ctx.as_mut(), args[0]).0 }; //let (argc, argv) = store_module_arguments(instance.context_mut(), args); let func: &Function = instance .exports @@ -818,16 +818,16 @@ pub fn run_emscripten_instance( Ok(()) } -fn store_module_arguments(mut ctx: ContextMut<'_, EmEnv>, args: Vec<&str>) -> (u32, u32) { +fn store_module_arguments(ctx: &mut FunctionEnvMut, args: Vec<&str>) -> (u32, u32) { let argc = args.len() + 1; let mut args_slice = vec![0; argc]; for (slot, arg) in args_slice[0..argc].iter_mut().zip(args.iter()) { - *slot = unsafe { allocate_cstr_on_stack(&mut ctx.as_context_mut(), arg).0 }; + *slot = unsafe { allocate_cstr_on_stack(&mut ctx.as_mut(), arg).0 }; } let (argv_offset, argv_slice): (_, &mut [u32]) = - unsafe { allocate_on_stack(&mut ctx, ((argc) * 4) as u32) }; + unsafe { allocate_on_stack(&mut ctx.as_mut(), ((argc) * 4) as u32) }; assert!(!argv_slice.is_empty()); for (slot, arg) in argv_slice[0..argc].iter_mut().zip(args_slice.iter()) { *slot = *arg @@ -838,15 +838,16 @@ fn store_module_arguments(mut ctx: ContextMut<'_, EmEnv>, args: Vec<&str>) -> (u } pub fn emscripten_set_up_memory( - mut ctx: ContextMut<'_, EmEnv>, + store: &mut impl AsStoreMut, + ctx: &FunctionEnv, memory: &Memory, globals: &EmscriptenGlobalsData, ) -> Result<(), String> { - ctx.data_mut().set_memory(memory.clone()); - let dynamictop_ptr = WasmPtr::::new(globals.dynamictop_ptr).deref(&ctx, memory); + ctx.as_mut(store).set_memory(memory.clone()); + let dynamictop_ptr = WasmPtr::::new(globals.dynamictop_ptr).deref(store, memory); let dynamic_base = globals.dynamic_base; - if dynamictop_ptr.offset() >= memory.data_size(&ctx) { + if dynamictop_ptr.offset() >= memory.data_size(store) { return Err("dynamictop_ptr beyond memory len".to_string()); } dynamictop_ptr.write(dynamic_base as i32).unwrap(); @@ -880,7 +881,8 @@ pub struct EmscriptenGlobals { impl EmscriptenGlobals { pub fn new( - mut ctx: ContextMut<'_, EmEnv>, + mut store: &mut impl AsStoreMut, + ctx: &FunctionEnv, module: &Module, /*, static_bump: u32 */ ) -> Result { let mut use_old_abort_on_cannot_grow_memory = false; @@ -898,14 +900,14 @@ impl EmscriptenGlobals { // Memory initialization let memory_type = MemoryType::new(memory_min, memory_max, shared); - let memory = Memory::new(&mut ctx, memory_type).unwrap(); + let memory = Memory::new(&mut store, memory_type).unwrap(); let table_type = TableType { ty: ValType::FuncRef, minimum: table_min, maximum: table_max, }; - let table = Table::new(&mut ctx, table_type, Value::FuncRef(None)).unwrap(); + let table = Table::new(&mut store, table_type, Value::FuncRef(None)).unwrap(); let data = { let static_bump = STATIC_BUMP; @@ -943,7 +945,7 @@ impl EmscriptenGlobals { } }; - emscripten_set_up_memory(ctx, &memory, &data)?; + emscripten_set_up_memory(store, ctx, &memory, &data)?; let mut null_function_names = vec![]; for import in module.imports().functions() { @@ -967,13 +969,18 @@ impl EmscriptenGlobals { } pub fn generate_emscripten_env( - ctx: &mut ContextMut<'_, EmEnv>, + mut store: &mut impl AsStoreMut, + ctx: &FunctionEnv, globals: &mut EmscriptenGlobals, ) -> Imports { let abort_on_cannot_grow_memory_export = if globals.data.use_old_abort_on_cannot_grow_memory { - Function::new_native(ctx, crate::memory::abort_on_cannot_grow_memory_old) + Function::new_native( + &mut store, + ctx, + crate::memory::abort_on_cannot_grow_memory_old, + ) } else { - Function::new_native(ctx, crate::memory::abort_on_cannot_grow_memory) + Function::new_native(&mut store, ctx, crate::memory::abort_on_cannot_grow_memory) }; let mut env_ns: Exports = namespace! { @@ -981,440 +988,440 @@ pub fn generate_emscripten_env( "table" => globals.table.clone(), // Globals - "STACKTOP" => Global::new(ctx, Value::I32(globals.data.stacktop as i32)), - "STACK_MAX" => Global::new(ctx, Value::I32(globals.data.stack_max as i32)), - "DYNAMICTOP_PTR" => Global::new(ctx, Value::I32(globals.data.dynamictop_ptr as i32)), - "fb" => Global::new(ctx, Value::I32(globals.data.table_base as i32)), - "tableBase" => Global::new(ctx, Value::I32(globals.data.table_base as i32)), - "__table_base" => Global::new(ctx, Value::I32(globals.data.table_base as i32)), - "ABORT" => Global::new(ctx, Value::I32(globals.data.abort as i32)), - "gb" => Global::new(ctx, Value::I32(globals.data.memory_base as i32)), - "memoryBase" => Global::new(ctx, Value::I32(globals.data.memory_base as i32)), - "__memory_base" => Global::new(ctx, Value::I32(globals.data.memory_base as i32)), - "tempDoublePtr" => Global::new(ctx, Value::I32(globals.data.temp_double_ptr as i32)), + "STACKTOP" => Global::new(&mut store, Value::I32(globals.data.stacktop as i32)), + "STACK_MAX" => Global::new(&mut store, Value::I32(globals.data.stack_max as i32)), + "DYNAMICTOP_PTR" => Global::new(&mut store, Value::I32(globals.data.dynamictop_ptr as i32)), + "fb" => Global::new(&mut store, Value::I32(globals.data.table_base as i32)), + "tableBase" => Global::new(&mut store, Value::I32(globals.data.table_base as i32)), + "__table_base" => Global::new(&mut store, Value::I32(globals.data.table_base as i32)), + "ABORT" => Global::new(&mut store, Value::I32(globals.data.abort as i32)), + "gb" => Global::new(&mut store, Value::I32(globals.data.memory_base as i32)), + "memoryBase" => Global::new(&mut store, Value::I32(globals.data.memory_base as i32)), + "__memory_base" => Global::new(&mut store, Value::I32(globals.data.memory_base as i32)), + "tempDoublePtr" => Global::new(&mut store, Value::I32(globals.data.temp_double_ptr as i32)), // inet - "_inet_addr" => Function::new_native(ctx, crate::inet::addr), + "_inet_addr" => Function::new_native(&mut store, ctx, crate::inet::addr), // IO - "printf" => Function::new_native(ctx, crate::io::printf), - "putchar" => Function::new_native(ctx, crate::io::putchar), - "___lock" => Function::new_native(ctx, crate::lock::___lock), - "___unlock" => Function::new_native(ctx, crate::lock::___unlock), - "___wait" => Function::new_native(ctx, crate::lock::___wait), - "_flock" => Function::new_native(ctx, crate::lock::_flock), - "_chroot" => Function::new_native(ctx, crate::io::chroot), - "_getprotobyname" => Function::new_native(ctx, crate::io::getprotobyname), - "_getprotobynumber" => Function::new_native(ctx, crate::io::getprotobynumber), - "_getpwuid" => Function::new_native(ctx, crate::io::getpwuid), - "_sigdelset" => Function::new_native(ctx, crate::io::sigdelset), - "_sigfillset" => Function::new_native(ctx, crate::io::sigfillset), - "_tzset" => Function::new_native(ctx, crate::io::tzset), - "_strptime" => Function::new_native(ctx, crate::io::strptime), + "printf" => Function::new_native(&mut store, ctx, crate::io::printf), + "putchar" => Function::new_native(&mut store, ctx, crate::io::putchar), + "___lock" => Function::new_native(&mut store, ctx, crate::lock::___lock), + "___unlock" => Function::new_native(&mut store, ctx, crate::lock::___unlock), + "___wait" => Function::new_native(&mut store, ctx, crate::lock::___wait), + "_flock" => Function::new_native(&mut store, ctx, crate::lock::_flock), + "_chroot" => Function::new_native(&mut store, ctx, crate::io::chroot), + "_getprotobyname" => Function::new_native(&mut store, ctx, crate::io::getprotobyname), + "_getprotobynumber" => Function::new_native(&mut store, ctx, crate::io::getprotobynumber), + "_getpwuid" => Function::new_native(&mut store, ctx, crate::io::getpwuid), + "_sigdelset" => Function::new_native(&mut store, ctx, crate::io::sigdelset), + "_sigfillset" => Function::new_native(&mut store, ctx, crate::io::sigfillset), + "_tzset" => Function::new_native(&mut store, ctx, crate::io::tzset), + "_strptime" => Function::new_native(&mut store, ctx, crate::io::strptime), // exec - "_execvp" => Function::new_native(ctx, crate::exec::execvp), - "_execl" => Function::new_native(ctx, crate::exec::execl), - "_execle" => Function::new_native(ctx, crate::exec::execle), + "_execvp" => Function::new_native(&mut store, ctx, crate::exec::execvp), + "_execl" => Function::new_native(&mut store, ctx, crate::exec::execl), + "_execle" => Function::new_native(&mut store, ctx, crate::exec::execle), // exit - "__exit" => Function::new_native(ctx, crate::exit::exit), + "__exit" => Function::new_native(&mut store, ctx, crate::exit::exit), // Env - "___assert_fail" => Function::new_native(ctx, crate::env::___assert_fail), - "_getenv" => Function::new_native(ctx, crate::env::_getenv), - "_setenv" => Function::new_native(ctx, crate::env::_setenv), - "_putenv" => Function::new_native(ctx, crate::env::_putenv), - "_unsetenv" => Function::new_native(ctx, crate::env::_unsetenv), - "_getpwnam" => Function::new_native(ctx, crate::env::_getpwnam), - "_getgrnam" => Function::new_native(ctx, crate::env::_getgrnam), - "___buildEnvironment" => Function::new_native(ctx, crate::env::___build_environment), - "___setErrNo" => Function::new_native(ctx, crate::errno::___seterrno), - "_getpagesize" => Function::new_native(ctx, crate::env::_getpagesize), - "_sysconf" => Function::new_native(ctx, crate::env::_sysconf), - "_getaddrinfo" => Function::new_native(ctx, crate::env::_getaddrinfo), - "_times" => Function::new_native(ctx, crate::env::_times), - "_pathconf" => Function::new_native(ctx, crate::env::_pathconf), - "_fpathconf" => Function::new_native(ctx, crate::env::_fpathconf), + "___assert_fail" => Function::new_native(&mut store, ctx, crate::env::___assert_fail), + "_getenv" => Function::new_native(&mut store, ctx, crate::env::_getenv), + "_setenv" => Function::new_native(&mut store, ctx, crate::env::_setenv), + "_putenv" => Function::new_native(&mut store, ctx, crate::env::_putenv), + "_unsetenv" => Function::new_native(&mut store, ctx, crate::env::_unsetenv), + "_getpwnam" => Function::new_native(&mut store, ctx, crate::env::_getpwnam), + "_getgrnam" => Function::new_native(&mut store, ctx, crate::env::_getgrnam), + "___buildEnvironment" => Function::new_native(&mut store, ctx, crate::env::___build_environment), + "___setErrNo" => Function::new_native(&mut store, ctx, crate::errno::___seterrno), + "_getpagesize" => Function::new_native(&mut store, ctx, crate::env::_getpagesize), + "_sysconf" => Function::new_native(&mut store, ctx, crate::env::_sysconf), + "_getaddrinfo" => Function::new_native(&mut store, ctx, crate::env::_getaddrinfo), + "_times" => Function::new_native(&mut store, ctx, crate::env::_times), + "_pathconf" => Function::new_native(&mut store, ctx, crate::env::_pathconf), + "_fpathconf" => Function::new_native(&mut store, ctx, crate::env::_fpathconf), // Syscalls - "___syscall1" => Function::new_native(ctx, crate::syscalls::___syscall1), - "___syscall3" => Function::new_native(ctx, crate::syscalls::___syscall3), - "___syscall4" => Function::new_native(ctx, crate::syscalls::___syscall4), - "___syscall5" => Function::new_native(ctx, crate::syscalls::___syscall5), - "___syscall6" => Function::new_native(ctx, crate::syscalls::___syscall6), - "___syscall9" => Function::new_native(ctx, crate::syscalls::___syscall9), - "___syscall10" => Function::new_native(ctx, crate::syscalls::___syscall10), - "___syscall12" => Function::new_native(ctx, crate::syscalls::___syscall12), - "___syscall14" => Function::new_native(ctx, crate::syscalls::___syscall14), - "___syscall15" => Function::new_native(ctx, crate::syscalls::___syscall15), - "___syscall20" => Function::new_native(ctx, crate::syscalls::___syscall20), - "___syscall21" => Function::new_native(ctx, crate::syscalls::___syscall21), - "___syscall25" => Function::new_native(ctx, crate::syscalls::___syscall25), - "___syscall29" => Function::new_native(ctx, crate::syscalls::___syscall29), - "___syscall32" => Function::new_native(ctx, crate::syscalls::___syscall32), - "___syscall33" => Function::new_native(ctx, crate::syscalls::___syscall33), - "___syscall34" => Function::new_native(ctx, crate::syscalls::___syscall34), - "___syscall36" => Function::new_native(ctx, crate::syscalls::___syscall36), - "___syscall39" => Function::new_native(ctx, crate::syscalls::___syscall39), - "___syscall38" => Function::new_native(ctx, crate::syscalls::___syscall38), - "___syscall40" => Function::new_native(ctx, crate::syscalls::___syscall40), - "___syscall41" => Function::new_native(ctx, crate::syscalls::___syscall41), - "___syscall42" => Function::new_native(ctx, crate::syscalls::___syscall42), - "___syscall51" => Function::new_native(ctx, crate::syscalls::___syscall51), - "___syscall52" => Function::new_native(ctx, crate::syscalls::___syscall52), - "___syscall53" => Function::new_native(ctx, crate::syscalls::___syscall53), - "___syscall54" => Function::new_native(ctx, crate::syscalls::___syscall54), - "___syscall57" => Function::new_native(ctx, crate::syscalls::___syscall57), - "___syscall60" => Function::new_native(ctx, crate::syscalls::___syscall60), - "___syscall63" => Function::new_native(ctx, crate::syscalls::___syscall63), - "___syscall64" => Function::new_native(ctx, crate::syscalls::___syscall64), - "___syscall66" => Function::new_native(ctx, crate::syscalls::___syscall66), - "___syscall75" => Function::new_native(ctx, crate::syscalls::___syscall75), - "___syscall77" => Function::new_native(ctx, crate::syscalls::___syscall77), - "___syscall83" => Function::new_native(ctx, crate::syscalls::___syscall83), - "___syscall85" => Function::new_native(ctx, crate::syscalls::___syscall85), - "___syscall91" => Function::new_native(ctx, crate::syscalls::___syscall91), - "___syscall94" => Function::new_native(ctx, crate::syscalls::___syscall94), - "___syscall96" => Function::new_native(ctx, crate::syscalls::___syscall96), - "___syscall97" => Function::new_native(ctx, crate::syscalls::___syscall97), - "___syscall102" => Function::new_native(ctx, crate::syscalls::___syscall102), - "___syscall110" => Function::new_native(ctx, crate::syscalls::___syscall110), - "___syscall114" => Function::new_native(ctx, crate::syscalls::___syscall114), - "___syscall118" => Function::new_native(ctx, crate::syscalls::___syscall118), - "___syscall121" => Function::new_native(ctx, crate::syscalls::___syscall121), - "___syscall122" => Function::new_native(ctx, crate::syscalls::___syscall122), - "___syscall125" => Function::new_native(ctx, crate::syscalls::___syscall125), - "___syscall132" => Function::new_native(ctx, crate::syscalls::___syscall132), - "___syscall133" => Function::new_native(ctx, crate::syscalls::___syscall133), - "___syscall140" => Function::new_native(ctx, crate::syscalls::___syscall140), - "___syscall142" => Function::new_native(ctx, crate::syscalls::___syscall142), - "___syscall144" => Function::new_native(ctx, crate::syscalls::___syscall144), - "___syscall145" => Function::new_native(ctx, crate::syscalls::___syscall145), - "___syscall146" => Function::new_native(ctx, crate::syscalls::___syscall146), - "___syscall147" => Function::new_native(ctx, crate::syscalls::___syscall147), - "___syscall148" => Function::new_native(ctx, crate::syscalls::___syscall148), - "___syscall150" => Function::new_native(ctx, crate::syscalls::___syscall150), - "___syscall151" => Function::new_native(ctx, crate::syscalls::___syscall151), - "___syscall152" => Function::new_native(ctx, crate::syscalls::___syscall152), - "___syscall153" => Function::new_native(ctx, crate::syscalls::___syscall153), - "___syscall163" => Function::new_native(ctx, crate::syscalls::___syscall163), - "___syscall168" => Function::new_native(ctx, crate::syscalls::___syscall168), - "___syscall180" => Function::new_native(ctx, crate::syscalls::___syscall180), - "___syscall181" => Function::new_native(ctx, crate::syscalls::___syscall181), - "___syscall183" => Function::new_native(ctx, crate::syscalls::___syscall183), - "___syscall191" => Function::new_native(ctx, crate::syscalls::___syscall191), - "___syscall192" => Function::new_native(ctx, crate::syscalls::___syscall192), - "___syscall193" => Function::new_native(ctx, crate::syscalls::___syscall193), - "___syscall194" => Function::new_native(ctx, crate::syscalls::___syscall194), - "___syscall195" => Function::new_native(ctx, crate::syscalls::___syscall195), - "___syscall196" => Function::new_native(ctx, crate::syscalls::___syscall196), - "___syscall197" => Function::new_native(ctx, crate::syscalls::___syscall197), - "___syscall198" => Function::new_native(ctx, crate::syscalls::___syscall198), - "___syscall199" => Function::new_native(ctx, crate::syscalls::___syscall199), - "___syscall200" => Function::new_native(ctx, crate::syscalls::___syscall200), - "___syscall201" => Function::new_native(ctx, crate::syscalls::___syscall201), - "___syscall202" => Function::new_native(ctx, crate::syscalls::___syscall202), - "___syscall205" => Function::new_native(ctx, crate::syscalls::___syscall205), - "___syscall207" => Function::new_native(ctx, crate::syscalls::___syscall207), - "___syscall209" => Function::new_native(ctx, crate::syscalls::___syscall209), - "___syscall211" => Function::new_native(ctx, crate::syscalls::___syscall211), - "___syscall212" => Function::new_native(ctx, crate::syscalls::___syscall212), - "___syscall218" => Function::new_native(ctx, crate::syscalls::___syscall218), - "___syscall219" => Function::new_native(ctx, crate::syscalls::___syscall219), - "___syscall220" => Function::new_native(ctx, crate::syscalls::___syscall220), - "___syscall221" => Function::new_native(ctx, crate::syscalls::___syscall221), - "___syscall268" => Function::new_native(ctx, crate::syscalls::___syscall268), - "___syscall269" => Function::new_native(ctx, crate::syscalls::___syscall269), - "___syscall272" => Function::new_native(ctx, crate::syscalls::___syscall272), - "___syscall295" => Function::new_native(ctx, crate::syscalls::___syscall295), - "___syscall296" => Function::new_native(ctx, crate::syscalls::___syscall296), - "___syscall297" => Function::new_native(ctx, crate::syscalls::___syscall297), - "___syscall298" => Function::new_native(ctx, crate::syscalls::___syscall298), - "___syscall300" => Function::new_native(ctx, crate::syscalls::___syscall300), - "___syscall301" => Function::new_native(ctx, crate::syscalls::___syscall301), - "___syscall302" => Function::new_native(ctx, crate::syscalls::___syscall302), - "___syscall303" => Function::new_native(ctx, crate::syscalls::___syscall303), - "___syscall304" => Function::new_native(ctx, crate::syscalls::___syscall304), - "___syscall305" => Function::new_native(ctx, crate::syscalls::___syscall305), - "___syscall306" => Function::new_native(ctx, crate::syscalls::___syscall306), - "___syscall307" => Function::new_native(ctx, crate::syscalls::___syscall307), - "___syscall308" => Function::new_native(ctx, crate::syscalls::___syscall308), - "___syscall320" => Function::new_native(ctx, crate::syscalls::___syscall320), - "___syscall324" => Function::new_native(ctx, crate::syscalls::___syscall324), - "___syscall330" => Function::new_native(ctx, crate::syscalls::___syscall330), - "___syscall331" => Function::new_native(ctx, crate::syscalls::___syscall331), - "___syscall333" => Function::new_native(ctx, crate::syscalls::___syscall333), - "___syscall334" => Function::new_native(ctx, crate::syscalls::___syscall334), - "___syscall337" => Function::new_native(ctx, crate::syscalls::___syscall337), - "___syscall340" => Function::new_native(ctx, crate::syscalls::___syscall340), - "___syscall345" => Function::new_native(ctx, crate::syscalls::___syscall345), + "___syscall1" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall1), + "___syscall3" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall3), + "___syscall4" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall4), + "___syscall5" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall5), + "___syscall6" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall6), + "___syscall9" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall9), + "___syscall10" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall10), + "___syscall12" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall12), + "___syscall14" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall14), + "___syscall15" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall15), + "___syscall20" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall20), + "___syscall21" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall21), + "___syscall25" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall25), + "___syscall29" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall29), + "___syscall32" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall32), + "___syscall33" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall33), + "___syscall34" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall34), + "___syscall36" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall36), + "___syscall39" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall39), + "___syscall38" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall38), + "___syscall40" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall40), + "___syscall41" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall41), + "___syscall42" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall42), + "___syscall51" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall51), + "___syscall52" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall52), + "___syscall53" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall53), + "___syscall54" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall54), + "___syscall57" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall57), + "___syscall60" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall60), + "___syscall63" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall63), + "___syscall64" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall64), + "___syscall66" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall66), + "___syscall75" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall75), + "___syscall77" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall77), + "___syscall83" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall83), + "___syscall85" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall85), + "___syscall91" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall91), + "___syscall94" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall94), + "___syscall96" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall96), + "___syscall97" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall97), + "___syscall102" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall102), + "___syscall110" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall110), + "___syscall114" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall114), + "___syscall118" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall118), + "___syscall121" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall121), + "___syscall122" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall122), + "___syscall125" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall125), + "___syscall132" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall132), + "___syscall133" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall133), + "___syscall140" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall140), + "___syscall142" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall142), + "___syscall144" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall144), + "___syscall145" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall145), + "___syscall146" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall146), + "___syscall147" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall147), + "___syscall148" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall148), + "___syscall150" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall150), + "___syscall151" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall151), + "___syscall152" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall152), + "___syscall153" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall153), + "___syscall163" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall163), + "___syscall168" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall168), + "___syscall180" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall180), + "___syscall181" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall181), + "___syscall183" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall183), + "___syscall191" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall191), + "___syscall192" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall192), + "___syscall193" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall193), + "___syscall194" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall194), + "___syscall195" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall195), + "___syscall196" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall196), + "___syscall197" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall197), + "___syscall198" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall198), + "___syscall199" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall199), + "___syscall200" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall200), + "___syscall201" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall201), + "___syscall202" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall202), + "___syscall205" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall205), + "___syscall207" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall207), + "___syscall209" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall209), + "___syscall211" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall211), + "___syscall212" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall212), + "___syscall218" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall218), + "___syscall219" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall219), + "___syscall220" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall220), + "___syscall221" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall221), + "___syscall268" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall268), + "___syscall269" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall269), + "___syscall272" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall272), + "___syscall295" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall295), + "___syscall296" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall296), + "___syscall297" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall297), + "___syscall298" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall298), + "___syscall300" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall300), + "___syscall301" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall301), + "___syscall302" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall302), + "___syscall303" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall303), + "___syscall304" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall304), + "___syscall305" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall305), + "___syscall306" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall306), + "___syscall307" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall307), + "___syscall308" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall308), + "___syscall320" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall320), + "___syscall324" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall324), + "___syscall330" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall330), + "___syscall331" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall331), + "___syscall333" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall333), + "___syscall334" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall334), + "___syscall337" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall337), + "___syscall340" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall340), + "___syscall345" => Function::new_native(&mut store, ctx, crate::syscalls::___syscall345), // Process - "abort" => Function::new_native(ctx, crate::process::em_abort), - "_abort" => Function::new_native(ctx, crate::process::_abort), - "_prctl" => Function::new_native(ctx, crate::process::_prctl), - "abortStackOverflow" => Function::new_native(ctx, crate::process::abort_stack_overflow), - "_llvm_trap" => Function::new_native(ctx, crate::process::_llvm_trap), - "_fork" => Function::new_native(ctx, crate::process::_fork), - "_exit" => Function::new_native(ctx, crate::process::_exit), - "_system" => Function::new_native(ctx, crate::process::_system), - "_popen" => Function::new_native(ctx, crate::process::_popen), - "_endgrent" => Function::new_native(ctx, crate::process::_endgrent), - "_execve" => Function::new_native(ctx, crate::process::_execve), - "_kill" => Function::new_native(ctx, crate::process::_kill), - "_llvm_stackrestore" => Function::new_native(ctx, crate::process::_llvm_stackrestore), - "_llvm_stacksave" => Function::new_native(ctx, crate::process::_llvm_stacksave), - "_llvm_eh_typeid_for" => Function::new_native(ctx, crate::process::_llvm_eh_typeid_for), - "_raise" => Function::new_native(ctx, crate::process::_raise), - "_sem_init" => Function::new_native(ctx, crate::process::_sem_init), - "_sem_destroy" => Function::new_native(ctx, crate::process::_sem_destroy), - "_sem_post" => Function::new_native(ctx, crate::process::_sem_post), - "_sem_wait" => Function::new_native(ctx, crate::process::_sem_wait), - "_getgrent" => Function::new_native(ctx, crate::process::_getgrent), - "_sched_yield" => Function::new_native(ctx, crate::process::_sched_yield), - "_setgrent" => Function::new_native(ctx, crate::process::_setgrent), - "_setgroups" => Function::new_native(ctx, crate::process::_setgroups), - "_setitimer" => Function::new_native(ctx, crate::process::_setitimer), - "_usleep" => Function::new_native(ctx, crate::process::_usleep), - "_nanosleep" => Function::new_native(ctx, crate::process::_nanosleep), - "_utime" => Function::new_native(ctx, crate::process::_utime), - "_utimes" => Function::new_native(ctx, crate::process::_utimes), - "_wait" => Function::new_native(ctx, crate::process::_wait), - "_wait3" => Function::new_native(ctx, crate::process::_wait3), - "_wait4" => Function::new_native(ctx, crate::process::_wait4), - "_waitid" => Function::new_native(ctx, crate::process::_waitid), - "_waitpid" => Function::new_native(ctx, crate::process::_waitpid), + "abort" => Function::new_native(&mut store, ctx, crate::process::em_abort), + "_abort" => Function::new_native(&mut store, ctx, crate::process::_abort), + "_prctl" => Function::new_native(&mut store, ctx, crate::process::_prctl), + "abortStackOverflow" => Function::new_native(&mut store, ctx, crate::process::abort_stack_overflow), + "_llvm_trap" => Function::new_native(&mut store, ctx, crate::process::_llvm_trap), + "_fork" => Function::new_native(&mut store, ctx, crate::process::_fork), + "_exit" => Function::new_native(&mut store, ctx, crate::process::_exit), + "_system" => Function::new_native(&mut store, ctx, crate::process::_system), + "_popen" => Function::new_native(&mut store, ctx, crate::process::_popen), + "_endgrent" => Function::new_native(&mut store, ctx, crate::process::_endgrent), + "_execve" => Function::new_native(&mut store, ctx, crate::process::_execve), + "_kill" => Function::new_native(&mut store, ctx, crate::process::_kill), + "_llvm_stackrestore" => Function::new_native(&mut store, ctx, crate::process::_llvm_stackrestore), + "_llvm_stacksave" => Function::new_native(&mut store, ctx, crate::process::_llvm_stacksave), + "_llvm_eh_typeid_for" => Function::new_native(&mut store, ctx, crate::process::_llvm_eh_typeid_for), + "_raise" => Function::new_native(&mut store, ctx, crate::process::_raise), + "_sem_init" => Function::new_native(&mut store, ctx, crate::process::_sem_init), + "_sem_destroy" => Function::new_native(&mut store, ctx, crate::process::_sem_destroy), + "_sem_post" => Function::new_native(&mut store, ctx, crate::process::_sem_post), + "_sem_wait" => Function::new_native(&mut store, ctx, crate::process::_sem_wait), + "_getgrent" => Function::new_native(&mut store, ctx, crate::process::_getgrent), + "_sched_yield" => Function::new_native(&mut store, ctx, crate::process::_sched_yield), + "_setgrent" => Function::new_native(&mut store, ctx, crate::process::_setgrent), + "_setgroups" => Function::new_native(&mut store, ctx, crate::process::_setgroups), + "_setitimer" => Function::new_native(&mut store, ctx, crate::process::_setitimer), + "_usleep" => Function::new_native(&mut store, ctx, crate::process::_usleep), + "_nanosleep" => Function::new_native(&mut store, ctx, crate::process::_nanosleep), + "_utime" => Function::new_native(&mut store, ctx, crate::process::_utime), + "_utimes" => Function::new_native(&mut store, ctx, crate::process::_utimes), + "_wait" => Function::new_native(&mut store, ctx, crate::process::_wait), + "_wait3" => Function::new_native(&mut store, ctx, crate::process::_wait3), + "_wait4" => Function::new_native(&mut store, ctx, crate::process::_wait4), + "_waitid" => Function::new_native(&mut store, ctx, crate::process::_waitid), + "_waitpid" => Function::new_native(&mut store, ctx, crate::process::_waitpid), // Emscripten - "_emscripten_asm_const_i" => Function::new_native(ctx, crate::emscripten_target::asm_const_i), - "_emscripten_exit_with_live_runtime" => Function::new_native(ctx, crate::emscripten_target::exit_with_live_runtime), + "_emscripten_asm_const_i" => Function::new_native(&mut store, ctx, crate::emscripten_target::asm_const_i), + "_emscripten_exit_with_live_runtime" => Function::new_native(&mut store, ctx, crate::emscripten_target::exit_with_live_runtime), // Signal - "_sigemptyset" => Function::new_native(ctx, crate::signal::_sigemptyset), - "_sigaddset" => Function::new_native(ctx, crate::signal::_sigaddset), - "_sigprocmask" => Function::new_native(ctx, crate::signal::_sigprocmask), - "_sigaction" => Function::new_native(ctx, crate::signal::_sigaction), - "_signal" => Function::new_native(ctx, crate::signal::_signal), - "_sigsuspend" => Function::new_native(ctx, crate::signal::_sigsuspend), + "_sigemptyset" => Function::new_native(&mut store, ctx, crate::signal::_sigemptyset), + "_sigaddset" => Function::new_native(&mut store, ctx, crate::signal::_sigaddset), + "_sigprocmask" => Function::new_native(&mut store, ctx, crate::signal::_sigprocmask), + "_sigaction" => Function::new_native(&mut store, ctx, crate::signal::_sigaction), + "_signal" => Function::new_native(&mut store, ctx, crate::signal::_signal), + "_sigsuspend" => Function::new_native(&mut store, ctx, crate::signal::_sigsuspend), // Memory "abortOnCannotGrowMemory" => abort_on_cannot_grow_memory_export, - "_emscripten_memcpy_big" => Function::new_native(ctx, crate::memory::_emscripten_memcpy_big), - "_emscripten_get_heap_size" => Function::new_native(ctx, crate::memory::_emscripten_get_heap_size), - "_emscripten_resize_heap" => Function::new_native(ctx, crate::memory::_emscripten_resize_heap), - "enlargeMemory" => Function::new_native(ctx, crate::memory::enlarge_memory), - "segfault" => Function::new_native(ctx, crate::memory::segfault), - "alignfault" => Function::new_native(ctx, crate::memory::alignfault), - "ftfault" => Function::new_native(ctx, crate::memory::ftfault), - "getTotalMemory" => Function::new_native(ctx, crate::memory::get_total_memory), - "_sbrk" => Function::new_native(ctx, crate::memory::sbrk), - "___map_file" => Function::new_native(ctx, crate::memory::___map_file), + "_emscripten_memcpy_big" => Function::new_native(&mut store, ctx, crate::memory::_emscripten_memcpy_big), + "_emscripten_get_heap_size" => Function::new_native(&mut store, ctx, crate::memory::_emscripten_get_heap_size), + "_emscripten_resize_heap" => Function::new_native(&mut store, ctx, crate::memory::_emscripten_resize_heap), + "enlargeMemory" => Function::new_native(&mut store, ctx, crate::memory::enlarge_memory), + "segfault" => Function::new_native(&mut store, ctx, crate::memory::segfault), + "alignfault" => Function::new_native(&mut store, ctx, crate::memory::alignfault), + "ftfault" => Function::new_native(&mut store, ctx, crate::memory::ftfault), + "getTotalMemory" => Function::new_native(&mut store, ctx, crate::memory::get_total_memory), + "_sbrk" => Function::new_native(&mut store, ctx, crate::memory::sbrk), + "___map_file" => Function::new_native(&mut store, ctx, crate::memory::___map_file), // Exception - "___cxa_allocate_exception" => Function::new_native(ctx, crate::exception::___cxa_allocate_exception), - "___cxa_current_primary_exception" => Function::new_native(ctx, crate::exception::___cxa_current_primary_exception), - "___cxa_decrement_exception_refcount" => Function::new_native(ctx, crate::exception::___cxa_decrement_exception_refcount), - "___cxa_increment_exception_refcount" => Function::new_native(ctx, crate::exception::___cxa_increment_exception_refcount), - "___cxa_rethrow_primary_exception" => Function::new_native(ctx, crate::exception::___cxa_rethrow_primary_exception), - "___cxa_throw" => Function::new_native(ctx, crate::exception::___cxa_throw), - "___cxa_begin_catch" => Function::new_native(ctx, crate::exception::___cxa_begin_catch), - "___cxa_end_catch" => Function::new_native(ctx, crate::exception::___cxa_end_catch), - "___cxa_uncaught_exception" => Function::new_native(ctx, crate::exception::___cxa_uncaught_exception), - "___cxa_pure_virtual" => Function::new_native(ctx, crate::exception::___cxa_pure_virtual), + "___cxa_allocate_exception" => Function::new_native(&mut store, ctx, crate::exception::___cxa_allocate_exception), + "___cxa_current_primary_exception" => Function::new_native(&mut store, ctx, crate::exception::___cxa_current_primary_exception), + "___cxa_decrement_exception_refcount" => Function::new_native(&mut store, ctx, crate::exception::___cxa_decrement_exception_refcount), + "___cxa_increment_exception_refcount" => Function::new_native(&mut store, ctx, crate::exception::___cxa_increment_exception_refcount), + "___cxa_rethrow_primary_exception" => Function::new_native(&mut store, ctx, crate::exception::___cxa_rethrow_primary_exception), + "___cxa_throw" => Function::new_native(&mut store, ctx, crate::exception::___cxa_throw), + "___cxa_begin_catch" => Function::new_native(&mut store, ctx, crate::exception::___cxa_begin_catch), + "___cxa_end_catch" => Function::new_native(&mut store, ctx, crate::exception::___cxa_end_catch), + "___cxa_uncaught_exception" => Function::new_native(&mut store, ctx, crate::exception::___cxa_uncaught_exception), + "___cxa_pure_virtual" => Function::new_native(&mut store, ctx, crate::exception::___cxa_pure_virtual), // Time - "_gettimeofday" => Function::new_native(ctx, crate::time::_gettimeofday), - "_clock_getres" => Function::new_native(ctx, crate::time::_clock_getres), - "_clock_gettime" => Function::new_native(ctx, crate::time::_clock_gettime), - "_clock_settime" => Function::new_native(ctx, crate::time::_clock_settime), - "___clock_gettime" => Function::new_native(ctx, crate::time::_clock_gettime), - "_clock" => Function::new_native(ctx, crate::time::_clock), - "_difftime" => Function::new_native(ctx, crate::time::_difftime), - "_asctime" => Function::new_native(ctx, crate::time::_asctime), - "_asctime_r" => Function::new_native(ctx, crate::time::_asctime_r), - "_localtime" => Function::new_native(ctx, crate::time::_localtime), - "_time" => Function::new_native(ctx, crate::time::_time), - "_timegm" => Function::new_native(ctx, crate::time::_timegm), - "_strftime" => Function::new_native(ctx, crate::time::_strftime), - "_strftime_l" => Function::new_native(ctx, crate::time::_strftime_l), - "_localtime_r" => Function::new_native(ctx, crate::time::_localtime_r), - "_gmtime_r" => Function::new_native(ctx, crate::time::_gmtime_r), - "_ctime" => Function::new_native(ctx, crate::time::_ctime), - "_ctime_r" => Function::new_native(ctx, crate::time::_ctime_r), - "_mktime" => Function::new_native(ctx, crate::time::_mktime), - "_gmtime" => Function::new_native(ctx, crate::time::_gmtime), + "_gettimeofday" => Function::new_native(&mut store, ctx, crate::time::_gettimeofday), + "_clock_getres" => Function::new_native(&mut store, ctx, crate::time::_clock_getres), + "_clock_gettime" => Function::new_native(&mut store, ctx, crate::time::_clock_gettime), + "_clock_settime" => Function::new_native(&mut store, ctx, crate::time::_clock_settime), + "___clock_gettime" => Function::new_native(&mut store, ctx, crate::time::_clock_gettime), + "_clock" => Function::new_native(&mut store, ctx, crate::time::_clock), + "_difftime" => Function::new_native(&mut store, ctx, crate::time::_difftime), + "_asctime" => Function::new_native(&mut store, ctx, crate::time::_asctime), + "_asctime_r" => Function::new_native(&mut store, ctx, crate::time::_asctime_r), + "_localtime" => Function::new_native(&mut store, ctx, crate::time::_localtime), + "_time" => Function::new_native(&mut store, ctx, crate::time::_time), + "_timegm" => Function::new_native(&mut store, ctx, crate::time::_timegm), + "_strftime" => Function::new_native(&mut store, ctx, crate::time::_strftime), + "_strftime_l" => Function::new_native(&mut store, ctx, crate::time::_strftime_l), + "_localtime_r" => Function::new_native(&mut store, ctx, crate::time::_localtime_r), + "_gmtime_r" => Function::new_native(&mut store, ctx, crate::time::_gmtime_r), + "_ctime" => Function::new_native(&mut store, ctx, crate::time::_ctime), + "_ctime_r" => Function::new_native(&mut store, ctx, crate::time::_ctime_r), + "_mktime" => Function::new_native(&mut store, ctx, crate::time::_mktime), + "_gmtime" => Function::new_native(&mut store, ctx, crate::time::_gmtime), // Math - "sqrt" => Function::new_native(ctx, crate::math::sqrt), - "floor" => Function::new_native(ctx, crate::math::floor), - "fabs" => Function::new_native(ctx, crate::math::fabs), - "f64-rem" => Function::new_native(ctx, crate::math::f64_rem), - "_llvm_copysign_f32" => Function::new_native(ctx, crate::math::_llvm_copysign_f32), - "_llvm_copysign_f64" => Function::new_native(ctx, crate::math::_llvm_copysign_f64), - "_llvm_log10_f64" => Function::new_native(ctx, crate::math::_llvm_log10_f64), - "_llvm_log2_f64" => Function::new_native(ctx, crate::math::_llvm_log2_f64), - "_llvm_log10_f32" => Function::new_native(ctx, crate::math::_llvm_log10_f32), - "_llvm_log2_f32" => Function::new_native(ctx, crate::math::_llvm_log2_f64), - "_llvm_sin_f64" => Function::new_native(ctx, crate::math::_llvm_sin_f64), - "_llvm_cos_f64" => Function::new_native(ctx, crate::math::_llvm_cos_f64), - "_llvm_exp2_f32" => Function::new_native(ctx, crate::math::_llvm_exp2_f32), - "_llvm_exp2_f64" => Function::new_native(ctx, crate::math::_llvm_exp2_f64), - "_llvm_trunc_f64" => Function::new_native(ctx, crate::math::_llvm_trunc_f64), - "_llvm_fma_f64" => Function::new_native(ctx, crate::math::_llvm_fma_f64), - "_emscripten_random" => Function::new_native(ctx, crate::math::_emscripten_random), + "sqrt" => Function::new_native(&mut store, ctx, crate::math::sqrt), + "floor" => Function::new_native(&mut store, ctx, crate::math::floor), + "fabs" => Function::new_native(&mut store, ctx, crate::math::fabs), + "f64-rem" => Function::new_native(&mut store, ctx, crate::math::f64_rem), + "_llvm_copysign_f32" => Function::new_native(&mut store, ctx, crate::math::_llvm_copysign_f32), + "_llvm_copysign_f64" => Function::new_native(&mut store, ctx, crate::math::_llvm_copysign_f64), + "_llvm_log10_f64" => Function::new_native(&mut store, ctx, crate::math::_llvm_log10_f64), + "_llvm_log2_f64" => Function::new_native(&mut store, ctx, crate::math::_llvm_log2_f64), + "_llvm_log10_f32" => Function::new_native(&mut store, ctx, crate::math::_llvm_log10_f32), + "_llvm_log2_f32" => Function::new_native(&mut store, ctx, crate::math::_llvm_log2_f64), + "_llvm_sin_f64" => Function::new_native(&mut store, ctx, crate::math::_llvm_sin_f64), + "_llvm_cos_f64" => Function::new_native(&mut store, ctx, crate::math::_llvm_cos_f64), + "_llvm_exp2_f32" => Function::new_native(&mut store, ctx, crate::math::_llvm_exp2_f32), + "_llvm_exp2_f64" => Function::new_native(&mut store, ctx, crate::math::_llvm_exp2_f64), + "_llvm_trunc_f64" => Function::new_native(&mut store, ctx, crate::math::_llvm_trunc_f64), + "_llvm_fma_f64" => Function::new_native(&mut store, ctx, crate::math::_llvm_fma_f64), + "_emscripten_random" => Function::new_native(&mut store, ctx, crate::math::_emscripten_random), // Jump - "__setjmp" => Function::new_native(ctx, crate::jmp::__setjmp), - "__longjmp" => Function::new_native(ctx, crate::jmp::__longjmp), - "_longjmp" => Function::new_native(ctx, crate::jmp::_longjmp), - "_emscripten_longjmp" => Function::new_native(ctx, crate::jmp::_longjmp), + "__setjmp" => Function::new_native(&mut store, ctx, crate::jmp::__setjmp), + "__longjmp" => Function::new_native(&mut store, ctx, crate::jmp::__longjmp), + "_longjmp" => Function::new_native(&mut store, ctx, crate::jmp::_longjmp), + "_emscripten_longjmp" => Function::new_native(&mut store, ctx, crate::jmp::_longjmp), // Bitwise - "_llvm_bswap_i64" => Function::new_native(ctx, crate::bitwise::_llvm_bswap_i64), + "_llvm_bswap_i64" => Function::new_native(&mut store, ctx, crate::bitwise::_llvm_bswap_i64), // libc - "_execv" => Function::new_native(ctx, crate::libc::execv), - "_endpwent" => Function::new_native(ctx, crate::libc::endpwent), - "_fexecve" => Function::new_native(ctx, crate::libc::fexecve), - "_fpathconf" => Function::new_native(ctx, crate::libc::fpathconf), - "_getitimer" => Function::new_native(ctx, crate::libc::getitimer), - "_getpwent" => Function::new_native(ctx, crate::libc::getpwent), - "_killpg" => Function::new_native(ctx, crate::libc::killpg), - "_pathconf" => Function::new_native(ctx, crate::libc::pathconf), - "_siginterrupt" => Function::new_native(ctx, crate::signal::_siginterrupt), - "_setpwent" => Function::new_native(ctx, crate::libc::setpwent), - "_sigismember" => Function::new_native(ctx, crate::libc::sigismember), - "_sigpending" => Function::new_native(ctx, crate::libc::sigpending), - "___libc_current_sigrtmax" => Function::new_native(ctx, crate::libc::current_sigrtmax), - "___libc_current_sigrtmin" => Function::new_native(ctx, crate::libc::current_sigrtmin), + "_execv" => Function::new_native(&mut store, ctx, crate::libc::execv), + "_endpwent" => Function::new_native(&mut store, ctx, crate::libc::endpwent), + "_fexecve" => Function::new_native(&mut store, ctx, crate::libc::fexecve), + "_fpathconf" => Function::new_native(&mut store, ctx, crate::libc::fpathconf), + "_getitimer" => Function::new_native(&mut store, ctx, crate::libc::getitimer), + "_getpwent" => Function::new_native(&mut store, ctx, crate::libc::getpwent), + "_killpg" => Function::new_native(&mut store, ctx, crate::libc::killpg), + "_pathconf" => Function::new_native(&mut store, ctx, crate::libc::pathconf), + "_siginterrupt" => Function::new_native(&mut store, ctx, crate::signal::_siginterrupt), + "_setpwent" => Function::new_native(&mut store, ctx, crate::libc::setpwent), + "_sigismember" => Function::new_native(&mut store, ctx, crate::libc::sigismember), + "_sigpending" => Function::new_native(&mut store, ctx, crate::libc::sigpending), + "___libc_current_sigrtmax" => Function::new_native(&mut store, ctx, crate::libc::current_sigrtmax), + "___libc_current_sigrtmin" => Function::new_native(&mut store, ctx, crate::libc::current_sigrtmin), // Linking - "_dlclose" => Function::new_native(ctx, crate::linking::_dlclose), - "_dlerror" => Function::new_native(ctx, crate::linking::_dlerror), - "_dlopen" => Function::new_native(ctx, crate::linking::_dlopen), - "_dlsym" => Function::new_native(ctx, crate::linking::_dlsym), + "_dlclose" => Function::new_native(&mut store, ctx, crate::linking::_dlclose), + "_dlerror" => Function::new_native(&mut store, ctx, crate::linking::_dlerror), + "_dlopen" => Function::new_native(&mut store, ctx, crate::linking::_dlopen), + "_dlsym" => Function::new_native(&mut store, ctx, crate::linking::_dlsym), // wasm32-unknown-emscripten - "_alarm" => Function::new_native(ctx, crate::emscripten_target::_alarm), - "_atexit" => Function::new_native(ctx, crate::emscripten_target::_atexit), - "setTempRet0" => Function::new_native(ctx, crate::emscripten_target::setTempRet0), - "getTempRet0" => Function::new_native(ctx, crate::emscripten_target::getTempRet0), - "invoke_i" => Function::new_native(ctx, crate::emscripten_target::invoke_i), - "invoke_ii" => Function::new_native(ctx, crate::emscripten_target::invoke_ii), - "invoke_iii" => Function::new_native(ctx, crate::emscripten_target::invoke_iii), - "invoke_iiii" => Function::new_native(ctx, crate::emscripten_target::invoke_iiii), - "invoke_iifi" => Function::new_native(ctx, crate::emscripten_target::invoke_iifi), - "invoke_v" => Function::new_native(ctx, crate::emscripten_target::invoke_v), - "invoke_vi" => Function::new_native(ctx, crate::emscripten_target::invoke_vi), - "invoke_vj" => Function::new_native(ctx, crate::emscripten_target::invoke_vj), - "invoke_vjji" => Function::new_native(ctx, crate::emscripten_target::invoke_vjji), - "invoke_vii" => Function::new_native(ctx, crate::emscripten_target::invoke_vii), - "invoke_viii" => Function::new_native(ctx, crate::emscripten_target::invoke_viii), - "invoke_viiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiii), - "__Unwind_Backtrace" => Function::new_native(ctx, crate::emscripten_target::__Unwind_Backtrace), - "__Unwind_FindEnclosingFunction" => Function::new_native(ctx, crate::emscripten_target::__Unwind_FindEnclosingFunction), - "__Unwind_GetIPInfo" => Function::new_native(ctx, crate::emscripten_target::__Unwind_GetIPInfo), - "___cxa_find_matching_catch_2" => Function::new_native(ctx, crate::emscripten_target::___cxa_find_matching_catch_2), - "___cxa_find_matching_catch_3" => Function::new_native(ctx, crate::emscripten_target::___cxa_find_matching_catch_3), - "___cxa_free_exception" => Function::new_native(ctx, crate::emscripten_target::___cxa_free_exception), - "___resumeException" => Function::new_native(ctx, crate::emscripten_target::___resumeException), - "_dladdr" => Function::new_native(ctx, crate::emscripten_target::_dladdr), - "_pthread_attr_destroy" => Function::new_native(ctx, crate::pthread::_pthread_attr_destroy), - "_pthread_attr_getstack" => Function::new_native(ctx, crate::pthread::_pthread_attr_getstack), - "_pthread_attr_init" => Function::new_native(ctx, crate::pthread::_pthread_attr_init), - "_pthread_attr_setstacksize" => Function::new_native(ctx, crate::pthread::_pthread_attr_setstacksize), - "_pthread_cleanup_pop" => Function::new_native(ctx, crate::pthread::_pthread_cleanup_pop), - "_pthread_cleanup_push" => Function::new_native(ctx, crate::pthread::_pthread_cleanup_push), - "_pthread_cond_destroy" => Function::new_native(ctx, crate::pthread::_pthread_cond_destroy), - "_pthread_cond_init" => Function::new_native(ctx, crate::pthread::_pthread_cond_init), - "_pthread_cond_signal" => Function::new_native(ctx, crate::pthread::_pthread_cond_signal), - "_pthread_cond_timedwait" => Function::new_native(ctx, crate::pthread::_pthread_cond_timedwait), - "_pthread_cond_wait" => Function::new_native(ctx, crate::pthread::_pthread_cond_wait), - "_pthread_condattr_destroy" => Function::new_native(ctx, crate::pthread::_pthread_condattr_destroy), - "_pthread_condattr_init" => Function::new_native(ctx, crate::pthread::_pthread_condattr_init), - "_pthread_condattr_setclock" => Function::new_native(ctx, crate::pthread::_pthread_condattr_setclock), - "_pthread_create" => Function::new_native(ctx, crate::pthread::_pthread_create), - "_pthread_detach" => Function::new_native(ctx, crate::pthread::_pthread_detach), - "_pthread_equal" => Function::new_native(ctx, crate::pthread::_pthread_equal), - "_pthread_exit" => Function::new_native(ctx, crate::pthread::_pthread_exit), - "_pthread_self" => Function::new_native(ctx, crate::pthread::_pthread_self), - "_pthread_getattr_np" => Function::new_native(ctx, crate::pthread::_pthread_getattr_np), - "_pthread_getspecific" => Function::new_native(ctx, crate::pthread::_pthread_getspecific), - "_pthread_join" => Function::new_native(ctx, crate::pthread::_pthread_join), - "_pthread_key_create" => Function::new_native(ctx, crate::pthread::_pthread_key_create), - "_pthread_mutex_destroy" => Function::new_native(ctx, crate::pthread::_pthread_mutex_destroy), - "_pthread_mutex_init" => Function::new_native(ctx, crate::pthread::_pthread_mutex_init), - "_pthread_mutexattr_destroy" => Function::new_native(ctx, crate::pthread::_pthread_mutexattr_destroy), - "_pthread_mutexattr_init" => Function::new_native(ctx, crate::pthread::_pthread_mutexattr_init), - "_pthread_mutexattr_settype" => Function::new_native(ctx, crate::pthread::_pthread_mutexattr_settype), - "_pthread_once" => Function::new_native(ctx, crate::pthread::_pthread_once), - "_pthread_rwlock_destroy" => Function::new_native(ctx, crate::pthread::_pthread_rwlock_destroy), - "_pthread_rwlock_init" => Function::new_native(ctx, crate::pthread::_pthread_rwlock_init), - "_pthread_rwlock_rdlock" => Function::new_native(ctx, crate::pthread::_pthread_rwlock_rdlock), - "_pthread_rwlock_unlock" => Function::new_native(ctx, crate::pthread::_pthread_rwlock_unlock), - "_pthread_rwlock_wrlock" => Function::new_native(ctx, crate::pthread::_pthread_rwlock_wrlock), - "_pthread_setcancelstate" => Function::new_native(ctx, crate::pthread::_pthread_setcancelstate), - "_pthread_setspecific" => Function::new_native(ctx, crate::pthread::_pthread_setspecific), - "_pthread_sigmask" => Function::new_native(ctx, crate::pthread::_pthread_sigmask), - "___gxx_personality_v0" => Function::new_native(ctx, crate::emscripten_target::___gxx_personality_v0), - "_gai_strerror" => Function::new_native(ctx, crate::env::_gai_strerror), - "_getdtablesize" => Function::new_native(ctx, crate::emscripten_target::_getdtablesize), - "_gethostbyaddr" => Function::new_native(ctx, crate::emscripten_target::_gethostbyaddr), - "_gethostbyname" => Function::new_native(ctx, crate::emscripten_target::_gethostbyname), - "_gethostbyname_r" => Function::new_native(ctx, crate::emscripten_target::_gethostbyname_r), - "_getloadavg" => Function::new_native(ctx, crate::emscripten_target::_getloadavg), - "_getnameinfo" => Function::new_native(ctx, crate::emscripten_target::_getnameinfo), - "invoke_dii" => Function::new_native(ctx, crate::emscripten_target::invoke_dii), - "invoke_diiii" => Function::new_native(ctx, crate::emscripten_target::invoke_diiii), - "invoke_iiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_iiiii), - "invoke_iiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_iiiiii), - "invoke_iiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_iiiiiii), - "invoke_iiiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_iiiiiiii), - "invoke_iiiiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_iiiiiiiii), - "invoke_iiiiiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_iiiiiiiiii), - "invoke_iiiiiiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_iiiiiiiiiii), - "invoke_vd" => Function::new_native(ctx, crate::emscripten_target::invoke_vd), - "invoke_viiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiiii), - "invoke_viiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiiiii), - "invoke_viiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiiiiii), - "invoke_viiiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiiiiiii), - "invoke_viiiiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiiiiiiii), - "invoke_viiiiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiiiiiiii), - "invoke_viiiiiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiiiiiiiii), - "invoke_iij" => Function::new_native(ctx, crate::emscripten_target::invoke_iij), - "invoke_iji" => Function::new_native(ctx, crate::emscripten_target::invoke_iji), - "invoke_iiji" => Function::new_native(ctx, crate::emscripten_target::invoke_iiji), - "invoke_iiijj" => Function::new_native(ctx, crate::emscripten_target::invoke_iiijj), - "invoke_j" => Function::new_native(ctx, crate::emscripten_target::invoke_j), - "invoke_ji" => Function::new_native(ctx, crate::emscripten_target::invoke_ji), - "invoke_jii" => Function::new_native(ctx, crate::emscripten_target::invoke_jii), - "invoke_jij" => Function::new_native(ctx, crate::emscripten_target::invoke_jij), - "invoke_jjj" => Function::new_native(ctx, crate::emscripten_target::invoke_jjj), - "invoke_viiij" => Function::new_native(ctx, crate::emscripten_target::invoke_viiij), - "invoke_viiijiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiijiiii), - "invoke_viiijiiiiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viiijiiiiii), - "invoke_viij" => Function::new_native(ctx, crate::emscripten_target::invoke_viij), - "invoke_viiji" => Function::new_native(ctx, crate::emscripten_target::invoke_viiji), - "invoke_viijiii" => Function::new_native(ctx, crate::emscripten_target::invoke_viijiii), - "invoke_viijj" => Function::new_native(ctx, crate::emscripten_target::invoke_viijj), - "invoke_vij" => Function::new_native(ctx, crate::emscripten_target::invoke_vij), - "invoke_viji" => Function::new_native(ctx, crate::emscripten_target::invoke_viji), - "invoke_vijiii" => Function::new_native(ctx, crate::emscripten_target::invoke_vijiii), - "invoke_vijj" => Function::new_native(ctx, crate::emscripten_target::invoke_vijj), - "invoke_vidd" => Function::new_native(ctx, crate::emscripten_target::invoke_vidd), - "invoke_viid" => Function::new_native(ctx, crate::emscripten_target::invoke_viid), - "invoke_viidii" => Function::new_native(ctx, crate::emscripten_target::invoke_viidii), - "invoke_viidddddddd" => Function::new_native(ctx, crate::emscripten_target::invoke_viidddddddd), + "_alarm" => Function::new_native(&mut store, ctx, crate::emscripten_target::_alarm), + "_atexit" => Function::new_native(&mut store, ctx, crate::emscripten_target::_atexit), + "setTempRet0" => Function::new_native(&mut store, ctx, crate::emscripten_target::setTempRet0), + "getTempRet0" => Function::new_native(&mut store, ctx, crate::emscripten_target::getTempRet0), + "invoke_i" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_i), + "invoke_ii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_ii), + "invoke_iii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iii), + "invoke_iiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiii), + "invoke_iifi" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iifi), + "invoke_v" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_v), + "invoke_vi" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vi), + "invoke_vj" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vj), + "invoke_vjji" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vjji), + "invoke_vii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vii), + "invoke_viii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viii), + "invoke_viiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiii), + "__Unwind_Backtrace" => Function::new_native(&mut store, ctx, crate::emscripten_target::__Unwind_Backtrace), + "__Unwind_FindEnclosingFunction" => Function::new_native(&mut store, ctx, crate::emscripten_target::__Unwind_FindEnclosingFunction), + "__Unwind_GetIPInfo" => Function::new_native(&mut store, ctx, crate::emscripten_target::__Unwind_GetIPInfo), + "___cxa_find_matching_catch_2" => Function::new_native(&mut store, ctx, crate::emscripten_target::___cxa_find_matching_catch_2), + "___cxa_find_matching_catch_3" => Function::new_native(&mut store, ctx, crate::emscripten_target::___cxa_find_matching_catch_3), + "___cxa_free_exception" => Function::new_native(&mut store, ctx, crate::emscripten_target::___cxa_free_exception), + "___resumeException" => Function::new_native(&mut store, ctx, crate::emscripten_target::___resumeException), + "_dladdr" => Function::new_native(&mut store, ctx, crate::emscripten_target::_dladdr), + "_pthread_attr_destroy" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_attr_destroy), + "_pthread_attr_getstack" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_attr_getstack), + "_pthread_attr_init" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_attr_init), + "_pthread_attr_setstacksize" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_attr_setstacksize), + "_pthread_cleanup_pop" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_cleanup_pop), + "_pthread_cleanup_push" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_cleanup_push), + "_pthread_cond_destroy" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_cond_destroy), + "_pthread_cond_init" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_cond_init), + "_pthread_cond_signal" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_cond_signal), + "_pthread_cond_timedwait" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_cond_timedwait), + "_pthread_cond_wait" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_cond_wait), + "_pthread_condattr_destroy" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_condattr_destroy), + "_pthread_condattr_init" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_condattr_init), + "_pthread_condattr_setclock" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_condattr_setclock), + "_pthread_create" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_create), + "_pthread_detach" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_detach), + "_pthread_equal" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_equal), + "_pthread_exit" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_exit), + "_pthread_self" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_self), + "_pthread_getattr_np" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_getattr_np), + "_pthread_getspecific" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_getspecific), + "_pthread_join" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_join), + "_pthread_key_create" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_key_create), + "_pthread_mutex_destroy" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_mutex_destroy), + "_pthread_mutex_init" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_mutex_init), + "_pthread_mutexattr_destroy" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_mutexattr_destroy), + "_pthread_mutexattr_init" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_mutexattr_init), + "_pthread_mutexattr_settype" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_mutexattr_settype), + "_pthread_once" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_once), + "_pthread_rwlock_destroy" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_rwlock_destroy), + "_pthread_rwlock_init" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_rwlock_init), + "_pthread_rwlock_rdlock" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_rwlock_rdlock), + "_pthread_rwlock_unlock" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_rwlock_unlock), + "_pthread_rwlock_wrlock" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_rwlock_wrlock), + "_pthread_setcancelstate" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_setcancelstate), + "_pthread_setspecific" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_setspecific), + "_pthread_sigmask" => Function::new_native(&mut store, ctx, crate::pthread::_pthread_sigmask), + "___gxx_personality_v0" => Function::new_native(&mut store, ctx, crate::emscripten_target::___gxx_personality_v0), + "_gai_strerror" => Function::new_native(&mut store, ctx, crate::env::_gai_strerror), + "_getdtablesize" => Function::new_native(&mut store, ctx, crate::emscripten_target::_getdtablesize), + "_gethostbyaddr" => Function::new_native(&mut store, ctx, crate::emscripten_target::_gethostbyaddr), + "_gethostbyname" => Function::new_native(&mut store, ctx, crate::emscripten_target::_gethostbyname), + "_gethostbyname_r" => Function::new_native(&mut store, ctx, crate::emscripten_target::_gethostbyname_r), + "_getloadavg" => Function::new_native(&mut store, ctx, crate::emscripten_target::_getloadavg), + "_getnameinfo" => Function::new_native(&mut store, ctx, crate::emscripten_target::_getnameinfo), + "invoke_dii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_dii), + "invoke_diiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_diiii), + "invoke_iiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiiii), + "invoke_iiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiiiii), + "invoke_iiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiiiiii), + "invoke_iiiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiiiiiii), + "invoke_iiiiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiiiiiiii), + "invoke_iiiiiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiiiiiiiii), + "invoke_iiiiiiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiiiiiiiiii), + "invoke_vd" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vd), + "invoke_viiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiiii), + "invoke_viiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiiiii), + "invoke_viiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiiiiii), + "invoke_viiiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiiiiiii), + "invoke_viiiiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiiiiiiii), + "invoke_viiiiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiiiiiiii), + "invoke_viiiiiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiiiiiiiii), + "invoke_iij" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iij), + "invoke_iji" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iji), + "invoke_iiji" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiji), + "invoke_iiijj" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_iiijj), + "invoke_j" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_j), + "invoke_ji" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_ji), + "invoke_jii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_jii), + "invoke_jij" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_jij), + "invoke_jjj" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_jjj), + "invoke_viiij" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiij), + "invoke_viiijiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiijiiii), + "invoke_viiijiiiiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiijiiiiii), + "invoke_viij" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viij), + "invoke_viiji" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viiji), + "invoke_viijiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viijiii), + "invoke_viijj" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viijj), + "invoke_vij" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vij), + "invoke_viji" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viji), + "invoke_vijiii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vijiii), + "invoke_vijj" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vijj), + "invoke_vidd" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_vidd), + "invoke_viid" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viid), + "invoke_viidii" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viidii), + "invoke_viidddddddd" => Function::new_native(&mut store, ctx, crate::emscripten_target::invoke_viidddddddd), // ucontext - "_getcontext" => Function::new_native(ctx, crate::ucontext::_getcontext), - "_makecontext" => Function::new_native(ctx, crate::ucontext::_makecontext), - "_setcontext" => Function::new_native(ctx, crate::ucontext::_setcontext), - "_swapcontext" => Function::new_native(ctx, crate::ucontext::_swapcontext), + "_getcontext" => Function::new_native(&mut store, ctx, crate::ucontext::_getcontext), + "_makecontext" => Function::new_native(&mut store, ctx, crate::ucontext::_makecontext), + "_setcontext" => Function::new_native(&mut store, ctx, crate::ucontext::_setcontext), + "_swapcontext" => Function::new_native(&mut store, ctx, crate::ucontext::_swapcontext), // unistd - "_confstr" => Function::new_native(ctx, crate::unistd::confstr), + "_confstr" => Function::new_native(&mut store, ctx, crate::unistd::confstr), }; // Compatibility with newer versions of Emscripten @@ -1434,31 +1441,31 @@ pub fn generate_emscripten_env( for null_function_name in globals.null_function_names.iter() { env_ns.insert( null_function_name.as_str(), - Function::new_native(ctx, nullfunc), + Function::new_native(&mut store, ctx, nullfunc), ); } let import_object: Imports = imports! { "env" => env_ns, "global" => { - "NaN" => Global::new(ctx, Value::F64(f64::NAN)), - "Infinity" => Global::new(ctx, Value::F64(f64::INFINITY)), + "NaN" => Global::new(&mut store, Value::F64(f64::NAN)), + "Infinity" => Global::new(&mut store, Value::F64(f64::INFINITY)), }, "global.Math" => { - "pow" => Function::new_native(ctx, crate::math::pow), - "exp" => Function::new_native(ctx, crate::math::exp), - "log" => Function::new_native(ctx, crate::math::log), + "pow" => Function::new_native(&mut store, ctx, crate::math::pow), + "exp" => Function::new_native(&mut store, ctx, crate::math::exp), + "log" => Function::new_native(&mut store, ctx, crate::math::log), }, "asm2wasm" => { - "f64-rem" => Function::new_native(ctx, crate::math::f64_rem), - "f64-to-int" => Function::new_native(ctx, crate::math::f64_to_int), + "f64-rem" => Function::new_native(&mut store, ctx, crate::math::f64_rem), + "f64-to-int" => Function::new_native(&mut store, ctx, crate::math::f64_to_int), }, }; import_object } -pub fn nullfunc(ctx: ContextMut<'_, EmEnv>, _x: u32) { +pub fn nullfunc(ctx: FunctionEnvMut, _x: u32) { use crate::process::abort_with_message; debug!("emscripten::nullfunc_i {}", _x); abort_with_message( diff --git a/lib/emscripten/src/libc.rs b/lib/emscripten/src/libc.rs index 3916a553b48..52ef2effcd5 100644 --- a/lib/emscripten/src/libc.rs +++ b/lib/emscripten/src/libc.rs @@ -1,77 +1,77 @@ extern crate libc; use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; #[cfg(unix)] use std::convert::TryInto; -pub fn current_sigrtmax(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn current_sigrtmax(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::current_sigrtmax"); 0 } -pub fn current_sigrtmin(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn current_sigrtmin(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::current_sigrtmin"); 0 } -pub fn endpwent(_ctx: ContextMut<'_, EmEnv>) { +pub fn endpwent(_ctx: FunctionEnvMut) { debug!("emscripten::endpwent"); } -pub fn execv(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn execv(_ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::execv"); 0 } -pub fn fexecve(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32, _c: i32) -> i32 { +pub fn fexecve(_ctx: FunctionEnvMut, _a: i32, _b: i32, _c: i32) -> i32 { debug!("emscripten::fexecve"); 0 } -pub fn fpathconf(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn fpathconf(_ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::fpathconf"); 0 } -pub fn getitimer(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn getitimer(_ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::getitimer"); 0 } -pub fn getpwent(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn getpwent(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::getpwent"); 0 } -pub fn killpg(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn killpg(_ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::killpg"); 0 } #[cfg(unix)] -pub fn pathconf(ctx: ContextMut<'_, EmEnv>, path_ptr: i32, name: i32) -> i32 { +pub fn pathconf(ctx: FunctionEnvMut, path_ptr: i32, name: i32) -> i32 { debug!("emscripten::pathconf"); let path = emscripten_memory_pointer!(ctx, ctx.data().memory(0), path_ptr) as *const i8; unsafe { libc::pathconf(path as *const _, name).try_into().unwrap() } } #[cfg(not(unix))] -pub fn pathconf(_ctx: ContextMut<'_, EmEnv>, _path_ptr: i32, _name: i32) -> i32 { +pub fn pathconf(_ctx: FunctionEnvMut, _path_ptr: i32, _name: i32) -> i32 { debug!("emscripten::pathconf"); 0 } -pub fn setpwent(_ctx: ContextMut<'_, EmEnv>) { +pub fn setpwent(_ctx: FunctionEnvMut) { debug!("emscripten::setpwent"); } -pub fn sigismember(_ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn sigismember(_ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::sigismember"); 0 } -pub fn sigpending(_ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn sigpending(_ctx: FunctionEnvMut, _a: i32) -> i32 { debug!("emscripten::sigpending"); 0 } diff --git a/lib/emscripten/src/linking.rs b/lib/emscripten/src/linking.rs index 585c2e46c8a..83e39c4404c 100644 --- a/lib/emscripten/src/linking.rs +++ b/lib/emscripten/src/linking.rs @@ -1,28 +1,28 @@ use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; // TODO: Need to implement. /// emscripten: dlopen(filename: *const c_char, flag: c_int) -> *mut c_void -pub fn _dlopen(mut _ctx: ContextMut<'_, EmEnv>, _filename: u32, _flag: u32) -> i32 { +pub fn _dlopen(mut _ctx: FunctionEnvMut, _filename: u32, _flag: u32) -> i32 { debug!("emscripten::_dlopen"); -1 } /// emscripten: dlclose(handle: *mut c_void) -> c_int -pub fn _dlclose(mut _ctx: ContextMut<'_, EmEnv>, _filename: u32) -> i32 { +pub fn _dlclose(mut _ctx: FunctionEnvMut, _filename: u32) -> i32 { debug!("emscripten::_dlclose"); -1 } /// emscripten: dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void -pub fn _dlsym(mut _ctx: ContextMut<'_, EmEnv>, _filepath: u32, _symbol: u32) -> i32 { +pub fn _dlsym(mut _ctx: FunctionEnvMut, _filepath: u32, _symbol: u32) -> i32 { debug!("emscripten::_dlsym"); -1 } /// emscripten: dlerror() -> *mut c_char -pub fn _dlerror(mut _ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn _dlerror(mut _ctx: FunctionEnvMut) -> i32 { debug!("emscripten::_dlerror"); -1 } diff --git a/lib/emscripten/src/lock.rs b/lib/emscripten/src/lock.rs index 118ff9d5a28..ce905d3e759 100644 --- a/lib/emscripten/src/lock.rs +++ b/lib/emscripten/src/lock.rs @@ -1,20 +1,20 @@ use crate::EmEnv; use libc::c_int; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; // NOTE: Not implemented by Emscripten -pub fn ___lock(mut _ctx: ContextMut<'_, EmEnv>, _what: c_int) { +pub fn ___lock(mut _ctx: FunctionEnvMut, _what: c_int) { debug!("emscripten::___lock {}", _what); } // NOTE: Not implemented by Emscripten -pub fn ___unlock(mut _ctx: ContextMut<'_, EmEnv>, _what: c_int) { +pub fn ___unlock(mut _ctx: FunctionEnvMut, _what: c_int) { debug!("emscripten::___unlock {}", _what); } // NOTE: Not implemented by Emscripten pub fn ___wait( - mut _ctx: ContextMut<'_, EmEnv>, + mut _ctx: FunctionEnvMut, _which: u32, _varargs: u32, _three: u32, @@ -23,7 +23,7 @@ pub fn ___wait( debug!("emscripten::___wait"); } -pub fn _flock(mut _ctx: ContextMut<'_, EmEnv>, _fd: u32, _op: u32) -> u32 { +pub fn _flock(mut _ctx: FunctionEnvMut, _fd: u32, _op: u32) -> u32 { debug!("emscripten::_flock"); 0 } diff --git a/lib/emscripten/src/math.rs b/lib/emscripten/src/math.rs index 896bc3d38f0..1940b7edbeb 100644 --- a/lib/emscripten/src/math.rs +++ b/lib/emscripten/src/math.rs @@ -1,111 +1,111 @@ use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; -pub fn _llvm_copysign_f32(mut _ctx: ContextMut<'_, EmEnv>, x: f64, y: f64) -> f64 { +pub fn _llvm_copysign_f32(mut _ctx: FunctionEnvMut, x: f64, y: f64) -> f64 { x.copysign(y) } -pub fn _llvm_copysign_f64(mut _ctx: ContextMut<'_, EmEnv>, x: f64, y: f64) -> f64 { +pub fn _llvm_copysign_f64(mut _ctx: FunctionEnvMut, x: f64, y: f64) -> f64 { x.copysign(y) } /// emscripten: _llvm_log10_f64 -pub fn _llvm_log10_f64(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn _llvm_log10_f64(mut _ctx: FunctionEnvMut, value: f64) -> f64 { debug!("emscripten::_llvm_log10_f64"); value.log10() } /// emscripten: _llvm_log2_f64 -pub fn _llvm_log2_f64(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn _llvm_log2_f64(mut _ctx: FunctionEnvMut, value: f64) -> f64 { debug!("emscripten::_llvm_log2_f64"); value.log2() } /// emscripten: _llvm_sin_f64 -pub fn _llvm_sin_f64(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn _llvm_sin_f64(mut _ctx: FunctionEnvMut, value: f64) -> f64 { debug!("emscripten::_llvm_sin_f64"); value.sin() } /// emscripten: _llvm_cos_f64 -pub fn _llvm_cos_f64(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn _llvm_cos_f64(mut _ctx: FunctionEnvMut, value: f64) -> f64 { debug!("emscripten::_llvm_cos_f64"); value.cos() } -pub fn _llvm_log10_f32(mut _ctx: ContextMut<'_, EmEnv>, _value: f64) -> f64 { +pub fn _llvm_log10_f32(mut _ctx: FunctionEnvMut, _value: f64) -> f64 { debug!("emscripten::_llvm_log10_f32"); -1.0 } -pub fn _llvm_log2_f32(mut _ctx: ContextMut<'_, EmEnv>, _value: f64) -> f64 { +pub fn _llvm_log2_f32(mut _ctx: FunctionEnvMut, _value: f64) -> f64 { debug!("emscripten::_llvm_log10_f32"); -1.0 } -pub fn _llvm_exp2_f32(mut _ctx: ContextMut<'_, EmEnv>, value: f32) -> f32 { +pub fn _llvm_exp2_f32(mut _ctx: FunctionEnvMut, value: f32) -> f32 { debug!("emscripten::_llvm_exp2_f32"); 2f32.powf(value) } -pub fn _llvm_exp2_f64(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn _llvm_exp2_f64(mut _ctx: FunctionEnvMut, value: f64) -> f64 { debug!("emscripten::_llvm_exp2_f64"); 2f64.powf(value) } -pub fn _llvm_trunc_f64(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn _llvm_trunc_f64(mut _ctx: FunctionEnvMut, value: f64) -> f64 { debug!("emscripten::_llvm_trunc_f64"); value.trunc() } -pub fn _llvm_fma_f64(mut _ctx: ContextMut<'_, EmEnv>, value: f64, a: f64, b: f64) -> f64 { +pub fn _llvm_fma_f64(mut _ctx: FunctionEnvMut, value: f64, a: f64, b: f64) -> f64 { debug!("emscripten::_llvm_fma_f64"); value.mul_add(a, b) } -pub fn _emscripten_random(mut _ctx: ContextMut<'_, EmEnv>) -> f64 { +pub fn _emscripten_random(mut _ctx: FunctionEnvMut) -> f64 { debug!("emscripten::_emscripten_random"); -1.0 } // emscripten: asm2wasm.f64-rem -pub fn f64_rem(mut _ctx: ContextMut<'_, EmEnv>, x: f64, y: f64) -> f64 { +pub fn f64_rem(mut _ctx: FunctionEnvMut, x: f64, y: f64) -> f64 { debug!("emscripten::f64-rem"); x % y } // emscripten: global.Math pow -pub fn pow(mut _ctx: ContextMut<'_, EmEnv>, x: f64, y: f64) -> f64 { +pub fn pow(mut _ctx: FunctionEnvMut, x: f64, y: f64) -> f64 { x.powf(y) } // emscripten: global.Math exp -pub fn exp(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn exp(mut _ctx: FunctionEnvMut, value: f64) -> f64 { value.exp() } // emscripten: global.Math log -pub fn log(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn log(mut _ctx: FunctionEnvMut, value: f64) -> f64 { value.ln() } // emscripten: global.Math sqrt -pub fn sqrt(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn sqrt(mut _ctx: FunctionEnvMut, value: f64) -> f64 { value.sqrt() } // emscripten: global.Math floor -pub fn floor(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn floor(mut _ctx: FunctionEnvMut, value: f64) -> f64 { value.floor() } // emscripten: global.Math fabs -pub fn fabs(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> f64 { +pub fn fabs(mut _ctx: FunctionEnvMut, value: f64) -> f64 { value.abs() } // emscripten: asm2wasm.f64-to-int -pub fn f64_to_int(mut _ctx: ContextMut<'_, EmEnv>, value: f64) -> i32 { +pub fn f64_to_int(mut _ctx: FunctionEnvMut, value: f64) -> i32 { debug!("emscripten::f64_to_int {}", value); value as i32 } diff --git a/lib/emscripten/src/memory.rs b/lib/emscripten/src/memory.rs index 065aaaec429..e3fe43a2db8 100644 --- a/lib/emscripten/src/memory.rs +++ b/lib/emscripten/src/memory.rs @@ -3,12 +3,10 @@ use super::process::abort_with_message; use crate::EmEnv; use libc::{c_int, c_void, memcpy, size_t}; // TODO: investigate max pages etc. probably in Wasm Common, maybe reexport -use wasmer::{ - AsContextMut, ContextMut, Pages, WasmPtr, WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE, -}; +use wasmer::{FunctionEnvMut, Pages, WasmPtr, WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE}; /// emscripten: _emscripten_memcpy_big -pub fn _emscripten_memcpy_big(ctx: ContextMut<'_, EmEnv>, dest: u32, src: u32, len: u32) -> u32 { +pub fn _emscripten_memcpy_big(ctx: FunctionEnvMut, dest: u32, src: u32, len: u32) -> u32 { debug!( "emscripten::_emscripten_memcpy_big {}, {}, {}", dest, src, len @@ -21,12 +19,12 @@ pub fn _emscripten_memcpy_big(ctx: ContextMut<'_, EmEnv>, dest: u32, src: u32, l dest } -fn get_heap_size(ctx: &ContextMut<'_, EmEnv>) -> u32 { +fn get_heap_size(ctx: &FunctionEnvMut) -> u32 { ctx.data().memory(0).size(&ctx).bytes().0 as u32 } /// emscripten: _emscripten_get_heap_size -pub fn _emscripten_get_heap_size(ctx: ContextMut<'_, EmEnv>) -> u32 { +pub fn _emscripten_get_heap_size(ctx: FunctionEnvMut) -> u32 { trace!("emscripten::_emscripten_get_heap_size"); let result = get_heap_size(&ctx); trace!("=> {}", result); @@ -42,7 +40,7 @@ fn align_up(mut val: usize, multiple: usize) -> usize { val } -fn resize_heap(ctx: &mut ContextMut<'_, EmEnv>, requested_size: u32) -> u32 { +fn resize_heap(ctx: &mut FunctionEnvMut, requested_size: u32) -> u32 { debug!("emscripten::_emscripten_resize_heap {}", requested_size); let current_memory_pages = ctx.data().memory(0).size(&ctx); let current_memory = current_memory_pages.bytes().0 as u32; @@ -67,7 +65,7 @@ fn resize_heap(ctx: &mut ContextMut<'_, EmEnv>, requested_size: u32) -> u32 { if let Ok(_pages_allocated) = ctx .data() .memory(0) - .grow(&mut ctx.as_context_mut(), Pages(amount_to_grow as u32)) + .grow(&mut ctx.as_mut(), Pages(amount_to_grow as u32)) { debug!("{} pages allocated", _pages_allocated.0); 1 @@ -78,12 +76,12 @@ fn resize_heap(ctx: &mut ContextMut<'_, EmEnv>, requested_size: u32) -> u32 { /// emscripten: _emscripten_resize_heap /// Note: this function only allows growing the size of heap -pub fn _emscripten_resize_heap(mut ctx: ContextMut<'_, EmEnv>, requested_size: u32) -> u32 { +pub fn _emscripten_resize_heap(mut ctx: FunctionEnvMut, requested_size: u32) -> u32 { resize_heap(&mut ctx, requested_size) } /// emscripten: sbrk -pub fn sbrk(mut ctx: ContextMut<'_, EmEnv>, increment: i32) -> i32 { +pub fn sbrk(mut ctx: FunctionEnvMut, increment: i32) -> i32 { debug!("emscripten::sbrk"); // let old_dynamic_top = 0; // let new_dynamic_top = 0; @@ -122,7 +120,7 @@ pub fn sbrk(mut ctx: ContextMut<'_, EmEnv>, increment: i32) -> i32 { } /// emscripten: getTotalMemory -pub fn get_total_memory(ctx: ContextMut<'_, EmEnv>) -> u32 { +pub fn get_total_memory(ctx: FunctionEnvMut) -> u32 { debug!("emscripten::get_total_memory"); // instance.memories[0].current_pages() // TODO: Fix implementation @@ -130,7 +128,7 @@ pub fn get_total_memory(ctx: ContextMut<'_, EmEnv>) -> u32 { } /// emscripten: enlargeMemory -pub fn enlarge_memory(_ctx: ContextMut<'_, EmEnv>) -> u32 { +pub fn enlarge_memory(_ctx: FunctionEnvMut) -> u32 { debug!("emscripten::enlarge_memory"); // instance.memories[0].grow(100); // TODO: Fix implementation @@ -138,7 +136,7 @@ pub fn enlarge_memory(_ctx: ContextMut<'_, EmEnv>) -> u32 { } /// emscripten: abortOnCannotGrowMemory -pub fn abort_on_cannot_grow_memory(ctx: ContextMut<'_, EmEnv>, _requested_size: u32) -> u32 { +pub fn abort_on_cannot_grow_memory(ctx: FunctionEnvMut, _requested_size: u32) -> u32 { debug!( "emscripten::abort_on_cannot_grow_memory {}", _requested_size @@ -148,32 +146,32 @@ pub fn abort_on_cannot_grow_memory(ctx: ContextMut<'_, EmEnv>, _requested_size: } /// emscripten: abortOnCannotGrowMemory -pub fn abort_on_cannot_grow_memory_old(ctx: ContextMut<'_, EmEnv>) -> u32 { +pub fn abort_on_cannot_grow_memory_old(ctx: FunctionEnvMut) -> u32 { debug!("emscripten::abort_on_cannot_grow_memory"); abort_with_message(ctx, "Cannot enlarge memory arrays!"); 0 } /// emscripten: segfault -pub fn segfault(ctx: ContextMut<'_, EmEnv>) { +pub fn segfault(ctx: FunctionEnvMut) { debug!("emscripten::segfault"); abort_with_message(ctx, "segmentation fault"); } /// emscripten: alignfault -pub fn alignfault(ctx: ContextMut<'_, EmEnv>) { +pub fn alignfault(ctx: FunctionEnvMut) { debug!("emscripten::alignfault"); abort_with_message(ctx, "alignment fault"); } /// emscripten: ftfault -pub fn ftfault(ctx: ContextMut<'_, EmEnv>) { +pub fn ftfault(ctx: FunctionEnvMut) { debug!("emscripten::ftfault"); abort_with_message(ctx, "Function table mask error"); } /// emscripten: ___map_file -pub fn ___map_file(_ctx: ContextMut<'_, EmEnv>, _one: u32, _two: u32) -> c_int { +pub fn ___map_file(_ctx: FunctionEnvMut, _one: u32, _two: u32) -> c_int { debug!("emscripten::___map_file"); // NOTE: TODO: Em returns -1 here as well. May need to implement properly -1 diff --git a/lib/emscripten/src/process.rs b/lib/emscripten/src/process.rs index 665a5fb9b10..9156f2f2c32 100644 --- a/lib/emscripten/src/process.rs +++ b/lib/emscripten/src/process.rs @@ -6,35 +6,35 @@ type PidT = libc::pid_t; type PidT = c_int; use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; -pub fn abort_with_message(ctx: ContextMut<'_, EmEnv>, message: &str) { +pub fn abort_with_message(ctx: FunctionEnvMut, message: &str) { debug!("emscripten::abort_with_message"); println!("{}", message); _abort(ctx); } /// The name of this call is `abort` but we want to avoid conflicts with libc::abort -pub fn em_abort(ctx: ContextMut<'_, EmEnv>, arg: u32) { +pub fn em_abort(ctx: FunctionEnvMut, arg: u32) { debug!("emscripten::abort"); eprintln!("Program aborted with value {}", arg); _abort(ctx); } -pub fn _abort(_ctx: ContextMut<'_, EmEnv>) { +pub fn _abort(_ctx: FunctionEnvMut) { debug!("emscripten::_abort"); unsafe { abort(); } } -pub fn _prctl(ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _prctl(ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { debug!("emscripten::_prctl"); abort_with_message(ctx, "missing function: prctl"); -1 } -pub fn _fork(_ctx: ContextMut<'_, EmEnv>) -> PidT { +pub fn _fork(_ctx: FunctionEnvMut) -> PidT { debug!("emscripten::_fork"); // unsafe { // fork() @@ -42,132 +42,132 @@ pub fn _fork(_ctx: ContextMut<'_, EmEnv>) -> PidT { -1 } -pub fn _endgrent(_ctx: ContextMut<'_, EmEnv>) { +pub fn _endgrent(_ctx: FunctionEnvMut) { debug!("emscripten::_endgrent"); } -pub fn _execve(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32) -> i32 { +pub fn _execve(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32) -> i32 { debug!("emscripten::_execve"); -1 } #[allow(unreachable_code)] -pub fn _exit(_ctx: ContextMut<'_, EmEnv>, status: c_int) { +pub fn _exit(_ctx: FunctionEnvMut, status: c_int) { // -> ! debug!("emscripten::_exit {}", status); unsafe { exit(status) } } -pub fn _kill(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn _kill(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::_kill"); -1 } -pub fn _sched_yield(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn _sched_yield(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::_sched_yield"); -1 } -pub fn _llvm_stacksave(_ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn _llvm_stacksave(_ctx: FunctionEnvMut) -> i32 { debug!("emscripten::_llvm_stacksave"); -1 } -pub fn _llvm_stackrestore(_ctx: ContextMut<'_, EmEnv>, _one: i32) { +pub fn _llvm_stackrestore(_ctx: FunctionEnvMut, _one: i32) { debug!("emscripten::_llvm_stackrestore"); } -pub fn _raise(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _raise(_ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_raise"); -1 } -pub fn _sem_init(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32) -> i32 { +pub fn _sem_init(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32) -> i32 { debug!("emscripten::_sem_init: {}, {}, {}", _one, _two, _three); 0 } -pub fn _sem_destroy(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _sem_destroy(_ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_sem_destroy"); 0 } -pub fn _sem_post(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _sem_post(_ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_sem_post"); -1 } -pub fn _sem_wait(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _sem_wait(_ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_sem_post"); -1 } #[allow(clippy::cast_ptr_alignment)] -pub fn _getgrent(_ctx: ContextMut<'_, EmEnv>) -> c_int { +pub fn _getgrent(_ctx: FunctionEnvMut) -> c_int { debug!("emscripten::_getgrent"); -1 } -pub fn _setgrent(_ctx: ContextMut<'_, EmEnv>) { +pub fn _setgrent(_ctx: FunctionEnvMut) { debug!("emscripten::_setgrent"); } -pub fn _setgroups(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn _setgroups(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::_setgroups"); -1 } -pub fn _setitimer(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32) -> i32 { +pub fn _setitimer(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32) -> i32 { debug!("emscripten::_setitimer"); -1 } -pub fn _usleep(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _usleep(_ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_usleep"); -1 } -pub fn _nanosleep(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn _nanosleep(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::_nanosleep"); -1 } -pub fn _utime(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn _utime(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::_utime"); -1 } -pub fn _utimes(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn _utimes(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::_utimes"); -1 } -pub fn _wait(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _wait(_ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_wait"); -1 } -pub fn _wait3(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32) -> i32 { +pub fn _wait3(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32) -> i32 { debug!("emscripten::_wait3"); -1 } -pub fn _wait4(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32, _d: i32) -> i32 { +pub fn _wait4(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32, _d: i32) -> i32 { debug!("emscripten::_wait4"); -1 } -pub fn _waitid(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32, _d: i32) -> i32 { +pub fn _waitid(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32, _d: i32) -> i32 { debug!("emscripten::_waitid"); -1 } -pub fn _waitpid(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32) -> i32 { +pub fn _waitpid(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32) -> i32 { debug!("emscripten::_waitpid"); -1 } -pub fn abort_stack_overflow(ctx: ContextMut<'_, EmEnv>, _what: c_int) { +pub fn abort_stack_overflow(ctx: FunctionEnvMut, _what: c_int) { debug!("emscripten::abort_stack_overflow"); // TODO: Message incomplete. Need to finish em runtime data first abort_with_message( @@ -176,24 +176,24 @@ pub fn abort_stack_overflow(ctx: ContextMut<'_, EmEnv>, _what: c_int) { ); } -pub fn _llvm_trap(ctx: ContextMut<'_, EmEnv>) { +pub fn _llvm_trap(ctx: FunctionEnvMut) { debug!("emscripten::_llvm_trap"); abort_with_message(ctx, "abort!"); } -pub fn _llvm_eh_typeid_for(_ctx: ContextMut<'_, EmEnv>, _type_info_addr: u32) -> i32 { +pub fn _llvm_eh_typeid_for(_ctx: FunctionEnvMut, _type_info_addr: u32) -> i32 { debug!("emscripten::_llvm_eh_typeid_for"); -1 } -pub fn _system(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> c_int { +pub fn _system(_ctx: FunctionEnvMut, _one: i32) -> c_int { debug!("emscripten::_system"); // TODO: May need to change this Em impl to a working version eprintln!("Can't call external programs"); EAGAIN } -pub fn _popen(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> c_int { +pub fn _popen(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> c_int { debug!("emscripten::_popen"); // TODO: May need to change this Em impl to a working version eprintln!("Missing function: popen"); diff --git a/lib/emscripten/src/pthread.rs b/lib/emscripten/src/pthread.rs index 2ffd17c97a0..322a1b0326b 100644 --- a/lib/emscripten/src/pthread.rs +++ b/lib/emscripten/src/pthread.rs @@ -1,13 +1,13 @@ use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; -pub fn _pthread_attr_destroy(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_attr_destroy(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_attr_destroy"); 0 } pub fn _pthread_attr_getstack( - mut _ctx: ContextMut<'_, EmEnv>, + mut _ctx: FunctionEnvMut, _stackaddr: i32, _stacksize: i32, _other: i32, @@ -24,175 +24,175 @@ pub fn _pthread_attr_getstack( 0 } -pub fn _pthread_attr_init(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_attr_init(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_attr_init({})", _a); 0 } -pub fn _pthread_attr_setstacksize(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_attr_setstacksize(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_attr_setstacksize"); 0 } -pub fn _pthread_cleanup_pop(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) { +pub fn _pthread_cleanup_pop(mut _ctx: FunctionEnvMut, _a: i32) { trace!("emscripten::_pthread_cleanup_pop"); } -pub fn _pthread_cleanup_push(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) { +pub fn _pthread_cleanup_push(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) { trace!("emscripten::_pthread_cleanup_push"); } -pub fn _pthread_cond_destroy(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_cond_destroy(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_cond_destroy"); 0 } -pub fn _pthread_cond_init(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_cond_init(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_cond_init"); 0 } -pub fn _pthread_cond_signal(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_cond_signal(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_cond_signal"); 0 } -pub fn _pthread_cond_timedwait(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32, _c: i32) -> i32 { +pub fn _pthread_cond_timedwait(mut _ctx: FunctionEnvMut, _a: i32, _b: i32, _c: i32) -> i32 { trace!("emscripten::_pthread_cond_timedwait"); 0 } -pub fn _pthread_cond_wait(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_cond_wait(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_cond_wait"); 0 } -pub fn _pthread_condattr_destroy(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_condattr_destroy(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_condattr_destroy"); 0 } -pub fn _pthread_condattr_init(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_condattr_init(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_condattr_init"); 0 } -pub fn _pthread_condattr_setclock(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_condattr_setclock(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_condattr_setclock"); 0 } -pub fn _pthread_create(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32, _c: i32, _d: i32) -> i32 { +pub fn _pthread_create(mut _ctx: FunctionEnvMut, _a: i32, _b: i32, _c: i32, _d: i32) -> i32 { trace!("emscripten::_pthread_create"); // 11 seems to mean "no" 11 } -pub fn _pthread_detach(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_detach(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_detach"); 0 } -pub fn _pthread_equal(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_equal(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_equal"); 0 } -pub fn _pthread_exit(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) { +pub fn _pthread_exit(mut _ctx: FunctionEnvMut, _a: i32) { trace!("emscripten::_pthread_exit"); } -pub fn _pthread_getattr_np(mut _ctx: ContextMut<'_, EmEnv>, _thread: i32, _attr: i32) -> i32 { +pub fn _pthread_getattr_np(mut _ctx: FunctionEnvMut, _thread: i32, _attr: i32) -> i32 { trace!("emscripten::_pthread_getattr_np({}, {})", _thread, _attr); 0 } -pub fn _pthread_getspecific(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_getspecific(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_getspecific"); 0 } -pub fn _pthread_join(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_join(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_join"); 0 } -pub fn _pthread_self(mut _ctx: ContextMut<'_, EmEnv>) -> i32 { +pub fn _pthread_self(mut _ctx: FunctionEnvMut) -> i32 { trace!("emscripten::_pthread_self"); 0 } -pub fn _pthread_key_create(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_key_create(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_key_create"); 0 } -pub fn _pthread_mutex_destroy(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_mutex_destroy(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_mutex_destroy"); 0 } -pub fn _pthread_mutex_init(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_mutex_init(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_mutex_init"); 0 } -pub fn _pthread_mutexattr_destroy(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_mutexattr_destroy(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_mutexattr_destroy"); 0 } -pub fn _pthread_mutexattr_init(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_mutexattr_init(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_mutexattr_init"); 0 } -pub fn _pthread_mutexattr_settype(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_mutexattr_settype(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_mutexattr_settype"); 0 } -pub fn _pthread_once(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_once(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_once"); 0 } -pub fn _pthread_rwlock_destroy(mut _ctx: ContextMut<'_, EmEnv>, _rwlock: i32) -> i32 { +pub fn _pthread_rwlock_destroy(mut _ctx: FunctionEnvMut, _rwlock: i32) -> i32 { trace!("emscripten::_pthread_rwlock_destroy({})", _rwlock); 0 } -pub fn _pthread_rwlock_init(mut _ctx: ContextMut<'_, EmEnv>, _rwlock: i32, _attr: i32) -> i32 { +pub fn _pthread_rwlock_init(mut _ctx: FunctionEnvMut, _rwlock: i32, _attr: i32) -> i32 { trace!("emscripten::_pthread_rwlock_init({}, {})", _rwlock, _attr); 0 } -pub fn _pthread_rwlock_rdlock(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_rwlock_rdlock(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_rwlock_rdlock"); 0 } -pub fn _pthread_rwlock_unlock(mut _ctx: ContextMut<'_, EmEnv>, _a: i32) -> i32 { +pub fn _pthread_rwlock_unlock(mut _ctx: FunctionEnvMut, _a: i32) -> i32 { trace!("emscripten::_pthread_rwlock_unlock"); 0 } -pub fn _pthread_rwlock_wrlock(mut _ctx: ContextMut<'_, EmEnv>, _rwlock: i32) -> i32 { +pub fn _pthread_rwlock_wrlock(mut _ctx: FunctionEnvMut, _rwlock: i32) -> i32 { trace!("emscripten::_pthread_rwlock_wrlock({})", _rwlock); 0 } -pub fn _pthread_setcancelstate(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_setcancelstate(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_setcancelstate"); 0 } -pub fn _pthread_setspecific(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32) -> i32 { +pub fn _pthread_setspecific(mut _ctx: FunctionEnvMut, _a: i32, _b: i32) -> i32 { trace!("emscripten::_pthread_setspecific"); 0 } -pub fn _pthread_sigmask(mut _ctx: ContextMut<'_, EmEnv>, _a: i32, _b: i32, _c: i32) -> i32 { +pub fn _pthread_sigmask(mut _ctx: FunctionEnvMut, _a: i32, _b: i32, _c: i32) -> i32 { trace!("emscripten::_pthread_sigmask"); 0 } diff --git a/lib/emscripten/src/signal.rs b/lib/emscripten/src/signal.rs index 1e0c55f9b5a..967a15a32d0 100644 --- a/lib/emscripten/src/signal.rs +++ b/lib/emscripten/src/signal.rs @@ -1,9 +1,9 @@ // use super::varargs::VarArgs; use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; #[allow(clippy::cast_ptr_alignment)] -pub fn _sigemptyset(ctx: ContextMut<'_, EmEnv>, set: u32) -> i32 { +pub fn _sigemptyset(ctx: FunctionEnvMut, set: u32) -> i32 { debug!("emscripten::_sigemptyset"); let set_addr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), set) as *mut u32; unsafe { @@ -12,18 +12,18 @@ pub fn _sigemptyset(ctx: ContextMut<'_, EmEnv>, set: u32) -> i32 { 0 } -pub fn _sigaction(_ctx: ContextMut<'_, EmEnv>, _signum: u32, _act: u32, _oldact: u32) -> i32 { +pub fn _sigaction(_ctx: FunctionEnvMut, _signum: u32, _act: u32, _oldact: u32) -> i32 { debug!("emscripten::_sigaction {}, {}, {}", _signum, _act, _oldact); 0 } -pub fn _siginterrupt(_ctx: ContextMut<'_, EmEnv>, _a: u32, _b: u32) -> i32 { +pub fn _siginterrupt(_ctx: FunctionEnvMut, _a: u32, _b: u32) -> i32 { debug!("emscripten::_siginterrupt {}, {}", _a, _b); 0 } #[allow(clippy::cast_ptr_alignment)] -pub fn _sigaddset(ctx: ContextMut<'_, EmEnv>, set: u32, signum: u32) -> i32 { +pub fn _sigaddset(ctx: FunctionEnvMut, set: u32, signum: u32) -> i32 { debug!("emscripten::_sigaddset {}, {}", set, signum); let set_addr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), set) as *mut u32; unsafe { @@ -32,17 +32,17 @@ pub fn _sigaddset(ctx: ContextMut<'_, EmEnv>, set: u32, signum: u32) -> i32 { 0 } -pub fn _sigsuspend(_ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _sigsuspend(_ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_sigsuspend"); -1 } -pub fn _sigprocmask(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32, _three: i32) -> i32 { +pub fn _sigprocmask(_ctx: FunctionEnvMut, _one: i32, _two: i32, _three: i32) -> i32 { debug!("emscripten::_sigprocmask"); 0 } -pub fn _signal(_ctx: ContextMut<'_, EmEnv>, _sig: u32, _two: i32) -> i32 { +pub fn _signal(_ctx: FunctionEnvMut, _sig: u32, _two: i32) -> i32 { debug!("emscripten::_signal ({})", _sig); 0 } diff --git a/lib/emscripten/src/syscalls/mod.rs b/lib/emscripten/src/syscalls/mod.rs index 6b8dc0ffd47..2fb48f4350d 100644 --- a/lib/emscripten/src/syscalls/mod.rs +++ b/lib/emscripten/src/syscalls/mod.rs @@ -48,10 +48,10 @@ use super::env; #[allow(unused_imports)] use std::io::Error; use std::slice; -use wasmer::{AsContextMut, ContextMut, WasmPtr}; +use wasmer::{FunctionEnvMut, WasmPtr}; /// exit -pub fn ___syscall1(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) { +pub fn ___syscall1(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) { debug!("emscripten::___syscall1 (exit) {}", _which); let status: i32 = varargs.get(&ctx); unsafe { @@ -60,7 +60,7 @@ pub fn ___syscall1(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarAr } /// read -pub fn ___syscall3(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarArgs) -> i32 { +pub fn ___syscall3(ctx: FunctionEnvMut, _which: i32, mut varargs: VarArgs) -> i32 { // -> ssize_t debug!("emscripten::___syscall3 (read) {}", _which); let fd: i32 = varargs.get(&ctx); @@ -74,7 +74,7 @@ pub fn ___syscall3(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarArgs } /// write -pub fn ___syscall4(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall4(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall4 (write) {}", _which); let fd: i32 = varargs.get(&ctx); let buf: i32 = varargs.get(&ctx); @@ -85,7 +85,7 @@ pub fn ___syscall4(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarAr } /// close -pub fn ___syscall6(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall6(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall6 (close) {}", _which); let fd: i32 = varargs.get(&ctx); debug!("fd: {}", fd); @@ -93,7 +93,7 @@ pub fn ___syscall6(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarAr } // chdir -pub fn ___syscall12(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall12(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall12 (chdir) {}", _which); let path_ptr = varargs.get_str(&ctx); let real_path_owned = get_cstr_path(ctx, path_ptr as *const _); @@ -111,63 +111,63 @@ pub fn ___syscall12(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarA ret } -pub fn ___syscall10(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall10(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall10"); -1 } -pub fn ___syscall14(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall14(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall14"); -1 } -pub fn ___syscall15(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall15(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall15"); -1 } // getpid -pub fn ___syscall20(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall20(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall20 (getpid)"); unsafe { getpid() } } -pub fn ___syscall21(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall21(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall21"); -1 } -pub fn ___syscall25(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall25(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall25"); -1 } -pub fn ___syscall29(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall29(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall29"); -1 } -pub fn ___syscall32(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall32(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall32"); -1 } -pub fn ___syscall33(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall33(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall33"); -1 } -pub fn ___syscall36(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall36(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall36"); -1 } // rename -pub fn ___syscall38(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> i32 { +pub fn ___syscall38(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> i32 { debug!("emscripten::___syscall38 (rename)"); let old_path = varargs.get_str(&ctx); let new_path = varargs.get_str(&ctx); - let real_old_path_owned = get_cstr_path(ctx.as_context_mut(), old_path as *const _); + let real_old_path_owned = get_cstr_path(ctx.as_mut(), old_path as *const _); let real_old_path = if let Some(ref rp) = real_old_path_owned { rp.as_c_str().as_ptr() } else { @@ -190,7 +190,7 @@ pub fn ___syscall38(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } // rmdir -pub fn ___syscall40(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall40(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall40 (rmdir)"); let pathname_addr = varargs.get_str(&ctx); let real_path_owned = get_cstr_path(ctx, pathname_addr as *const _); @@ -203,7 +203,7 @@ pub fn ___syscall40(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarA } // pipe -pub fn ___syscall42(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall42(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall42 (pipe)"); // offset to a file descriptor, which contains a read end and write end, 2 integers let fd_offset: u32 = varargs.get(&ctx); @@ -230,28 +230,28 @@ pub fn ___syscall42(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarA result } -pub fn ___syscall51(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall51(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall51"); -1 } -pub fn ___syscall52(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall52(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall52"); -1 } -pub fn ___syscall53(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall53(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall53"); -1 } -pub fn ___syscall60(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall60(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall60"); -1 } // dup2 -pub fn ___syscall63(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall63(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall63 (dup2) {}", _which); let src: i32 = varargs.get(&ctx); @@ -261,97 +261,97 @@ pub fn ___syscall63(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarA } // getppid -pub fn ___syscall64(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall64(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall64 (getppid)"); unsafe { getpid() } } -pub fn ___syscall66(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall66(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall66"); -1 } -pub fn ___syscall75(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall75(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall75"); -1 } -pub fn ___syscall91(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall91(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall91 - stub"); 0 } -pub fn ___syscall96(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall96(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall96"); -1 } -pub fn ___syscall97(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall97(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall97"); -1 } -pub fn ___syscall110(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall110(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall110"); -1 } -pub fn ___syscall121(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall121(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall121"); -1 } -pub fn ___syscall125(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall125(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall125"); -1 } -pub fn ___syscall133(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall133(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall133"); -1 } -pub fn ___syscall144(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall144(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall144"); -1 } -pub fn ___syscall147(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall147(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall147"); -1 } -pub fn ___syscall150(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall150(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall150"); -1 } -pub fn ___syscall151(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall151(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall151"); -1 } -pub fn ___syscall152(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall152(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall152"); -1 } -pub fn ___syscall153(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall153(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall153"); -1 } -pub fn ___syscall163(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall163(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall163"); -1 } // getcwd -pub fn ___syscall183(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> i32 { +pub fn ___syscall183(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> i32 { debug!("emscripten::___syscall183"); let buf_offset: WasmPtr = varargs.get(&ctx); let _size: c_int = varargs.get(&ctx); - let path = get_current_directory(ctx.as_context_mut()); + let path = get_current_directory(ctx.as_mut()); let path_string = path.unwrap().display().to_string(); let len = path_string.len(); let memory = ctx.data().memory(0); @@ -365,7 +365,7 @@ pub fn ___syscall183(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } // mmap2 -pub fn ___syscall192(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall192(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall192 (mmap2) {}", _which); let _addr: i32 = varargs.get(&ctx); let len: u32 = varargs.get(&ctx); @@ -379,13 +379,13 @@ pub fn ___syscall192(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: ); if fd == -1 { - let ptr = env::call_memalign(ctx.as_context_mut(), 16384, len); + let ptr = env::call_memalign(&mut ctx, 16384, len); if ptr == 0 { // ENOMEM return -12; } let real_ptr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), ptr) as *const u8; - env::call_memset(ctx, ptr, 0, len); + env::call_memset(&mut ctx, ptr, 0, len); for i in 0..(len as usize) { unsafe { assert_eq!(*real_ptr.add(i), 0); @@ -400,7 +400,7 @@ pub fn ___syscall192(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } /// lseek -pub fn ___syscall140(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarArgs) -> i32 { +pub fn ___syscall140(ctx: FunctionEnvMut, _which: i32, mut varargs: VarArgs) -> i32 { // -> c_int debug!("emscripten::___syscall140 (lseek) {}", _which); let fd: i32 = varargs.get(&ctx); @@ -429,7 +429,7 @@ pub fn ___syscall140(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarAr /// readv #[allow(clippy::cast_ptr_alignment)] -pub fn ___syscall145(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> i32 { +pub fn ___syscall145(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> i32 { // -> ssize_t debug!("emscripten::___syscall145 (readv) {}", _which); @@ -468,7 +468,7 @@ pub fn ___syscall145(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var // writev #[allow(clippy::cast_ptr_alignment)] -pub fn ___syscall146(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarArgs) -> i32 { +pub fn ___syscall146(ctx: FunctionEnvMut, _which: i32, mut varargs: VarArgs) -> i32 { // -> ssize_t debug!("emscripten::___syscall146 (writev) {}", _which); let fd: i32 = varargs.get(&ctx); @@ -511,7 +511,7 @@ pub fn ___syscall146(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarAr ret as _ } -pub fn ___syscall191(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarArgs) -> i32 { +pub fn ___syscall191(ctx: FunctionEnvMut, _which: i32, mut varargs: VarArgs) -> i32 { let _resource: i32 = varargs.get(&ctx); debug!( "emscripten::___syscall191 - mostly stub, resource: {}", @@ -528,18 +528,18 @@ pub fn ___syscall191(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarAr 0 } -pub fn ___syscall193(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall193(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall193"); -1 } // stat64 -pub fn ___syscall195(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall195(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall195 (stat64) {}", _which); let pathname_addr = varargs.get_str(&ctx); let buf: u32 = varargs.get(&ctx); - let real_path_owned = get_cstr_path(ctx.as_context_mut(), pathname_addr as *const _); + let real_path_owned = get_cstr_path(ctx.as_mut(), pathname_addr as *const _); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -565,7 +565,7 @@ pub fn ___syscall195(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } // fstat64 -pub fn ___syscall197(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall197(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall197 (fstat64) {}", _which); let fd: c_int = varargs.get(&ctx); @@ -584,129 +584,129 @@ pub fn ___syscall197(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var 0 } -pub fn ___syscall209(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall209(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall209"); -1 } -pub fn ___syscall211(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall211(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall211"); -1 } -pub fn ___syscall218(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall218(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall218"); -1 } -pub fn ___syscall268(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall268(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall268"); -1 } -pub fn ___syscall269(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall269(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall269"); -1 } -pub fn ___syscall272(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall272(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall272"); -1 } -pub fn ___syscall295(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall295(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall295"); -1 } -pub fn ___syscall296(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall296(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall296"); -1 } -pub fn ___syscall297(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall297(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall297"); -1 } -pub fn ___syscall298(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall298(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall298"); -1 } -pub fn ___syscall300(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall300(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall300"); -1 } -pub fn ___syscall301(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall301(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall301"); -1 } -pub fn ___syscall302(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall302(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall302"); -1 } -pub fn ___syscall303(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall303(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall303"); -1 } -pub fn ___syscall304(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall304(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall304"); -1 } -pub fn ___syscall305(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall305(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall305"); -1 } -pub fn ___syscall306(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall306(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall306"); -1 } -pub fn ___syscall307(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall307(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall307"); -1 } -pub fn ___syscall308(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall308(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall308"); -1 } // utimensat -pub fn ___syscall320(_ctx: ContextMut<'_, EmEnv>, _which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall320(_ctx: FunctionEnvMut, _which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall320 (utimensat), {}", _which); 0 } -pub fn ___syscall331(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall331(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall331"); -1 } -pub fn ___syscall333(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall333(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall333"); -1 } -pub fn ___syscall334(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall334(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall334"); -1 } -pub fn ___syscall337(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall337(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall337"); -1 } // prlimit64 -pub fn ___syscall340(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall340(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall340 (prlimit64), {}", _which); // NOTE: Doesn't really matter. Wasm modules cannot exceed WASM_PAGE_SIZE anyway. let _pid: i32 = varargs.get(&ctx); @@ -732,7 +732,7 @@ pub fn ___syscall340(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var 0 } -pub fn ___syscall345(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall345(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall345"); -1 } diff --git a/lib/emscripten/src/syscalls/unix.rs b/lib/emscripten/src/syscalls/unix.rs index ea402a33a63..4ef741dd75e 100644 --- a/lib/emscripten/src/syscalls/unix.rs +++ b/lib/emscripten/src/syscalls/unix.rs @@ -81,7 +81,7 @@ use libc::{ // TCGETS, // TCSETSW, }; -use wasmer::{AsContextMut, ContextMut, ValueType, WasmPtr}; +use wasmer::{FunctionEnvMut, ValueType, WasmPtr}; // They are not exposed in in Rust libc in macOS const TCGETS: u64 = 0x5401; @@ -157,12 +157,12 @@ use libc::SO_NOSIGPIPE; const SO_NOSIGPIPE: c_int = 0; /// open -pub fn ___syscall5(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall5(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall5 (open) {}", _which); let pathname_addr = varargs.get_str(&ctx); let flags: i32 = varargs.get(&ctx); let mode: u32 = varargs.get(&ctx); - let real_path_owned = utils::get_cstr_path(ctx.as_context_mut(), pathname_addr as *const _); + let real_path_owned = utils::get_cstr_path(ctx, pathname_addr as *const _); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -181,7 +181,7 @@ pub fn ___syscall5(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: V } /// link -pub fn ___syscall9(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall9(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall9 (link) {}", _which); let oldname_ptr = varargs.get_str(&ctx); @@ -197,7 +197,7 @@ pub fn ___syscall9(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarAr } /// getrusage -pub fn ___syscall77(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall77(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall77 (getrusage) {}", _which); let resource: c_int = varargs.get(&ctx); @@ -209,18 +209,18 @@ pub fn ___syscall77(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarA } /// symlink -pub fn ___syscall83(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall83(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall83 (symlink) {}", _which); let path1 = varargs.get_str(&ctx); let path2 = varargs.get_str(&ctx); - let real_path1_owned = utils::get_cstr_path(ctx.as_context_mut(), path1 as *const _); + let real_path1_owned = utils::get_cstr_path(ctx.as_mut(), path1 as *const _); let real_path1 = if let Some(ref rp) = real_path1_owned { rp.as_c_str().as_ptr() } else { path1 }; - let real_path2_owned = utils::get_cstr_path(ctx.as_context_mut(), path2 as *const _); + let real_path2_owned = utils::get_cstr_path(ctx, path2 as *const _); let real_path2 = if let Some(ref rp) = real_path2_owned { rp.as_c_str().as_ptr() } else { @@ -237,13 +237,13 @@ pub fn ___syscall83(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } /// readlink -pub fn ___syscall85(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> i32 { +pub fn ___syscall85(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> i32 { debug!("emscripten::___syscall85 (readlink)"); let pathname_addr = varargs.get_str(&ctx); let buf = varargs.get_str(&ctx); // let buf_addr: i32 = varargs.get(&ctx); let buf_size: i32 = varargs.get(&ctx); - let real_path_owned = get_cstr_path(ctx.as_context_mut(), pathname_addr as *const _); + let real_path_owned = get_cstr_path(ctx, pathname_addr as *const _); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -266,7 +266,7 @@ pub fn ___syscall85(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } /// ftruncate64 -pub fn ___syscall194(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall194(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall194 (ftruncate64) {}", _which); let _fd: c_int = varargs.get(&ctx); let _length: i64 = varargs.get(&ctx); @@ -283,10 +283,10 @@ pub fn ___syscall194(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// lchown -pub fn ___syscall198(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall198(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall198 (lchown) {}", _which); let path_ptr = varargs.get_str(&ctx); - let real_path_owned = utils::get_cstr_path(ctx.as_context_mut(), path_ptr as *const _); + let real_path_owned = utils::get_cstr_path(ctx.as_mut(), path_ptr as *const _); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -306,7 +306,7 @@ pub fn ___syscall198(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } /// getgroups -pub fn ___syscall205(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall205(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall205 (getgroups) {}", _which); let ngroups_max: c_int = varargs.get(&ctx); let groups: c_int = varargs.get(&ctx); @@ -323,11 +323,11 @@ pub fn ___syscall205(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } // chown -pub fn ___syscall212(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall212(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall212 (chown) {}", _which); let pathname_addr = varargs.get_str(&ctx); - let real_path_owned = utils::get_cstr_path(ctx.as_context_mut(), pathname_addr as *const _); + let real_path_owned = utils::get_cstr_path(ctx.as_mut(), pathname_addr as *const _); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -340,7 +340,7 @@ pub fn ___syscall212(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } /// madvise -pub fn ___syscall219(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall219(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall212 (chown) {}", _which); let addr_ptr: c_int = varargs.get(&ctx); @@ -353,10 +353,10 @@ pub fn ___syscall219(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// access -pub fn ___syscall33(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall33(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall33 (access) {}", _which); let path = varargs.get_str(&ctx); - let real_path_owned = utils::get_cstr_path(ctx.as_context_mut(), path as *const _); + let real_path_owned = utils::get_cstr_path(ctx.as_mut(), path as *const _); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -374,17 +374,17 @@ pub fn ___syscall33(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } /// nice -pub fn ___syscall34(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall34(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall34 (nice) {}", _which); let inc_r: c_int = varargs.get(&ctx); unsafe { nice(inc_r) } } // mkdir -pub fn ___syscall39(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall39(mut ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall39 (mkdir) {}", _which); let pathname_addr = varargs.get_str(&ctx); - let real_path_owned = utils::get_cstr_path(ctx.as_context_mut(), pathname_addr as *const _); + let real_path_owned = utils::get_cstr_path(ctx.as_mut(), pathname_addr as *const _); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -395,20 +395,20 @@ pub fn ___syscall39(mut ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: } /// dup -pub fn ___syscall41(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall41(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall41 (dup) {}", _which); let fd: c_int = varargs.get(&ctx); unsafe { dup(fd) } } /// getgid32 -pub fn ___syscall200(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall200(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall200 (getgid32)"); unsafe { getgid() as i32 } } // geteuid32 -pub fn ___syscall201(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall201(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall201 (geteuid32)"); unsafe { // Maybe fix: Emscripten returns 0 always @@ -417,7 +417,7 @@ pub fn ___syscall201(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { } // getegid32 -pub fn ___syscall202(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall202(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { // gid_t debug!("emscripten::___syscall202 (getegid32)"); unsafe { @@ -427,7 +427,7 @@ pub fn ___syscall202(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { } /// fchown -pub fn ___syscall207(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall207(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall207 (fchown) {}", _which); let fd: c_int = varargs.get(&ctx); let owner: uid_t = varargs.get(&ctx); @@ -436,7 +436,7 @@ pub fn ___syscall207(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// dup3 -pub fn ___syscall330(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> pid_t { +pub fn ___syscall330(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> pid_t { // Implementation based on description at https://linux.die.net/man/2/dup3 debug!("emscripten::___syscall330 (dup3)"); let oldfd: c_int = varargs.get(&ctx); @@ -474,7 +474,7 @@ pub fn ___syscall330(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// ioctl -pub fn ___syscall54(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall54(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall54 (ioctl) {}", _which); let fd: i32 = varargs.get(&ctx); @@ -517,7 +517,7 @@ const SOCK_CLOEXC: i32 = 0x80000; // socketcall #[allow(clippy::cast_ptr_alignment)] -pub fn ___syscall102(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall102(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall102 (socketcall) {}", _which); let call: u32 = varargs.get(&ctx); let mut socket_varargs: VarArgs = varargs.get(&ctx); @@ -833,7 +833,7 @@ fn translate_socket_name_flag(name: i32) -> i32 { } /// getpgid -pub fn ___syscall132(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall132(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall132 (getpgid)"); let pid: pid_t = varargs.get(&ctx); @@ -855,7 +855,7 @@ pub struct EmPollFd { } /// poll -pub fn ___syscall168(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarArgs) -> i32 { +pub fn ___syscall168(ctx: FunctionEnvMut, _which: i32, mut varargs: VarArgs) -> i32 { debug!("emscripten::___syscall168(poll)"); let fds: WasmPtr = varargs.get(&ctx); let nfds: u32 = varargs.get(&ctx); @@ -874,7 +874,7 @@ pub fn ___syscall168(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarAr } // pread -pub fn ___syscall180(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall180(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall180 (pread) {}", _which); let fd: i32 = varargs.get(&ctx); let buf: u32 = varargs.get(&ctx); @@ -891,7 +891,7 @@ pub fn ___syscall180(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } // pwrite -pub fn ___syscall181(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall181(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall181 (pwrite) {}", _which); let fd: i32 = varargs.get(&ctx); let buf: u32 = varargs.get(&ctx); @@ -912,7 +912,7 @@ pub fn ___syscall181(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// fchmod -pub fn ___syscall94(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall94(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall118 (fchmod) {}", _which); let fd: c_int = varargs.get(&ctx); let mode: mode_t = varargs.get(&ctx); @@ -921,7 +921,7 @@ pub fn ___syscall94(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarA /// wait4 #[allow(clippy::cast_ptr_alignment)] -pub fn ___syscall114(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> pid_t { +pub fn ___syscall114(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> pid_t { debug!("emscripten::___syscall114 (wait4)"); let pid: pid_t = varargs.get(&ctx); let status: u32 = varargs.get(&ctx); @@ -939,7 +939,7 @@ pub fn ___syscall114(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// fsync -pub fn ___syscall118(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall118(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall118 (fsync) {}", _which); let fd: c_int = varargs.get(&ctx); unsafe { fsync(fd) } @@ -947,7 +947,7 @@ pub fn ___syscall118(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var // select #[allow(clippy::cast_ptr_alignment)] -pub fn ___syscall142(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall142(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall142 (newselect) {}", _which); let nfds: i32 = varargs.get(&ctx); @@ -969,7 +969,7 @@ pub fn ___syscall142(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// fdatasync -pub fn ___syscall148(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall148(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall148 (fdatasync) {}", _which); let fd: i32 = varargs.get(&ctx); @@ -978,7 +978,7 @@ pub fn ___syscall148(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } // setpgid -pub fn ___syscall57(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall57(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall57 (setpgid) {}", _which); let pid: i32 = varargs.get(&ctx); @@ -994,7 +994,7 @@ pub fn ___syscall57(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarA /// uname // NOTE: Wondering if we should return custom utsname, like Emscripten. -pub fn ___syscall122(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall122(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall122 (uname) {}", _which); let buf: u32 = varargs.get(&ctx); debug!("=> buf: {}", buf); @@ -1003,10 +1003,10 @@ pub fn ___syscall122(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// lstat64 -pub fn ___syscall196(mut ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarArgs) -> i32 { +pub fn ___syscall196(mut ctx: FunctionEnvMut, _which: i32, mut varargs: VarArgs) -> i32 { debug!("emscripten::___syscall196 (lstat64) {}", _which); let path = varargs.get_str(&ctx); - let real_path_owned = utils::get_cstr_path(ctx.as_context_mut(), path as *const _); + let real_path_owned = utils::get_cstr_path(ctx.as_mut(), path as *const _); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -1036,7 +1036,7 @@ pub fn ___syscall196(mut ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: V } // getuid -pub fn ___syscall199(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall199(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall199 (getuid)"); let uid = unsafe { getuid() as _ }; debug!(" => {}", uid); @@ -1046,7 +1046,7 @@ pub fn ___syscall199(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { // getdents // dirent structure is // i64, i64, u16 (280), i8, [i8; 256] -pub fn ___syscall220(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarArgs) -> i32 { +pub fn ___syscall220(ctx: FunctionEnvMut, _which: i32, mut varargs: VarArgs) -> i32 { use super::super::env::get_emscripten_data; let fd: i32 = varargs.get(&ctx); @@ -1111,7 +1111,7 @@ pub fn ___syscall220(ctx: ContextMut<'_, EmEnv>, _which: i32, mut varargs: VarAr } // fcntl64 -pub fn ___syscall221(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall221(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall221 (fcntl64) {}", _which); let fd: i32 = varargs.get(&ctx); let cmd: i32 = varargs.get(&ctx); @@ -1129,7 +1129,7 @@ pub fn ___syscall221(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: Var } /// fallocate -pub fn ___syscall324(ctx: ContextMut<'_, EmEnv>, _which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall324(ctx: FunctionEnvMut, _which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall324 (fallocate) {}", _which); let _fd: c_int = varargs.get(&ctx); let _mode: c_int = varargs.get(&ctx); diff --git a/lib/emscripten/src/syscalls/windows.rs b/lib/emscripten/src/syscalls/windows.rs index 3c16821c940..705dd19905c 100644 --- a/lib/emscripten/src/syscalls/windows.rs +++ b/lib/emscripten/src/syscalls/windows.rs @@ -8,18 +8,18 @@ use std::ffi::CString; use std::fs::File; use std::io::Write; use std::os::raw::c_int; -use wasmer::{AsContextMut, ContextMut}; +use wasmer::FunctionEnvMut; #[allow(non_camel_case_types)] type pid_t = c_int; /// open -pub fn ___syscall5(mut ctx: ContextMut<'_, EmEnv>, which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall5(mut ctx: FunctionEnvMut, which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall5 (open) {}", which); #[cfg(not(feature = "debug"))] let _ = which; let pathname_addr = varargs.get_str(&ctx); - let real_path_owned = get_cstr_path(ctx.as_context_mut(), pathname_addr); + let real_path_owned = get_cstr_path(ctx.as_mut(), pathname_addr); let real_path = if let Some(ref rp) = real_path_owned { rp.as_c_str().as_ptr() } else { @@ -45,7 +45,7 @@ pub fn ___syscall5(mut ctx: ContextMut<'_, EmEnv>, which: c_int, mut varargs: Va getrandom::getrandom(&mut random_bytes).unwrap(); let _ = urandom_file.write_all(&random_bytes).unwrap(); // put the file path string into wasm memory - let urandom_file_offset = unsafe { copy_cstr_into_wasm(ctx.as_context_mut(), ptr) }; + let urandom_file_offset = unsafe { copy_cstr_into_wasm(&mut ctx, ptr) }; let raw_pointer_to_urandom_file = emscripten_memory_pointer!(ctx, memory, urandom_file_offset) as *const i8; let fd = unsafe { open(raw_pointer_to_urandom_file, flags, mode) }; @@ -67,19 +67,19 @@ pub fn ___syscall5(mut ctx: ContextMut<'_, EmEnv>, which: c_int, mut varargs: Va } /// link -pub fn ___syscall9(_ctx: ContextMut<'_, EmEnv>, _which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall9(_ctx: FunctionEnvMut, _which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall9 (link) {}", _which); unimplemented!("emscripten::___syscall9 (link) {}", _which); } /// ftruncate64 -pub fn ___syscall194(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall194(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall194 - stub"); unimplemented!("emscripten::___syscall194 - stub") } // chown -pub fn ___syscall212(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall212(_ctx: FunctionEnvMut, which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall212 (chown) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -87,19 +87,19 @@ pub fn ___syscall212(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: Va } /// access -pub fn ___syscall33(_ctx: ContextMut<'_, EmEnv>, _which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall33(_ctx: FunctionEnvMut, _which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall33 (access) {}", _which); unimplemented!("emscripten::___syscall33 (access) {}", _which); } /// nice -pub fn ___syscall34(_ctx: ContextMut<'_, EmEnv>, _which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall34(_ctx: FunctionEnvMut, _which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall34 (nice) {}", _which); unimplemented!("emscripten::___syscall34 (nice) {}", _which); } // mkdir -pub fn ___syscall39(ctx: ContextMut<'_, EmEnv>, which: c_int, mut varargs: VarArgs) -> c_int { +pub fn ___syscall39(ctx: FunctionEnvMut, which: c_int, mut varargs: VarArgs) -> c_int { debug!("emscripten::___syscall39 (mkdir) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -114,80 +114,80 @@ pub fn ___syscall39(ctx: ContextMut<'_, EmEnv>, which: c_int, mut varargs: VarAr } /// dup -pub fn ___syscall41(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall41(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall41 (dup) {}", _which); unimplemented!("emscripten::___syscall41 (dup) {}", _which); } /// getrusage -pub fn ___syscall77(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall77(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall77 (getrusage) {}", _which); unimplemented!("emscripten::___syscall77 (getrusage) {}", _which); } /// symlink -pub fn ___syscall83(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall83(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall83 (symlink) {}", _which); unimplemented!("emscripten::___syscall83 (symlink) {}", _which); } /// readlink -pub fn ___syscall85(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall85(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall85 (readlink) {}", _which); -1 } /// getpgid -pub fn ___syscall132(_ctx: ContextMut<'_, EmEnv>, _which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall132(_ctx: FunctionEnvMut, _which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall132 (getpgid)"); -1 } /// lchown -pub fn ___syscall198(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall198(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall198 (lchown) {}", _which); unimplemented!("emscripten::___syscall198 (lchown) {}", _which); } /// getgid32 -pub fn ___syscall200(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall200(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall200 (getgid32)"); unimplemented!("emscripten::___syscall200 (getgid32)"); } // geteuid32 -pub fn ___syscall201(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall201(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall201 (geteuid32)"); unimplemented!("emscripten::___syscall201 (geteuid32)"); } // getegid32 -pub fn ___syscall202(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall202(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { // gid_t debug!("emscripten::___syscall202 (getegid32)"); unimplemented!("emscripten::___syscall202 (getegid32)"); } /// getgroups -pub fn ___syscall205(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall205(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall205 (getgroups) {}", _which); unimplemented!("emscripten::___syscall205 (getgroups) {}", _which); } /// madvise -pub fn ___syscall219(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall219(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall212 (chown) {}", _which); unimplemented!("emscripten::___syscall212 (chown) {}", _which); } /// dup3 -pub fn ___syscall330(_ctx: ContextMut<'_, EmEnv>, _which: c_int, mut _varargs: VarArgs) -> pid_t { +pub fn ___syscall330(_ctx: FunctionEnvMut, _which: c_int, mut _varargs: VarArgs) -> pid_t { debug!("emscripten::___syscall330 (dup3)"); -1 } /// ioctl -pub fn ___syscall54(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall54(_ctx: FunctionEnvMut, which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall54 (ioctl) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -195,14 +195,14 @@ pub fn ___syscall54(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: Var } /// fchmod -pub fn ___syscall94(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall94(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall118 (fchmod) {}", _which); unimplemented!("emscripten::___syscall118 (fchmod) {}", _which); } // socketcall #[allow(clippy::cast_ptr_alignment)] -pub fn ___syscall102(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall102(_ctx: FunctionEnvMut, which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall102 (socketcall) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -210,13 +210,13 @@ pub fn ___syscall102(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: Va } /// fsync -pub fn ___syscall118(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall118(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall118 (fsync) {}", _which); unimplemented!("emscripten::___syscall118 (fsync) {}", _which); } // pread -pub fn ___syscall180(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall180(_ctx: FunctionEnvMut, which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall180 (pread) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -224,7 +224,7 @@ pub fn ___syscall180(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: Va } // pwrite -pub fn ___syscall181(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall181(_ctx: FunctionEnvMut, which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall181 (pwrite) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -233,14 +233,14 @@ pub fn ___syscall181(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: Va /// wait4 #[allow(clippy::cast_ptr_alignment)] -pub fn ___syscall114(_ctx: ContextMut<'_, EmEnv>, _which: c_int, mut _varargs: VarArgs) -> pid_t { +pub fn ___syscall114(_ctx: FunctionEnvMut, _which: c_int, mut _varargs: VarArgs) -> pid_t { debug!("emscripten::___syscall114 (wait4)"); -1 } // select #[allow(clippy::cast_ptr_alignment)] -pub fn ___syscall142(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall142(_ctx: FunctionEnvMut, which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall142 (newselect) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -248,13 +248,13 @@ pub fn ___syscall142(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: Va } /// fdatasync -pub fn ___syscall148(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall148(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall148 (fdatasync) {}", _which); unimplemented!("emscripten::___syscall148 (fdatasync) {}", _which); } // setpgid -pub fn ___syscall57(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall57(_ctx: FunctionEnvMut, which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall57 (setpgid) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -263,7 +263,7 @@ pub fn ___syscall57(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: Var /// uname // NOTE: Wondering if we should return custom utsname, like Emscripten. -pub fn ___syscall122(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall122(_ctx: FunctionEnvMut, which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall122 (uname) {}", which); #[cfg(not(feature = "debug"))] let _ = which; @@ -271,43 +271,43 @@ pub fn ___syscall122(_ctx: ContextMut<'_, EmEnv>, which: c_int, mut _varargs: Va } /// poll -pub fn ___syscall168(_ctx: ContextMut<'_, EmEnv>, _which: i32, _varargs: VarArgs) -> i32 { +pub fn ___syscall168(_ctx: FunctionEnvMut, _which: i32, _varargs: VarArgs) -> i32 { debug!("emscripten::___syscall168(poll) - stub"); -1 } /// lstat64 -pub fn ___syscall196(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall196(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall196 (lstat64) - stub"); -1 } // getuid -pub fn ___syscall199(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall199(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall199 (getuid)"); -1 } // getdents -pub fn ___syscall220(_ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn ___syscall220(_ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::___syscall220"); -1 } // fcntl64 -pub fn ___syscall221(_ctx: ContextMut<'_, EmEnv>, _which: c_int, mut _varargs: VarArgs) -> c_int { +pub fn ___syscall221(_ctx: FunctionEnvMut, _which: c_int, mut _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall221 (fcntl64) {}", _which); -1 } /// fchown -pub fn ___syscall207(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall207(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall207 (fchown) {}", _which); unimplemented!("emscripten::___syscall207 (fchown) {}", _which) } /// fallocate -pub fn ___syscall324(_ctx: ContextMut<'_, EmEnv>, _which: c_int, _varargs: VarArgs) -> c_int { +pub fn ___syscall324(_ctx: FunctionEnvMut, _which: c_int, _varargs: VarArgs) -> c_int { debug!("emscripten::___syscall324 (fallocate) {}", _which); unimplemented!("emscripten::___syscall324 (fallocate) {}", _which) } diff --git a/lib/emscripten/src/time.rs b/lib/emscripten/src/time.rs index aa32da5d01c..63c90b13fc3 100644 --- a/lib/emscripten/src/time.rs +++ b/lib/emscripten/src/time.rs @@ -13,7 +13,7 @@ use std::ffi::CString; #[cfg(target_os = "windows")] use libc::time_t; -use wasmer::{AsContextMut, ContextMut}; +use wasmer::FunctionEnvMut; #[cfg(target_os = "windows")] #[allow(non_camel_case_types)] @@ -52,7 +52,7 @@ const CLOCK_MONOTONIC_COARSE: clockid_t = 6; /// emscripten: _gettimeofday #[allow(clippy::cast_ptr_alignment)] -pub fn _gettimeofday(ctx: ContextMut<'_, EmEnv>, tp: c_int, tz: c_int) -> c_int { +pub fn _gettimeofday(ctx: FunctionEnvMut, tp: c_int, tz: c_int) -> c_int { debug!("emscripten::_gettimeofday {} {}", tp, tz); #[repr(C)] struct GuestTimeVal { @@ -76,7 +76,7 @@ pub fn _gettimeofday(ctx: ContextMut<'_, EmEnv>, tp: c_int, tz: c_int) -> c_int 0 } -pub fn _clock_getres(mut _ctx: ContextMut<'_, EmEnv>, _clk_id: i32, _tp: i32) -> i32 { +pub fn _clock_getres(mut _ctx: FunctionEnvMut, _clk_id: i32, _tp: i32) -> i32 { debug!("emscripten::_clock_getres"); // clock_getres(clk_id, tp) 0 @@ -84,7 +84,7 @@ pub fn _clock_getres(mut _ctx: ContextMut<'_, EmEnv>, _clk_id: i32, _tp: i32) -> /// emscripten: _clock_gettime #[allow(clippy::cast_ptr_alignment)] -pub fn _clock_gettime(ctx: ContextMut<'_, EmEnv>, clk_id: clockid_t, tp: c_int) -> c_int { +pub fn _clock_gettime(ctx: FunctionEnvMut, clk_id: clockid_t, tp: c_int) -> c_int { debug!("emscripten::_clock_gettime {} {}", clk_id, tp); // debug!("Memory {:?}", ctx.memory(0)[..]); #[repr(C)] @@ -116,41 +116,41 @@ pub fn _clock_gettime(ctx: ContextMut<'_, EmEnv>, clk_id: clockid_t, tp: c_int) 0 } -pub fn _clock_settime(mut _ctx: ContextMut<'_, EmEnv>, _clk_id: i32, _tp: i32) -> i32 { +pub fn _clock_settime(mut _ctx: FunctionEnvMut, _clk_id: i32, _tp: i32) -> i32 { debug!("emscripten::_clock_settime"); // clock_settime(clk_id, tp) 0 } /// emscripten: ___clock_gettime -pub fn ___clock_gettime(ctx: ContextMut<'_, EmEnv>, clk_id: clockid_t, tp: c_int) -> c_int { +pub fn ___clock_gettime(ctx: FunctionEnvMut, clk_id: clockid_t, tp: c_int) -> c_int { debug!("emscripten::___clock_gettime {} {}", clk_id, tp); _clock_gettime(ctx, clk_id, tp) } /// emscripten: _clock -pub fn _clock(mut _ctx: ContextMut<'_, EmEnv>) -> c_int { +pub fn _clock(mut _ctx: FunctionEnvMut) -> c_int { debug!("emscripten::_clock"); 0 // TODO: unimplemented } /// emscripten: _difftime -pub fn _difftime(mut _ctx: ContextMut<'_, EmEnv>, t0: u32, t1: u32) -> f64 { +pub fn _difftime(mut _ctx: FunctionEnvMut, t0: u32, t1: u32) -> f64 { debug!("emscripten::_difftime"); (t0 - t1) as _ } -pub fn _gmtime_r(mut _ctx: ContextMut<'_, EmEnv>, _one: i32, _two: i32) -> i32 { +pub fn _gmtime_r(mut _ctx: FunctionEnvMut, _one: i32, _two: i32) -> i32 { debug!("emscripten::_gmtime_r"); -1 } -pub fn _mktime(mut _ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _mktime(mut _ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_mktime"); -1 } -pub fn _gmtime(mut _ctx: ContextMut<'_, EmEnv>, _one: i32) -> i32 { +pub fn _gmtime(mut _ctx: FunctionEnvMut, _one: i32) -> i32 { debug!("emscripten::_gmtime"); -1 } @@ -171,13 +171,13 @@ struct guest_tm { } /// emscripten: _tvset -pub fn _tvset(mut _ctx: ContextMut<'_, EmEnv>) { +pub fn _tvset(mut _ctx: FunctionEnvMut) { debug!("emscripten::_tvset UNIMPLEMENTED"); } /// formats time as a C string #[allow(clippy::cast_ptr_alignment)] -unsafe fn fmt_time(ctx: ContextMut<'_, EmEnv>, time: u32) -> *const c_char { +unsafe fn fmt_time(ctx: FunctionEnvMut, time: u32) -> *const c_char { let date = &*(emscripten_memory_pointer!(ctx, ctx.data().memory(0), time) as *mut guest_tm); let days = vec!["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; @@ -202,12 +202,12 @@ unsafe fn fmt_time(ctx: ContextMut<'_, EmEnv>, time: u32) -> *const c_char { } /// emscripten: _asctime -pub fn _asctime(mut ctx: ContextMut<'_, EmEnv>, time: u32) -> u32 { +pub fn _asctime(mut ctx: FunctionEnvMut, time: u32) -> u32 { debug!("emscripten::_asctime {}", time); unsafe { - let time_str_ptr = fmt_time(ctx.as_context_mut(), time); - copy_cstr_into_wasm(ctx, time_str_ptr) + let time_str_ptr = fmt_time(ctx.as_mut(), time); + copy_cstr_into_wasm(&mut ctx, time_str_ptr) // let c_str = emscripten_memory_pointer!(ctx, ctx.data().memory(0), res) as *mut i8; // use std::ffi::CStr; @@ -216,7 +216,7 @@ pub fn _asctime(mut ctx: ContextMut<'_, EmEnv>, time: u32) -> u32 { } /// emscripten: _asctime_r -pub fn _asctime_r(mut ctx: ContextMut<'_, EmEnv>, time: u32, buf: u32) -> u32 { +pub fn _asctime_r(mut ctx: FunctionEnvMut, time: u32, buf: u32) -> u32 { debug!("emscripten::_asctime_r {}, {}", time, buf); unsafe { @@ -224,7 +224,7 @@ pub fn _asctime_r(mut ctx: ContextMut<'_, EmEnv>, time: u32, buf: u32) -> u32 { // to write out more than 26 bytes (including the null terminator). // See http://pubs.opengroup.org/onlinepubs/9699919799/functions/asctime.html // Our undefined behavior is to truncate the write to at most 26 bytes, including null terminator. - let time_str_ptr = fmt_time(ctx.as_context_mut(), time); + let time_str_ptr = fmt_time(ctx.as_mut(), time); write_to_buf(ctx, time_str_ptr, buf, 26) // let c_str = emscripten_memory_pointer!(ctx, ctx.data().memory(0), res) as *mut i8; @@ -235,7 +235,7 @@ pub fn _asctime_r(mut ctx: ContextMut<'_, EmEnv>, time: u32, buf: u32) -> u32 { /// emscripten: _localtime #[allow(clippy::cast_ptr_alignment)] -pub fn _localtime(mut ctx: ContextMut<'_, EmEnv>, time_p: u32) -> c_int { +pub fn _localtime(mut ctx: FunctionEnvMut, time_p: u32) -> c_int { debug!("emscripten::_localtime {}", time_p); // NOTE: emscripten seems to want tzset() called in this function // https://stackoverflow.com/questions/19170721/real-time-awareness-of-timezone-change-in-localtime-vs-localtime-r @@ -247,8 +247,7 @@ pub fn _localtime(mut ctx: ContextMut<'_, EmEnv>, time_p: u32) -> c_int { }; unsafe { - let tm_struct_offset = - env::call_malloc(ctx.as_context_mut(), mem::size_of::() as _); + let tm_struct_offset = env::call_malloc(&mut ctx, mem::size_of::() as _); let tm_struct_ptr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), tm_struct_offset) as *mut guest_tm; // debug!( @@ -273,7 +272,7 @@ pub fn _localtime(mut ctx: ContextMut<'_, EmEnv>, time_p: u32) -> c_int { } /// emscripten: _localtime_r #[allow(clippy::cast_ptr_alignment)] -pub fn _localtime_r(ctx: ContextMut<'_, EmEnv>, time_p: u32, result: u32) -> c_int { +pub fn _localtime_r(ctx: FunctionEnvMut, time_p: u32, result: u32) -> c_int { debug!("emscripten::_localtime_r {}", time_p); // NOTE: emscripten seems to want tzset() called in this function @@ -310,7 +309,7 @@ pub fn _localtime_r(ctx: ContextMut<'_, EmEnv>, time_p: u32, result: u32) -> c_i /// emscripten: _time #[allow(clippy::cast_ptr_alignment)] -pub fn _time(ctx: ContextMut<'_, EmEnv>, time_p: u32) -> i32 { +pub fn _time(ctx: FunctionEnvMut, time_p: u32) -> i32 { debug!("emscripten::_time {}", time_p); unsafe { @@ -319,18 +318,18 @@ pub fn _time(ctx: ContextMut<'_, EmEnv>, time_p: u32) -> i32 { } } -pub fn _ctime_r(mut ctx: ContextMut<'_, EmEnv>, time_p: u32, buf: u32) -> u32 { +pub fn _ctime_r(mut ctx: FunctionEnvMut, time_p: u32, buf: u32) -> u32 { debug!("emscripten::_ctime_r {} {}", time_p, buf); // var stack = stackSave(); let (result_offset, _result_slice): (u32, &mut [u8]) = - unsafe { allocate_on_stack(&mut ctx.as_context_mut(), 44) }; - let time = _localtime_r(ctx.as_context_mut(), time_p, result_offset) as u32; + unsafe { allocate_on_stack(&mut ctx, 44) }; + let time = _localtime_r(ctx.as_mut(), time_p, result_offset) as u32; _asctime_r(ctx, time, buf) // stackRestore(stack); } -pub fn _ctime(ctx: ContextMut<'_, EmEnv>, time_p: u32) -> u32 { +pub fn _ctime(ctx: FunctionEnvMut, time_p: u32) -> u32 { debug!("emscripten::_ctime {}", time_p); let tm_current = 2414544; _ctime_r(ctx, time_p, tm_current) @@ -339,7 +338,7 @@ pub fn _ctime(ctx: ContextMut<'_, EmEnv>, time_p: u32) -> u32 { /// emscripten: _timegm #[cfg(not(target_os = "windows"))] #[allow(clippy::cast_ptr_alignment)] -pub fn _timegm(ctx: ContextMut<'_, EmEnv>, time_ptr: u32) -> i32 { +pub fn _timegm(ctx: FunctionEnvMut, time_ptr: u32) -> i32 { debug!("emscripten::_timegm {}", time_ptr); unsafe { @@ -380,7 +379,7 @@ pub fn _timegm(ctx: ContextMut<'_, EmEnv>, time_ptr: u32) -> i32 { } #[cfg(target_os = "windows")] -pub fn _timegm(mut _ctx: ContextMut<'_, EmEnv>, _time_ptr: c_int) -> i32 { +pub fn _timegm(mut _ctx: FunctionEnvMut, _time_ptr: c_int) -> i32 { debug!( "emscripten::_timegm - UNIMPLEMENTED IN WINDOWS {}", _time_ptr @@ -390,7 +389,7 @@ pub fn _timegm(mut _ctx: ContextMut<'_, EmEnv>, _time_ptr: c_int) -> i32 { /// emscripten: _strftime pub fn _strftime( - ctx: ContextMut<'_, EmEnv>, + ctx: FunctionEnvMut, s_ptr: c_int, maxsize: u32, format_ptr: c_int, @@ -443,7 +442,7 @@ pub fn _strftime( /// emscripten: _strftime_l pub fn _strftime_l( - ctx: ContextMut<'_, EmEnv>, + ctx: FunctionEnvMut, s_ptr: c_int, maxsize: u32, format_ptr: c_int, diff --git a/lib/emscripten/src/ucontext.rs b/lib/emscripten/src/ucontext.rs index d987cb0ba1c..58c9f929bc7 100644 --- a/lib/emscripten/src/ucontext.rs +++ b/lib/emscripten/src/ucontext.rs @@ -1,12 +1,12 @@ use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; -pub fn _getcontext(mut _ctx: ContextMut<'_, EmEnv>, _ucp: i32) -> i32 { +pub fn _getcontext(mut _ctx: FunctionEnvMut, _ucp: i32) -> i32 { debug!("emscripten::_getcontext({})", _ucp); 0 } pub fn _makecontext( - mut _ctx: ContextMut<'_, EmEnv>, + mut _ctx: FunctionEnvMut, _ucp: i32, _func: i32, _argc: i32, @@ -17,11 +17,11 @@ pub fn _makecontext( _ucp, _func, _argc, _argv ); } -pub fn _setcontext(mut _ctx: ContextMut<'_, EmEnv>, _ucp: i32) -> i32 { +pub fn _setcontext(mut _ctx: FunctionEnvMut, _ucp: i32) -> i32 { debug!("emscripten::_setcontext({})", _ucp); 0 } -pub fn _swapcontext(mut _ctx: ContextMut<'_, EmEnv>, _oucp: i32, _ucp: i32) -> i32 { +pub fn _swapcontext(mut _ctx: FunctionEnvMut, _oucp: i32, _ucp: i32) -> i32 { debug!("emscripten::_swapcontext({}, {})", _oucp, _ucp); 0 } diff --git a/lib/emscripten/src/unistd.rs b/lib/emscripten/src/unistd.rs index 7a6090199bd..b6875d055ab 100644 --- a/lib/emscripten/src/unistd.rs +++ b/lib/emscripten/src/unistd.rs @@ -1,7 +1,7 @@ use crate::EmEnv; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; -pub fn confstr(mut _ctx: ContextMut<'_, EmEnv>, _name: i32, _buf_pointer: i32, _len: i32) -> i32 { +pub fn confstr(mut _ctx: FunctionEnvMut, _name: i32, _buf_pointer: i32, _len: i32) -> i32 { debug!("unistd::confstr({}, {}, {})", _name, _buf_pointer, _len); 0 } diff --git a/lib/emscripten/src/utils.rs b/lib/emscripten/src/utils.rs index 303c277fa87..b645ae00ea8 100644 --- a/lib/emscripten/src/utils.rs +++ b/lib/emscripten/src/utils.rs @@ -8,7 +8,7 @@ use std::mem::size_of; use std::os::raw::c_char; use std::path::PathBuf; use std::slice; -use wasmer::{AsContextMut, ContextMut, GlobalInit, Memory, Module, Pages, WasmPtr}; +use wasmer::{FunctionEnvMut, GlobalInit, Memory, Module, Pages, WasmPtr}; /// We check if a provided module is an Emscripten generated one pub fn is_emscripten_module(module: &Module) -> bool { @@ -94,7 +94,7 @@ pub fn get_emscripten_metadata(module: &Module) -> Result, St } pub unsafe fn write_to_buf( - ctx: ContextMut<'_, EmEnv>, + ctx: FunctionEnvMut, string: *const c_char, buf: u32, max: u32, @@ -109,10 +109,10 @@ pub unsafe fn write_to_buf( } /// This function expects nullbyte to be appended. -pub unsafe fn copy_cstr_into_wasm(mut ctx: ContextMut<'_, EmEnv>, cstr: *const c_char) -> u32 { +pub unsafe fn copy_cstr_into_wasm(ctx: &mut FunctionEnvMut, cstr: *const c_char) -> u32 { let s = CStr::from_ptr(cstr).to_str().unwrap(); let cstr_len = s.len(); - let space_offset = env::call_malloc(ctx.as_context_mut(), (cstr_len as u32) + 1); + let space_offset = env::call_malloc(ctx, (cstr_len as u32) + 1); let raw_memory = emscripten_memory_pointer!(ctx, ctx.data().memory(0), space_offset) as *mut c_char; let slice = slice::from_raw_parts_mut(raw_memory, cstr_len); @@ -131,12 +131,12 @@ pub unsafe fn copy_cstr_into_wasm(mut ctx: ContextMut<'_, EmEnv>, cstr: *const c /// # Safety /// This method is unsafe because it operates directly with the slice of memory represented by the address pub unsafe fn allocate_on_stack<'a, T: Copy>( - ctx: &mut ContextMut<'a, EmEnv>, + mut ctx: &mut FunctionEnvMut<'a, EmEnv>, count: u32, ) -> (u32, &'a mut [T]) { let stack_alloc_ref = get_emscripten_funcs(ctx).stack_alloc_ref().unwrap().clone(); let offset = stack_alloc_ref - .call(&mut ctx.as_context_mut(), count * (size_of::() as u32)) + .call(&mut ctx, count * (size_of::() as u32)) .unwrap(); let addr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), offset) as *mut T; @@ -148,7 +148,7 @@ pub unsafe fn allocate_on_stack<'a, T: Copy>( /// # Safety /// This method is unsafe because it uses `allocate_on_stack` which is unsafe pub unsafe fn allocate_cstr_on_stack<'a>( - ctx: &'a mut ContextMut<'a, EmEnv>, + ctx: &'a mut FunctionEnvMut<'a, EmEnv>, s: &str, ) -> (u32, &'a [u8]) { let (offset, slice) = allocate_on_stack(ctx, (s.len() + 1) as u32); @@ -163,7 +163,7 @@ pub unsafe fn allocate_cstr_on_stack<'a>( #[cfg(not(target_os = "windows"))] pub unsafe fn copy_terminated_array_of_cstrs( - mut _ctx: ContextMut<'_, EmEnv>, + mut _ctx: FunctionEnvMut, cstrs: *mut *mut c_char, ) -> u32 { let _total_num = { @@ -203,7 +203,7 @@ pub struct GuestStat { } #[allow(clippy::cast_ptr_alignment)] -pub unsafe fn copy_stat_into_wasm(ctx: ContextMut<'_, EmEnv>, buf: u32, stat: &stat) { +pub unsafe fn copy_stat_into_wasm(ctx: FunctionEnvMut, buf: u32, stat: &stat) { let stat_ptr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), buf) as *mut GuestStat; (*stat_ptr).st_dev = stat.st_dev as _; (*stat_ptr).__st_dev_padding = 0; @@ -231,7 +231,7 @@ pub unsafe fn copy_stat_into_wasm(ctx: ContextMut<'_, EmEnv>, buf: u32, stat: &s } #[allow(dead_code)] // it's used in `env/windows/mod.rs`. -pub fn read_string_from_wasm(ctx: ContextMut<'_, EmEnv>, memory: &Memory, offset: u32) -> String { +pub fn read_string_from_wasm(ctx: FunctionEnvMut, memory: &Memory, offset: u32) -> String { WasmPtr::::new(offset) .read_utf8_string_with_nul(&ctx, memory) .unwrap() @@ -239,7 +239,7 @@ pub fn read_string_from_wasm(ctx: ContextMut<'_, EmEnv>, memory: &Memory, offset /// This function trys to find an entry in mapdir /// translating paths into their correct value -pub fn get_cstr_path(ctx: ContextMut<'_, EmEnv>, path: *const i8) -> Option { +pub fn get_cstr_path(ctx: FunctionEnvMut, path: *const i8) -> Option { use std::collections::VecDeque; let path_str = @@ -277,7 +277,7 @@ pub fn get_cstr_path(ctx: ContextMut<'_, EmEnv>, path: *const i8) -> Option) -> Option { +pub fn get_current_directory(ctx: FunctionEnvMut) -> Option { if let Some(val) = get_emscripten_data(&ctx) .as_ref() .unwrap() diff --git a/lib/emscripten/src/varargs.rs b/lib/emscripten/src/varargs.rs index 826dc15cf9b..ab5dcf453b2 100644 --- a/lib/emscripten/src/varargs.rs +++ b/lib/emscripten/src/varargs.rs @@ -3,7 +3,7 @@ use std::mem; use wasmer::FromToNativeWasmType; // use std::ffi::CStr; use std::os::raw::c_char; -use wasmer::ContextMut; +use wasmer::FunctionEnvMut; #[repr(transparent)] #[derive(Copy, Clone)] @@ -12,14 +12,14 @@ pub struct VarArgs { } impl VarArgs { - pub fn get(&mut self, ctx: &ContextMut<'_, EmEnv>) -> T { + pub fn get(&mut self, ctx: &FunctionEnvMut) -> T { let ptr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), self.pointer); self.pointer += mem::size_of::() as u32; unsafe { (ptr as *const T).read() } } // pub fn getStr<'a>(&mut self, ctx: &mut Ctx) -> &'a CStr { - pub fn get_str(&mut self, ctx: &ContextMut<'_, EmEnv>) -> *const c_char { + pub fn get_str(&mut self, ctx: &FunctionEnvMut) -> *const c_char { let ptr_addr: u32 = self.get(ctx); let ptr = emscripten_memory_pointer!(ctx, ctx.data().memory(0), ptr_addr) as *const c_char; ptr diff --git a/lib/middlewares/src/metering.rs b/lib/middlewares/src/metering.rs index 8c9d12a107d..7c287e8d10d 100644 --- a/lib/middlewares/src/metering.rs +++ b/lib/middlewares/src/metering.rs @@ -13,7 +13,7 @@ use std::fmt; use std::sync::{Arc, Mutex}; use wasmer::wasmparser::{Operator, Type as WpType, TypeOrFuncType as WpTypeOrFuncType}; use wasmer::{ - AsContextMut, ExportIndex, FunctionMiddleware, GlobalInit, GlobalType, Instance, + AsStoreMut, ExportIndex, FunctionMiddleware, GlobalInit, GlobalType, Instance, LocalFunctionIndex, MiddlewareError, MiddlewareReaderState, ModuleMiddleware, Mutability, Type, }; use wasmer_types::{GlobalIndex, ModuleInfo}; @@ -273,16 +273,16 @@ impl u64 + Send + Sync> FunctionMiddleware for FunctionMeter /// /// ```rust /// use wasmer::Instance; -/// use wasmer::AsContextMut; +/// use wasmer::AsStoreMut; /// use wasmer_middlewares::metering::{get_remaining_points, MeteringPoints}; /// /// /// Check whether the instance can continue to run based on the /// /// number of remaining points. -/// fn can_continue_to_run(ctx: &mut impl AsContextMut, instance: &Instance) -> bool { -/// matches!(get_remaining_points(&mut ctx.as_context_mut(), instance), MeteringPoints::Remaining(points) if points > 0) +/// fn can_continue_to_run(store: &mut impl AsStoreMut, instance: &Instance) -> bool { +/// matches!(get_remaining_points(store, instance), MeteringPoints::Remaining(points) if points > 0) /// } /// ``` -pub fn get_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance) -> MeteringPoints { +pub fn get_remaining_points(ctx: &mut impl AsStoreMut, instance: &Instance) -> MeteringPoints { let exhausted: i32 = instance .exports .get_global("wasmer_metering_points_exhausted") @@ -321,18 +321,18 @@ pub fn get_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance) -> /// # Example /// /// ```rust -/// use wasmer::{AsContextMut, Instance}; +/// use wasmer::{AsStoreMut, Instance}; /// use wasmer_middlewares::metering::set_remaining_points; /// -/// fn update_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance) { +/// fn update_remaining_points(store: &mut impl AsStoreMut, instance: &Instance) { /// // The new limit. /// let new_limit = 10; /// /// // Update the remaining points to the `new_limit`. -/// set_remaining_points(&mut ctx.as_context_mut(), instance, new_limit); +/// set_remaining_points(store, instance, new_limit); /// } /// ``` -pub fn set_remaining_points(ctx: &mut impl AsContextMut, instance: &Instance, points: u64) { +pub fn set_remaining_points(ctx: &mut impl AsStoreMut, instance: &Instance, points: u64) { instance .exports .get_global("wasmer_metering_remaining_points") @@ -354,8 +354,7 @@ mod tests { use std::sync::Arc; use wasmer::{ - imports, wat2wasm, CompilerConfig, Context, Cranelift, Module, Store, TypedFunction, - Universal, + imports, wat2wasm, CompilerConfig, Cranelift, Module, Store, TypedFunction, Universal, }; fn cost_function(operator: &Operator) -> u64 { @@ -384,18 +383,16 @@ mod tests { #[test] fn get_remaining_points_works() { - use wasmer::Context as WasmerContext; let metering = Arc::new(Metering::new(10, cost_function)); let mut compiler_config = Cranelift::default(); compiler_config.push_middleware(metering); - let store = Store::new_with_engine(&Universal::new(compiler_config).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler_config).engine()); let module = Module::new(&store, bytecode()).unwrap(); - let mut ctx = Context::new(&store, ()); // Instantiate - let instance = Instance::new(&mut ctx, &module, &imports! {}).unwrap(); + let instance = Instance::new(&mut store, &module, &imports! {}).unwrap(); assert_eq!( - get_remaining_points(&mut ctx.as_context_mut(), &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Remaining(10) ); @@ -409,25 +406,25 @@ mod tests { .exports .get_function("add_one") .unwrap() - .native(&ctx) + .native(&store) .unwrap(); - add_one.call(&mut ctx.as_context_mut(), 1).unwrap(); + add_one.call(&mut store, 1).unwrap(); assert_eq!( - get_remaining_points(&mut ctx.as_context_mut(), &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Remaining(6) ); // Second call - add_one.call(&mut ctx.as_context_mut(), 1).unwrap(); + add_one.call(&mut store, 1).unwrap(); assert_eq!( - get_remaining_points(&mut ctx.as_context_mut(), &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Remaining(2) ); // Third call fails due to limit - assert!(add_one.call(&mut ctx.as_context_mut(), 1).is_err()); + assert!(add_one.call(&mut store, 1).is_err()); assert_eq!( - get_remaining_points(&mut ctx.as_context_mut(), &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Exhausted ); } @@ -437,55 +434,54 @@ mod tests { let metering = Arc::new(Metering::new(10, cost_function)); let mut compiler_config = Cranelift::default(); compiler_config.push_middleware(metering); - let store = Store::new_with_engine(&Universal::new(compiler_config).engine()); + let mut store = Store::new_with_engine(&Universal::new(compiler_config).engine()); let module = Module::new(&store, bytecode()).unwrap(); - let mut ctx = Context::new(module.store(), ()); // Instantiate - let instance = Instance::new(&mut ctx, &module, &imports! {}).unwrap(); + let instance = Instance::new(&mut store, &module, &imports! {}).unwrap(); assert_eq!( - get_remaining_points(&mut ctx, &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Remaining(10) ); let add_one: TypedFunction = instance .exports .get_function("add_one") .unwrap() - .native(&ctx) + .native(&store) .unwrap(); // Increase a bit to have enough for 3 calls - set_remaining_points(&mut ctx, &instance, 12); + set_remaining_points(&mut store, &instance, 12); // Ensure we can use the new points now - add_one.call(&mut &mut ctx, 1).unwrap(); + add_one.call(&mut store, 1).unwrap(); assert_eq!( - get_remaining_points(&mut ctx, &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Remaining(8) ); - add_one.call(&mut &mut ctx, 1).unwrap(); + add_one.call(&mut store, 1).unwrap(); assert_eq!( - get_remaining_points(&mut ctx, &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Remaining(4) ); - add_one.call(&mut &mut ctx, 1).unwrap(); + add_one.call(&mut store, 1).unwrap(); assert_eq!( - get_remaining_points(&mut ctx, &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Remaining(0) ); - assert!(add_one.call(&mut &mut ctx, 1).is_err()); + assert!(add_one.call(&mut store, 1).is_err()); assert_eq!( - get_remaining_points(&mut ctx, &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Exhausted ); // Add some points for another call - set_remaining_points(&mut ctx, &instance, 4); + set_remaining_points(&mut store, &instance, 4); assert_eq!( - get_remaining_points(&mut ctx, &instance), + get_remaining_points(&mut store, &instance), MeteringPoints::Remaining(4) ); } diff --git a/lib/vm/src/export.rs b/lib/vm/src/export.rs index b87581cbd7f..68427062f7c 100644 --- a/lib/vm/src/export.rs +++ b/lib/vm/src/export.rs @@ -1,9 +1,9 @@ // This file contains code from external sources. // Attributions: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md -use crate::context::InternalContextHandle; use crate::global::VMGlobal; use crate::memory::VMMemory; +use crate::store::InternalStoreHandle; use crate::table::VMTable; use crate::vmcontext::VMFunctionKind; use crate::{MaybeInstanceOwned, VMCallerCheckedAnyfunc}; @@ -13,16 +13,16 @@ use wasmer_types::FunctionType; /// The value of an export passed from one instance to another. pub enum VMExtern { /// A function export value. - Function(InternalContextHandle), + Function(InternalStoreHandle), /// A table export value. - Table(InternalContextHandle), + Table(InternalStoreHandle), /// A memory export value. - Memory(InternalContextHandle), + Memory(InternalStoreHandle), /// A global export value. - Global(InternalContextHandle), + Global(InternalStoreHandle), } /// A function export value. diff --git a/lib/vm/src/extern_ref.rs b/lib/vm/src/extern_ref.rs index 89657a00907..f99a7e93f51 100644 --- a/lib/vm/src/extern_ref.rs +++ b/lib/vm/src/extern_ref.rs @@ -2,7 +2,7 @@ use std::any::Any; use wasmer_types::RawValue; -use crate::context::InternalContextHandle; +use crate::store::InternalStoreHandle; /// Underlying object referenced by a `VMExternRef`. pub struct VMExternObj { @@ -27,7 +27,7 @@ impl VMExternObj { /// Represents an opaque reference to any data within WebAssembly. #[repr(transparent)] #[derive(Debug, Clone, Copy)] -pub struct VMExternRef(pub InternalContextHandle); +pub struct VMExternRef(pub InternalStoreHandle); impl VMExternRef { /// Converts the `VMExternRef` into a `RawValue`. @@ -42,6 +42,6 @@ impl VMExternRef { /// # Safety /// `raw` must be a valid `VMExternRef` instance. pub unsafe fn from_raw(raw: RawValue) -> Option { - InternalContextHandle::from_index(raw.externref).map(Self) + InternalStoreHandle::from_index(raw.externref).map(Self) } } diff --git a/lib/vm/src/function_env.rs b/lib/vm/src/function_env.rs new file mode 100644 index 00000000000..ccedf04385e --- /dev/null +++ b/lib/vm/src/function_env.rs @@ -0,0 +1,27 @@ +use std::any::Any; + +/// Underlying FunctionEnvironment used by a `VMFunction`. +pub struct VMFunctionEnvironment { + contents: Box, +} + +impl VMFunctionEnvironment { + /// Wraps the given value to expose it to Wasm code as a function context. + pub fn new(val: impl Any + Send + 'static) -> Self { + Self { + contents: Box::new(val), + } + } + + #[allow(clippy::should_implement_trait)] + /// Returns a reference to the underlying value. + pub fn as_ref(&self) -> &(dyn Any + Send + 'static) { + &*self.contents + } + + #[allow(clippy::should_implement_trait)] + /// Returns a mutable reference to the underlying value. + pub fn as_mut(&mut self) -> &mut (dyn Any + Send + 'static) { + &mut *self.contents + } +} diff --git a/lib/vm/src/global.rs b/lib/vm/src/global.rs index 5dd6f6665ac..682a66fb294 100644 --- a/lib/vm/src/global.rs +++ b/lib/vm/src/global.rs @@ -1,4 +1,4 @@ -use crate::{context::MaybeInstanceOwned, vmcontext::VMGlobalDefinition}; +use crate::{store::MaybeInstanceOwned, vmcontext::VMGlobalDefinition}; use std::{cell::UnsafeCell, ptr::NonNull}; use wasmer_types::GlobalType; diff --git a/lib/vm/src/instance/mod.rs b/lib/vm/src/instance/mod.rs index 43d843fedd6..0fefd60a651 100644 --- a/lib/vm/src/instance/mod.rs +++ b/lib/vm/src/instance/mod.rs @@ -8,18 +8,18 @@ mod allocator; -use crate::context::{ContextObjects, InternalContextHandle}; use crate::export::VMExtern; use crate::imports::Imports; use crate::memory::MemoryError; +use crate::store::{InternalStoreHandle, StoreObjects}; use crate::table::TableElement; -use crate::trap::{catch_traps, Trap, TrapCode, TrapHandler}; +use crate::trap::{catch_traps, Trap, TrapCode}; use crate::vmcontext::{ - VMBuiltinFunctionsArray, VMCallerCheckedAnyfunc, VMContext, VMFunctionEnvironment, + VMBuiltinFunctionsArray, VMCallerCheckedAnyfunc, VMContext, VMFunctionContext, VMFunctionImport, VMFunctionKind, VMGlobalDefinition, VMGlobalImport, VMMemoryDefinition, VMMemoryImport, VMSharedSignatureIndex, VMTableDefinition, VMTableImport, VMTrampoline, }; -use crate::{FunctionBodyPtr, MaybeInstanceOwned, VMFunctionBody}; +use crate::{FunctionBodyPtr, MaybeInstanceOwned, TrapHandlerFn, VMFunctionBody}; use crate::{VMFuncRef, VMFunction, VMGlobal, VMMemory, VMTable}; pub use allocator::InstanceAllocator; use memoffset::offset_of; @@ -52,19 +52,19 @@ pub(crate) struct Instance { module: Arc, /// Pointer to the object store of the context owning this instance. - context: *mut ContextObjects, + context: *mut StoreObjects, /// Offsets in the `vmctx` region. offsets: VMOffsets, /// WebAssembly linear memory data. - memories: BoxedSlice>, + memories: BoxedSlice>, /// WebAssembly table data. - tables: BoxedSlice>, + tables: BoxedSlice>, /// WebAssembly global data. - globals: BoxedSlice>, + globals: BoxedSlice>, /// Pointers to functions in executable memory. functions: BoxedSlice, @@ -119,11 +119,11 @@ impl Instance { &*self.module } - fn context(&self) -> &ContextObjects { + fn context(&self) -> &StoreObjects { unsafe { &*self.context } } - fn context_mut(&mut self) -> &mut ContextObjects { + fn context_mut(&mut self) -> &mut StoreObjects { unsafe { &mut *self.context } } @@ -283,7 +283,7 @@ impl Instance { /// Invoke the WebAssembly start function of the instance, if one is present. fn invoke_start_function( &self, - trap_handler: &(dyn TrapHandler + 'static), + trap_handler: Option<*const TrapHandlerFn<'static>>, ) -> Result<(), Trap> { let start_index = match self.module.start_function { Some(idx) => idx, @@ -299,7 +299,7 @@ impl Instance { .0; ( body as *const _, - VMFunctionEnvironment { + VMFunctionContext { vmctx: self.vmctx_ptr(), }, ) @@ -314,7 +314,7 @@ impl Instance { // Make the call. unsafe { catch_traps(trap_handler, || { - mem::transmute::<*const VMFunctionBody, unsafe extern "C" fn(VMFunctionEnvironment)>( + mem::transmute::<*const VMFunctionBody, unsafe extern "C" fn(VMFunctionContext)>( callee_address, )(callee_vmctx) }) @@ -760,7 +760,7 @@ impl Instance { pub(crate) fn get_table_handle( &mut self, table_index: TableIndex, - ) -> InternalContextHandle { + ) -> InternalStoreHandle { if let Some(local_table_index) = self.module.local_table_index(table_index) { self.tables[local_table_index] } else { @@ -816,12 +816,12 @@ impl InstanceHandle { pub unsafe fn new( allocator: InstanceAllocator, module: Arc, - context: &mut ContextObjects, + context: &mut StoreObjects, finished_functions: BoxedSlice, finished_function_call_trampolines: BoxedSlice, - finished_memories: BoxedSlice>, - finished_tables: BoxedSlice>, - finished_globals: BoxedSlice>, + finished_memories: BoxedSlice>, + finished_tables: BoxedSlice>, + finished_globals: BoxedSlice>, imports: Imports, vmshared_signatures: BoxedSlice, ) -> Result { @@ -938,7 +938,7 @@ impl InstanceHandle { /// Only safe to call immediately after instantiation. pub unsafe fn finish_instantiation( &mut self, - trap_handler: &(dyn TrapHandler + 'static), + trap_handler: Option<*const TrapHandlerFn<'static>>, data_initializers: &[DataInitializer<'_>], ) -> Result<(), Trap> { let instance = self.instance_mut(); @@ -1010,7 +1010,7 @@ impl InstanceHandle { kind: VMFunctionKind::Static, host_data: Box::new(()), }; - InternalContextHandle::new(self.instance_mut().context_mut(), vm_function) + InternalStoreHandle::new(self.instance_mut().context_mut(), vm_function) } else { let import = instance.imported_function(index); import.handle @@ -1290,7 +1290,7 @@ fn initialize_globals(instance: &Instance) { /// future funcref operations are just looking up this data. fn build_funcrefs( module_info: &ModuleInfo, - ctx: &ContextObjects, + ctx: &StoreObjects, imports: &Imports, finished_functions: &BoxedSlice, vmshared_signatures: &BoxedSlice, @@ -1318,7 +1318,7 @@ fn build_funcrefs( let anyfunc = VMCallerCheckedAnyfunc { func_ptr: func_ptr.0, type_index, - vmctx: VMFunctionEnvironment { vmctx: vmctx_ptr }, + vmctx: VMFunctionContext { vmctx: vmctx_ptr }, call_trampoline, }; func_refs.push(anyfunc); diff --git a/lib/vm/src/lib.rs b/lib/vm/src/lib.rs index 835b27bdd29..1b30f1e61e4 100644 --- a/lib/vm/src/lib.rs +++ b/lib/vm/src/lib.rs @@ -20,9 +20,9 @@ ) )] -mod context; mod export; mod extern_ref; +mod function_env; mod global; mod imports; mod instance; @@ -30,6 +30,7 @@ mod memory; mod mmap; mod probestack; mod sig_registry; +mod store; mod table; mod trap; mod vmcontext; @@ -38,11 +39,9 @@ pub mod libcalls; use std::ptr::NonNull; -pub use crate::context::{ - ContextHandle, ContextId, ContextObjects, InternalContextHandle, MaybeInstanceOwned, -}; pub use crate::export::*; pub use crate::extern_ref::{VMExternObj, VMExternRef}; +pub use crate::function_env::VMFunctionEnvironment; pub use crate::global::*; pub use crate::imports::Imports; pub use crate::instance::{InstanceAllocator, InstanceHandle}; @@ -50,10 +49,13 @@ pub use crate::memory::{MemoryError, VMMemory}; pub use crate::mmap::Mmap; pub use crate::probestack::PROBESTACK; pub use crate::sig_registry::SignatureRegistry; +pub use crate::store::{ + InternalStoreHandle, MaybeInstanceOwned, StoreHandle, StoreId, StoreObjects, +}; pub use crate::table::{TableElement, VMTable}; pub use crate::trap::*; pub use crate::vmcontext::{ - VMCallerCheckedAnyfunc, VMContext, VMDynamicFunctionContext, VMFunctionEnvironment, + VMCallerCheckedAnyfunc, VMContext, VMDynamicFunctionContext, VMFunctionContext, VMFunctionImport, VMFunctionKind, VMGlobalDefinition, VMGlobalImport, VMMemoryDefinition, VMMemoryImport, VMSharedSignatureIndex, VMTableDefinition, VMTableImport, VMTrampoline, }; diff --git a/lib/vm/src/memory.rs b/lib/vm/src/memory.rs index 52afdb90b04..098dd8501b6 100644 --- a/lib/vm/src/memory.rs +++ b/lib/vm/src/memory.rs @@ -6,7 +6,7 @@ //! `Memory` is to WebAssembly linear memories what `Table` is to WebAssembly tables. use crate::vmcontext::VMMemoryDefinition; -use crate::{context::MaybeInstanceOwned, mmap::Mmap}; +use crate::{mmap::Mmap, store::MaybeInstanceOwned}; use more_asserts::assert_ge; use std::cell::UnsafeCell; use std::convert::TryInto; diff --git a/lib/vm/src/context.rs b/lib/vm/src/store.rs similarity index 69% rename from lib/vm/src/context.rs rename to lib/vm/src/store.rs index 1b8ca708ab7..747154f9d50 100644 --- a/lib/vm/src/context.rs +++ b/lib/vm/src/store.rs @@ -9,7 +9,7 @@ use std::{ use crate::VMExternObj; -use crate::{InstanceHandle, VMFunction, VMGlobal, VMMemory, VMTable}; +use crate::{InstanceHandle, VMFunction, VMFunctionEnvironment, VMGlobal, VMMemory, VMTable}; /// Unique ID to identify a context. /// @@ -17,9 +17,9 @@ use crate::{InstanceHandle, VMFunction, VMGlobal, VMMemory, VMTable}; /// context. This is used to check that a handle is always used with the /// correct context. #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct ContextId(NonZeroU64); +pub struct StoreId(NonZeroU64); -impl Default for ContextId { +impl Default for StoreId { // Allocates a unique ID for a new context. fn default() -> Self { // No overflow checking is needed here: overflowing this would take @@ -31,18 +31,18 @@ impl Default for ContextId { /// Trait to represent an object managed by a context. This is implemented on /// the VM types managed by the context. -pub trait ContextObject: Sized { - fn list(ctx: &ContextObjects) -> &Vec; - fn list_mut(ctx: &mut ContextObjects) -> &mut Vec; +pub trait StoreObject: Sized { + fn list(ctx: &StoreObjects) -> &Vec; + fn list_mut(ctx: &mut StoreObjects) -> &mut Vec; } macro_rules! impl_context_object { ($($field:ident => $ty:ty,)*) => { $( - impl ContextObject for $ty { - fn list(ctx: &ContextObjects) -> &Vec { + impl StoreObject for $ty { + fn list(ctx: &StoreObjects) -> &Vec { &ctx.$field } - fn list_mut(ctx: &mut ContextObjects) -> &mut Vec { + fn list_mut(ctx: &mut StoreObjects) -> &mut Vec { &mut ctx.$field } } @@ -56,33 +56,35 @@ impl_context_object! { instances => InstanceHandle, memories => VMMemory, extern_objs => VMExternObj, + function_environments => VMFunctionEnvironment, } /// Set of objects managed by a context. #[derive(Default)] -pub struct ContextObjects { - id: ContextId, +pub struct StoreObjects { + id: StoreId, memories: Vec, tables: Vec, globals: Vec, functions: Vec, instances: Vec, extern_objs: Vec, + function_environments: Vec, } -impl ContextObjects { +impl StoreObjects { /// Returns the ID of this context. - pub fn id(&self) -> ContextId { + pub fn id(&self) -> StoreId { self.id } /// Returns a pair of mutable references from two handles. /// /// Panics if both handles point to the same object. - pub fn get_2_mut( + pub fn get_2_mut( &mut self, - a: InternalContextHandle, - b: InternalContextHandle, + a: InternalStoreHandle, + b: InternalStoreHandle, ) -> (&mut T, &mut T) { assert_ne!(a.index(), b.index()); let list = T::list_mut(self); @@ -100,12 +102,12 @@ impl ContextObjects { /// /// Internally this is just an integer index into a context. A reference to the /// context must be passed in separately to access the actual object. -pub struct ContextHandle { - id: ContextId, - internal: InternalContextHandle, +pub struct StoreHandle { + id: StoreId, + internal: InternalStoreHandle, } -impl Clone for ContextHandle { +impl Clone for StoreHandle { fn clone(&self) -> Self { Self { id: self.id, @@ -114,98 +116,98 @@ impl Clone for ContextHandle { } } -impl fmt::Debug for ContextHandle { +impl fmt::Debug for StoreHandle { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ContextHandle") + f.debug_struct("StoreHandle") .field("id", &self.id) .field("internal", &self.internal.index()) .finish() } } -impl PartialEq for ContextHandle { +impl PartialEq for StoreHandle { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.internal == other.internal } } -impl Eq for ContextHandle {} +impl Eq for StoreHandle {} -impl ContextHandle { +impl StoreHandle { /// Moves the given object into a context and returns a handle to it. - pub fn new(ctx: &mut ContextObjects, val: T) -> Self { + pub fn new(ctx: &mut StoreObjects, val: T) -> Self { Self { id: ctx.id, - internal: InternalContextHandle::new(ctx, val), + internal: InternalStoreHandle::new(ctx, val), } } /// Returns a reference to the object that this handle points to. - pub fn get<'a>(&self, ctx: &'a ContextObjects) -> &'a T { + pub fn get<'a>(&self, ctx: &'a StoreObjects) -> &'a T { assert_eq!(self.id, ctx.id, "object used with the wrong context"); self.internal.get(ctx) } /// Returns a mutable reference to the object that this handle points to. - pub fn get_mut<'a>(&self, ctx: &'a mut ContextObjects) -> &'a mut T { + pub fn get_mut<'a>(&self, ctx: &'a mut StoreObjects) -> &'a mut T { assert_eq!(self.id, ctx.id, "object used with the wrong context"); self.internal.get_mut(ctx) } /// Returns the internal handle contains within this handle. - pub fn internal_handle(&self) -> InternalContextHandle { + pub fn internal_handle(&self) -> InternalStoreHandle { self.internal } /// Returns the ID of the context associated with the handle. - pub fn context_id(&self) -> ContextId { + pub fn store_id(&self) -> StoreId { self.id } - /// Constructs a `ContextHandle` from a `ContextId` and an `InternalContextHandle`. + /// Constructs a `StoreHandle` from a `StoreId` and an `InternalStoreHandle`. /// /// # Safety - /// Handling `InternalContextHandle` values is unsafe because they do not track context ID. - pub unsafe fn from_internal(id: ContextId, internal: InternalContextHandle) -> Self { + /// Handling `InternalStoreHandle` values is unsafe because they do not track context ID. + pub unsafe fn from_internal(id: StoreId, internal: InternalStoreHandle) -> Self { Self { id, internal } } } /// Internal handle to an object owned by the current context. /// -/// Unlike `ContextHandle` this does not track the context ID: it is only +/// Unlike `StoreHandle` this does not track the context ID: it is only /// intended to be used within objects already owned by a context. #[repr(transparent)] -pub struct InternalContextHandle { - // Use a NonZero here to reduce the size of Option. +pub struct InternalStoreHandle { + // Use a NonZero here to reduce the size of Option. idx: NonZeroUsize, marker: PhantomData T>, } -impl Clone for InternalContextHandle { +impl Clone for InternalStoreHandle { fn clone(&self) -> Self { *self } } -impl Copy for InternalContextHandle {} +impl Copy for InternalStoreHandle {} -impl fmt::Debug for InternalContextHandle { +impl fmt::Debug for InternalStoreHandle { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("InternalContextHandle") + f.debug_struct("InternalStoreHandle") .field("idx", &self.idx) .finish() } } -impl PartialEq for InternalContextHandle { +impl PartialEq for InternalStoreHandle { fn eq(&self, other: &Self) -> bool { self.idx == other.idx } } -impl Eq for InternalContextHandle {} +impl Eq for InternalStoreHandle {} -impl InternalContextHandle { +impl InternalStoreHandle { /// Moves the given object into a context and returns a handle to it. - pub fn new(ctx: &mut ContextObjects, val: T) -> Self { + pub fn new(ctx: &mut StoreObjects, val: T) -> Self { let list = T::list_mut(ctx); let idx = NonZeroUsize::new(list.len() + 1).unwrap(); list.push(val); @@ -216,12 +218,12 @@ impl InternalContextHandle { } /// Returns a reference to the object that this handle points to. - pub fn get<'a>(&self, ctx: &'a ContextObjects) -> &'a T { + pub fn get<'a>(&self, ctx: &'a StoreObjects) -> &'a T { &T::list(ctx)[self.idx.get() - 1] } /// Returns a mutable reference to the object that this handle points to. - pub fn get_mut<'a>(&self, ctx: &'a mut ContextObjects) -> &'a mut T { + pub fn get_mut<'a>(&self, ctx: &'a mut StoreObjects) -> &'a mut T { &mut T::list_mut(ctx)[self.idx.get() - 1] } diff --git a/lib/vm/src/table.rs b/lib/vm/src/table.rs index 364a81f11ff..bdc5e5fdbaa 100644 --- a/lib/vm/src/table.rs +++ b/lib/vm/src/table.rs @@ -5,7 +5,7 @@ //! //! `Table` is to WebAssembly tables what `Memory` is to WebAssembly linear memories. -use crate::context::MaybeInstanceOwned; +use crate::store::MaybeInstanceOwned; use crate::vmcontext::VMTableDefinition; use crate::Trap; use crate::VMExternRef; diff --git a/lib/vm/src/trap/traphandlers.rs b/lib/vm/src/trap/traphandlers.rs index 263e532845e..365237a4225 100644 --- a/lib/vm/src/trap/traphandlers.rs +++ b/lib/vm/src/trap/traphandlers.rs @@ -4,7 +4,7 @@ //! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. -use crate::vmcontext::{VMFunctionEnvironment, VMTrampoline}; +use crate::vmcontext::{VMFunctionContext, VMTrampoline}; use crate::{Trap, VMFunctionBody}; use backtrace::Backtrace; use core::ptr::{read, read_unaligned}; @@ -32,10 +32,10 @@ static MAGIC: u8 = 0xc0; cfg_if::cfg_if! { if #[cfg(unix)] { /// Function which may handle custom signals while processing traps. - pub type TrapHandlerFn = dyn Fn(libc::c_int, *const libc::siginfo_t, *const libc::c_void) -> bool; + pub type TrapHandlerFn<'a> = dyn Fn(libc::c_int, *const libc::siginfo_t, *const libc::c_void) -> bool + Send + Sync + 'a; } else if #[cfg(target_os = "windows")] { /// Function which may handle custom signals while processing traps. - pub type TrapHandlerFn = dyn Fn(winapi::um::winnt::PEXCEPTION_POINTERS) -> bool; + pub type TrapHandlerFn<'a> = dyn Fn(winapi::um::winnt::PEXCEPTION_POINTERS) -> bool + Send + Sync + 'a; } } @@ -611,14 +611,14 @@ pub unsafe fn resume_panic(payload: Box) -> ! { /// Wildly unsafe because it calls raw function pointers and reads/writes raw /// function pointers. pub unsafe fn wasmer_call_trampoline( - trap_handler: &(impl TrapHandler + 'static), - vmctx: VMFunctionEnvironment, + trap_handler: Option<*const TrapHandlerFn<'static>>, + vmctx: VMFunctionContext, trampoline: VMTrampoline, callee: *const VMFunctionBody, values_vec: *mut u8, ) -> Result<(), Trap> { catch_traps(trap_handler, || { - mem::transmute::<_, extern "C" fn(VMFunctionEnvironment, *const VMFunctionBody, *mut u8)>( + mem::transmute::<_, extern "C" fn(VMFunctionContext, *const VMFunctionBody, *mut u8)>( trampoline, )(vmctx, callee, values_vec); }) @@ -631,7 +631,7 @@ pub unsafe fn wasmer_call_trampoline( /// /// Highly unsafe since `closure` won't have any dtors run. pub unsafe fn catch_traps( - trap_handler: &(dyn TrapHandler + 'static), + trap_handler: Option<*const TrapHandlerFn<'static>>, closure: F, ) -> Result where @@ -669,7 +669,7 @@ struct TrapHandlerContext { Option, &mut dyn FnMut(TrapHandlerRegs), ) -> bool, - custom_trap: *const dyn TrapHandler, + custom_trap: Option<*const TrapHandlerFn<'static>>, } struct TrapHandlerContextInner { /// Information about the currently running coroutine. This is used to @@ -681,7 +681,7 @@ impl TrapHandlerContext { /// Runs the given function with a trap handler context. The previous /// trap handler context is preserved and restored afterwards. fn install( - custom_trap: &(dyn TrapHandler + 'static), + custom_trap: Option<*const TrapHandlerFn<'static>>, coro_trap_handler: CoroutineTrapHandler>, f: impl FnOnce() -> R, ) -> R { @@ -733,7 +733,7 @@ impl TrapHandlerContext { maybe_fault_address: Option, trap_code: Option, mut update_regs: impl FnMut(TrapHandlerRegs), - call_handler: impl Fn(&TrapHandlerFn) -> bool, + call_handler: impl Fn(&TrapHandlerFn<'static>) -> bool, ) -> bool { let ptr = TRAP_HANDLER.with(|ptr| ptr.load(Ordering::Relaxed)); if ptr.is_null() { @@ -743,8 +743,10 @@ impl TrapHandlerContext { let ctx = &*ptr; // Check if this trap is handled by a custom trap handler. - if (*ctx.custom_trap).custom_trap_handler(&call_handler) { - return true; + if let Some(trap_handler) = ctx.custom_trap { + if call_handler(&*trap_handler) { + return true; + } } (ctx.handle_trap)( @@ -855,7 +857,7 @@ unsafe fn unwind_with(reason: UnwindReason) -> ! { /// bounded. Stack overflows and other traps can be caught and execution /// returned to the root of the stack. fn on_wasm_stack T, T>( - trap_handler: &(dyn TrapHandler + 'static), + trap_handler: Option<*const TrapHandlerFn<'static>>, f: F, ) -> Result { // Allocating a new stack is pretty expensive since it involves several diff --git a/lib/vm/src/vmcontext.rs b/lib/vm/src/vmcontext.rs index 158e6ca5913..edc3bf4d40e 100644 --- a/lib/vm/src/vmcontext.rs +++ b/lib/vm/src/vmcontext.rs @@ -4,10 +4,10 @@ //! This file declares `VMContext` and several related structs which contain //! fields that compiled wasm code accesses directly. -use crate::context::InternalContextHandle; use crate::global::VMGlobal; use crate::instance::Instance; use crate::memory::VMMemory; +use crate::store::InternalStoreHandle; use crate::trap::{Trap, TrapCode}; use crate::VMFunctionBody; use crate::VMTable; @@ -22,35 +22,35 @@ use wasmer_types::RawValue; /// It may either be a pointer to the [`VMContext`] if it's a Wasm function /// or a pointer to arbitrary data controlled by the host if it's a host function. #[derive(Copy, Clone, Eq)] -pub union VMFunctionEnvironment { +pub union VMFunctionContext { /// Wasm functions take a pointer to [`VMContext`]. pub vmctx: *mut VMContext, /// Host functions can have custom environments. pub host_env: *mut std::ffi::c_void, } -impl VMFunctionEnvironment { +impl VMFunctionContext { /// Check whether the pointer stored is null or not. pub fn is_null(&self) -> bool { unsafe { self.host_env.is_null() } } } -impl std::fmt::Debug for VMFunctionEnvironment { +impl std::fmt::Debug for VMFunctionContext { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.debug_struct("VMFunctionEnvironment") + f.debug_struct("VMFunctionContext") .field("vmctx_or_hostenv", unsafe { &self.host_env }) .finish() } } -impl std::cmp::PartialEq for VMFunctionEnvironment { +impl std::cmp::PartialEq for VMFunctionContext { fn eq(&self, rhs: &Self) -> bool { unsafe { self.host_env as usize == rhs.host_env as usize } } } -impl std::hash::Hash for VMFunctionEnvironment { +impl std::hash::Hash for VMFunctionContext { fn hash(&self, state: &mut H) { unsafe { self.vmctx.hash(state); @@ -66,10 +66,10 @@ pub struct VMFunctionImport { pub body: *const VMFunctionBody, /// A pointer to the `VMContext` that owns the function or host env data. - pub environment: VMFunctionEnvironment, + pub environment: VMFunctionContext, /// Handle to the `VMFunction` in the context. - pub handle: InternalContextHandle, + pub handle: InternalStoreHandle, } #[cfg(test)] @@ -191,7 +191,7 @@ pub struct VMTableImport { pub definition: NonNull, /// Handle to the `VMTable` in the context. - pub handle: InternalContextHandle, + pub handle: InternalStoreHandle, } #[cfg(test)] @@ -226,7 +226,7 @@ pub struct VMMemoryImport { pub definition: NonNull, /// A handle to the `Memory` that owns the memory description. - pub handle: InternalContextHandle, + pub handle: InternalStoreHandle, } #[cfg(test)] @@ -265,7 +265,7 @@ pub struct VMGlobalImport { pub definition: NonNull, /// A handle to the `Global` that owns the global description. - pub handle: InternalContextHandle, + pub handle: InternalStoreHandle, } /// # Safety @@ -569,7 +569,7 @@ pub struct VMCallerCheckedAnyfunc { /// Function signature id. pub type_index: VMSharedSignatureIndex, /// Function `VMContext` or host env. - pub vmctx: VMFunctionEnvironment, + pub vmctx: VMFunctionContext, /// Address of the function call trampoline to invoke this function using /// a dynamic argument list. pub call_trampoline: VMTrampoline, diff --git a/lib/wasi/README.md b/lib/wasi/README.md index f2b97bb105b..86edd228817 100644 --- a/lib/wasi/README.md +++ b/lib/wasi/README.md @@ -57,7 +57,7 @@ Hello, Some("Gordon") use wasmer::{Store, Module, Instance}; use wasmer_wasi::WasiState; -let store = Store::default(); +let mut store = Store::default(); let module = Module::from_file(&store, "hello.wasm")?; // Create the `WasiEnv`. diff --git a/lib/wasi/src/lib.rs b/lib/wasi/src/lib.rs index 69c0f6b1cac..abc96368fc2 100644 --- a/lib/wasi/src/lib.rs +++ b/lib/wasi/src/lib.rs @@ -50,7 +50,6 @@ pub use crate::syscalls::types; pub use crate::utils::{ get_wasi_version, get_wasi_versions, is_wasi_module, is_wasix_module, WasiVersion, }; -use wasmer::ContextMut; pub use wasmer_vbus::{UnsupportedVirtualBus, VirtualBus}; #[deprecated(since = "2.1.0", note = "Please use `wasmer_vfs::FsError`")] pub use wasmer_vfs::FsError as WasiFsError; @@ -64,7 +63,7 @@ use derivative::*; use std::ops::Deref; use thiserror::Error; use wasmer::{ - imports, namespace, AsContextMut, Exports, Function, Imports, Memory, Memory32, + imports, namespace, AsStoreMut, Exports, Function, FunctionEnv, Imports, Memory, Memory32, MemoryAccessError, MemorySize, Module, TypedFunction, }; @@ -143,6 +142,65 @@ impl WasiThread { } } +pub struct WasiFunctionEnv { + pub env: FunctionEnv, +} + +impl WasiFunctionEnv { + pub fn new(store: &mut impl AsStoreMut, env: WasiEnv) -> Self { + Self { + env: FunctionEnv::new(store, env), + } + } + + /// Get an `Imports` for a specific version of WASI detected in the module. + pub fn import_object( + &self, + store: &mut impl AsStoreMut, + module: &Module, + ) -> Result { + let wasi_version = get_wasi_version(module, false).ok_or(WasiError::UnknownWasiVersion)?; + Ok(generate_import_object_from_env( + store, + &self.env, + wasi_version, + )) + } + + pub fn data_mut<'a>(&'a self, store: &'a mut impl AsStoreMut) -> &'a mut WasiEnv { + self.env.as_mut(store) + } + + /// Like `import_object` but containing all the WASI versions detected in + /// the module. + pub fn import_object_for_all_wasi_versions( + &self, + store: &mut impl AsStoreMut, + module: &Module, + ) -> Result { + let wasi_versions = + get_wasi_versions(module, false).ok_or(WasiError::UnknownWasiVersion)?; + + let mut resolver = Imports::new(); + for version in wasi_versions.iter() { + let new_import_object = generate_import_object_from_env(store, &self.env, *version); + for ((n, m), e) in new_import_object.into_iter() { + resolver.define(&n, &m, e); + } + } + + if is_wasix_module(module) { + self.data_mut(store) + .state + .fs + .is_wasix + .store(true, std::sync::atomic::Ordering::Release); + } + + Ok(resolver) + } +} + /// The environment provided to the WASI imports. #[derive(Derivative, Clone)] #[derivative(Debug)] @@ -229,45 +287,6 @@ impl WasiEnv { self.memory.clone() } - /// Get an `Imports` for a specific version of WASI detected in the module. - pub fn import_object( - &mut self, - ctx: &mut ContextMut<'_, WasiEnv>, - module: &Module, - ) -> Result { - let wasi_version = get_wasi_version(module, false).ok_or(WasiError::UnknownWasiVersion)?; - Ok(generate_import_object_from_ctx(ctx, wasi_version)) - } - - /// Like `import_object` but containing all the WASI versions detected in - /// the module. - pub fn import_object_for_all_wasi_versions( - &mut self, - ctx: &mut ContextMut<'_, WasiEnv>, - module: &Module, - ) -> Result { - let wasi_versions = - get_wasi_versions(module, false).ok_or(WasiError::UnknownWasiVersion)?; - - let mut resolver = Imports::new(); - for version in wasi_versions.iter() { - let new_import_object = - generate_import_object_from_ctx(&mut ctx.as_context_mut(), *version); - for ((n, m), e) in new_import_object.into_iter() { - resolver.define(&n, &m, e); - } - } - - if is_wasix_module(module) { - self.state - .fs - .is_wasix - .store(true, std::sync::atomic::Ordering::Release); - } - - Ok(resolver) - } - // Yields execution pub fn yield_now(&self) -> Result<(), WasiError> { self.runtime.yield_now(self.id)?; @@ -357,122 +376,131 @@ impl WasiEnv { } /// Create an [`Imports`] from a [`Context`] -pub fn generate_import_object_from_ctx( - ctx: &mut ContextMut<'_, WasiEnv>, +pub fn generate_import_object_from_env( + store: &mut impl AsStoreMut, + ctx: &FunctionEnv, version: WasiVersion, ) -> Imports { match version { - WasiVersion::Snapshot0 => generate_import_object_snapshot0(ctx), - WasiVersion::Snapshot1 | WasiVersion::Latest => generate_import_object_snapshot1(ctx), - WasiVersion::Wasix32v1 => generate_import_object_wasix32_v1(ctx), - WasiVersion::Wasix64v1 => generate_import_object_wasix64_v1(ctx), + WasiVersion::Snapshot0 => generate_import_object_snapshot0(store, ctx), + WasiVersion::Snapshot1 | WasiVersion::Latest => { + generate_import_object_snapshot1(store, ctx) + } + WasiVersion::Wasix32v1 => generate_import_object_wasix32_v1(store, ctx), + WasiVersion::Wasix64v1 => generate_import_object_wasix64_v1(store, ctx), } } -fn wasi_unstable_exports(ctx: &mut ContextMut<'_, WasiEnv>) -> Exports { +fn wasi_unstable_exports(mut store: &mut impl AsStoreMut, ctx: &FunctionEnv) -> Exports { let namespace = namespace! { - "args_get" => Function::new_native(ctx, args_get::), - "args_sizes_get" => Function::new_native(ctx, args_sizes_get::), - "clock_res_get" => Function::new_native(ctx, clock_res_get::), - "clock_time_get" => Function::new_native(ctx, clock_time_get::), - "environ_get" => Function::new_native(ctx, environ_get::), - "environ_sizes_get" => Function::new_native(ctx, environ_sizes_get::), - "fd_advise" => Function::new_native(ctx, fd_advise), - "fd_allocate" => Function::new_native(ctx, fd_allocate), - "fd_close" => Function::new_native(ctx, fd_close), - "fd_datasync" => Function::new_native(ctx, fd_datasync), - "fd_fdstat_get" => Function::new_native(ctx, fd_fdstat_get::), - "fd_fdstat_set_flags" => Function::new_native(ctx, fd_fdstat_set_flags), - "fd_fdstat_set_rights" => Function::new_native(ctx, fd_fdstat_set_rights), - "fd_filestat_get" => Function::new_native(ctx, legacy::snapshot0::fd_filestat_get), - "fd_filestat_set_size" => Function::new_native(ctx, fd_filestat_set_size), - "fd_filestat_set_times" => Function::new_native(ctx, fd_filestat_set_times), - "fd_pread" => Function::new_native(ctx, fd_pread::), - "fd_prestat_get" => Function::new_native(ctx, fd_prestat_get::), - "fd_prestat_dir_name" => Function::new_native(ctx, fd_prestat_dir_name::), - "fd_pwrite" => Function::new_native(ctx, fd_pwrite::), - "fd_read" => Function::new_native(ctx, fd_read::), - "fd_readdir" => Function::new_native(ctx, fd_readdir::), - "fd_renumber" => Function::new_native(ctx, fd_renumber), - "fd_seek" => Function::new_native(ctx, legacy::snapshot0::fd_seek), - "fd_sync" => Function::new_native(ctx, fd_sync), - "fd_tell" => Function::new_native(ctx, fd_tell::), - "fd_write" => Function::new_native(ctx, fd_write::), - "path_create_directory" => Function::new_native(ctx, path_create_directory::), - "path_filestat_get" => Function::new_native(ctx, legacy::snapshot0::path_filestat_get), - "path_filestat_set_times" => Function::new_native(ctx, path_filestat_set_times::), - "path_link" => Function::new_native(ctx, path_link::), - "path_open" => Function::new_native(ctx, path_open::), - "path_readlink" => Function::new_native(ctx, path_readlink::), - "path_remove_directory" => Function::new_native(ctx, path_remove_directory::), - "path_rename" => Function::new_native(ctx, path_rename::), - "path_symlink" => Function::new_native(ctx, path_symlink::), - "path_unlink_file" => Function::new_native(ctx, path_unlink_file::), - "poll_oneoff" => Function::new_native(ctx, legacy::snapshot0::poll_oneoff), - "proc_exit" => Function::new_native(ctx, proc_exit), - "proc_raise" => Function::new_native(ctx, proc_raise), - "random_get" => Function::new_native(ctx, random_get::), - "sched_yield" => Function::new_native(ctx, sched_yield), - "sock_recv" => Function::new_native(ctx, sock_recv::), - "sock_send" => Function::new_native(ctx, sock_send::), - "sock_shutdown" => Function::new_native(ctx, sock_shutdown), + "args_get" => Function::new_native(&mut store, ctx, args_get::), + "args_sizes_get" => Function::new_native(&mut store, ctx, args_sizes_get::), + "clock_res_get" => Function::new_native(&mut store, ctx, clock_res_get::), + "clock_time_get" => Function::new_native(&mut store, ctx, clock_time_get::), + "environ_get" => Function::new_native(&mut store, ctx, environ_get::), + "environ_sizes_get" => Function::new_native(&mut store, ctx, environ_sizes_get::), + "fd_advise" => Function::new_native(&mut store, ctx, fd_advise), + "fd_allocate" => Function::new_native(&mut store, ctx, fd_allocate), + "fd_close" => Function::new_native(&mut store, ctx, fd_close), + "fd_datasync" => Function::new_native(&mut store, ctx, fd_datasync), + "fd_fdstat_get" => Function::new_native(&mut store, ctx, fd_fdstat_get::), + "fd_fdstat_set_flags" => Function::new_native(&mut store, ctx, fd_fdstat_set_flags), + "fd_fdstat_set_rights" => Function::new_native(&mut store, ctx, fd_fdstat_set_rights), + "fd_filestat_get" => Function::new_native(&mut store, ctx, legacy::snapshot0::fd_filestat_get), + "fd_filestat_set_size" => Function::new_native(&mut store, ctx, fd_filestat_set_size), + "fd_filestat_set_times" => Function::new_native(&mut store, ctx, fd_filestat_set_times), + "fd_pread" => Function::new_native(&mut store, ctx, fd_pread::), + "fd_prestat_get" => Function::new_native(&mut store, ctx, fd_prestat_get::), + "fd_prestat_dir_name" => Function::new_native(&mut store, ctx, fd_prestat_dir_name::), + "fd_pwrite" => Function::new_native(&mut store, ctx, fd_pwrite::), + "fd_read" => Function::new_native(&mut store, ctx, fd_read::), + "fd_readdir" => Function::new_native(&mut store, ctx, fd_readdir::), + "fd_renumber" => Function::new_native(&mut store, ctx, fd_renumber), + "fd_seek" => Function::new_native(&mut store, ctx, legacy::snapshot0::fd_seek), + "fd_sync" => Function::new_native(&mut store, ctx, fd_sync), + "fd_tell" => Function::new_native(&mut store, ctx, fd_tell::), + "fd_write" => Function::new_native(&mut store, ctx, fd_write::), + "path_create_directory" => Function::new_native(&mut store, ctx, path_create_directory::), + "path_filestat_get" => Function::new_native(&mut store, ctx, legacy::snapshot0::path_filestat_get), + "path_filestat_set_times" => Function::new_native(&mut store, ctx, path_filestat_set_times::), + "path_link" => Function::new_native(&mut store, ctx, path_link::), + "path_open" => Function::new_native(&mut store, ctx, path_open::), + "path_readlink" => Function::new_native(&mut store, ctx, path_readlink::), + "path_remove_directory" => Function::new_native(&mut store, ctx, path_remove_directory::), + "path_rename" => Function::new_native(&mut store, ctx, path_rename::), + "path_symlink" => Function::new_native(&mut store, ctx, path_symlink::), + "path_unlink_file" => Function::new_native(&mut store, ctx, path_unlink_file::), + "poll_oneoff" => Function::new_native(&mut store, ctx, legacy::snapshot0::poll_oneoff), + "proc_exit" => Function::new_native(&mut store, ctx, proc_exit), + "proc_raise" => Function::new_native(&mut store, ctx, proc_raise), + "random_get" => Function::new_native(&mut store, ctx, random_get::), + "sched_yield" => Function::new_native(&mut store, ctx, sched_yield), + "sock_recv" => Function::new_native(&mut store, ctx, sock_recv::), + "sock_send" => Function::new_native(&mut store, ctx, sock_send::), + "sock_shutdown" => Function::new_native(&mut store, ctx, sock_shutdown), }; namespace } -fn wasi_snapshot_preview1_exports(ctx: &mut ContextMut<'_, WasiEnv>) -> Exports { +fn wasi_snapshot_preview1_exports( + mut store: &mut impl AsStoreMut, + ctx: &FunctionEnv, +) -> Exports { let namespace = namespace! { - "args_get" => Function::new_native(ctx, args_get::), - "args_sizes_get" => Function::new_native(ctx, args_sizes_get::), - "clock_res_get" => Function::new_native(ctx, clock_res_get::), - "clock_time_get" => Function::new_native(ctx, clock_time_get::), - "environ_get" => Function::new_native(ctx, environ_get::), - "environ_sizes_get" => Function::new_native(ctx, environ_sizes_get::), - "fd_advise" => Function::new_native(ctx, fd_advise), - "fd_allocate" => Function::new_native(ctx, fd_allocate), - "fd_close" => Function::new_native(ctx, fd_close), - "fd_datasync" => Function::new_native(ctx, fd_datasync), - "fd_fdstat_get" => Function::new_native(ctx, fd_fdstat_get::), - "fd_fdstat_set_flags" => Function::new_native(ctx, fd_fdstat_set_flags), - "fd_fdstat_set_rights" => Function::new_native(ctx, fd_fdstat_set_rights), - "fd_filestat_get" => Function::new_native(ctx, fd_filestat_get::), - "fd_filestat_set_size" => Function::new_native(ctx, fd_filestat_set_size), - "fd_filestat_set_times" => Function::new_native(ctx, fd_filestat_set_times), - "fd_pread" => Function::new_native(ctx, fd_pread::), - "fd_prestat_get" => Function::new_native(ctx, fd_prestat_get::), - "fd_prestat_dir_name" => Function::new_native(ctx, fd_prestat_dir_name::), - "fd_pwrite" => Function::new_native(ctx, fd_pwrite::), - "fd_read" => Function::new_native(ctx, fd_read::), - "fd_readdir" => Function::new_native(ctx, fd_readdir::), - "fd_renumber" => Function::new_native(ctx, fd_renumber), - "fd_seek" => Function::new_native(ctx, fd_seek::), - "fd_sync" => Function::new_native(ctx, fd_sync), - "fd_tell" => Function::new_native(ctx, fd_tell::), - "fd_write" => Function::new_native(ctx, fd_write::), - "path_create_directory" => Function::new_native(ctx, path_create_directory::), - "path_filestat_get" => Function::new_native(ctx, path_filestat_get::), - "path_filestat_set_times" => Function::new_native(ctx, path_filestat_set_times::), - "path_link" => Function::new_native(ctx, path_link::), - "path_open" => Function::new_native(ctx, path_open::), - "path_readlink" => Function::new_native(ctx, path_readlink::), - "path_remove_directory" => Function::new_native(ctx, path_remove_directory::), - "path_rename" => Function::new_native(ctx, path_rename::), - "path_symlink" => Function::new_native(ctx, path_symlink::), - "path_unlink_file" => Function::new_native(ctx, path_unlink_file::), - "poll_oneoff" => Function::new_native(ctx, poll_oneoff::), - "proc_exit" => Function::new_native(ctx, proc_exit), - "proc_raise" => Function::new_native(ctx, proc_raise), - "random_get" => Function::new_native(ctx, random_get::), - "sched_yield" => Function::new_native(ctx, sched_yield), - "sock_recv" => Function::new_native(ctx, sock_recv::), - "sock_send" => Function::new_native(ctx, sock_send::), - "sock_shutdown" => Function::new_native(ctx, sock_shutdown), + "args_get" => Function::new_native(&mut store, ctx, args_get::), + "args_sizes_get" => Function::new_native(&mut store, ctx, args_sizes_get::), + "clock_res_get" => Function::new_native(&mut store, ctx, clock_res_get::), + "clock_time_get" => Function::new_native(&mut store, ctx, clock_time_get::), + "environ_get" => Function::new_native(&mut store, ctx, environ_get::), + "environ_sizes_get" => Function::new_native(&mut store, ctx, environ_sizes_get::), + "fd_advise" => Function::new_native(&mut store, ctx, fd_advise), + "fd_allocate" => Function::new_native(&mut store, ctx, fd_allocate), + "fd_close" => Function::new_native(&mut store, ctx, fd_close), + "fd_datasync" => Function::new_native(&mut store, ctx, fd_datasync), + "fd_fdstat_get" => Function::new_native(&mut store, ctx, fd_fdstat_get::), + "fd_fdstat_set_flags" => Function::new_native(&mut store, ctx, fd_fdstat_set_flags), + "fd_fdstat_set_rights" => Function::new_native(&mut store, ctx, fd_fdstat_set_rights), + "fd_filestat_get" => Function::new_native(&mut store, ctx, fd_filestat_get::), + "fd_filestat_set_size" => Function::new_native(&mut store, ctx, fd_filestat_set_size), + "fd_filestat_set_times" => Function::new_native(&mut store, ctx, fd_filestat_set_times), + "fd_pread" => Function::new_native(&mut store, ctx, fd_pread::), + "fd_prestat_get" => Function::new_native(&mut store, ctx, fd_prestat_get::), + "fd_prestat_dir_name" => Function::new_native(&mut store, ctx, fd_prestat_dir_name::), + "fd_pwrite" => Function::new_native(&mut store, ctx, fd_pwrite::), + "fd_read" => Function::new_native(&mut store, ctx, fd_read::), + "fd_readdir" => Function::new_native(&mut store, ctx, fd_readdir::), + "fd_renumber" => Function::new_native(&mut store, ctx, fd_renumber), + "fd_seek" => Function::new_native(&mut store, ctx, fd_seek::), + "fd_sync" => Function::new_native(&mut store, ctx, fd_sync), + "fd_tell" => Function::new_native(&mut store, ctx, fd_tell::), + "fd_write" => Function::new_native(&mut store, ctx, fd_write::), + "path_create_directory" => Function::new_native(&mut store, ctx, path_create_directory::), + "path_filestat_get" => Function::new_native(&mut store, ctx, path_filestat_get::), + "path_filestat_set_times" => Function::new_native(&mut store, ctx, path_filestat_set_times::), + "path_link" => Function::new_native(&mut store, ctx, path_link::), + "path_open" => Function::new_native(&mut store, ctx, path_open::), + "path_readlink" => Function::new_native(&mut store, ctx, path_readlink::), + "path_remove_directory" => Function::new_native(&mut store, ctx, path_remove_directory::), + "path_rename" => Function::new_native(&mut store, ctx, path_rename::), + "path_symlink" => Function::new_native(&mut store, ctx, path_symlink::), + "path_unlink_file" => Function::new_native(&mut store, ctx, path_unlink_file::), + "poll_oneoff" => Function::new_native(&mut store, ctx, poll_oneoff::), + "proc_exit" => Function::new_native(&mut store, ctx, proc_exit), + "proc_raise" => Function::new_native(&mut store, ctx, proc_raise), + "random_get" => Function::new_native(&mut store, ctx, random_get::), + "sched_yield" => Function::new_native(&mut store, ctx, sched_yield), + "sock_recv" => Function::new_native(&mut store, ctx, sock_recv::), + "sock_send" => Function::new_native(&mut store, ctx, sock_send::), + "sock_shutdown" => Function::new_native(&mut store, ctx, sock_shutdown), }; namespace } -pub fn import_object_for_all_wasi_versions(ctx: &mut ContextMut<'_, WasiEnv>) -> Imports { - let wasi_unstable_exports = wasi_unstable_exports(ctx); - let wasi_snapshot_preview1_exports = wasi_snapshot_preview1_exports(ctx); +pub fn import_object_for_all_wasi_versions( + store: &mut impl AsStoreMut, + ctx: &FunctionEnv, +) -> Imports { + let wasi_unstable_exports = wasi_unstable_exports(store, ctx); + let wasi_snapshot_preview1_exports = wasi_snapshot_preview1_exports(store, ctx); imports! { "wasi_unstable" => wasi_unstable_exports, "wasi_snapshot_preview1" => wasi_snapshot_preview1_exports, @@ -480,247 +508,259 @@ pub fn import_object_for_all_wasi_versions(ctx: &mut ContextMut<'_, WasiEnv>) -> } /// Combines a state generating function with the import list for legacy WASI -fn generate_import_object_snapshot0(ctx: &mut ContextMut<'_, WasiEnv>) -> Imports { - let wasi_unstable_exports = wasi_unstable_exports(ctx); +fn generate_import_object_snapshot0( + store: &mut impl AsStoreMut, + ctx: &FunctionEnv, +) -> Imports { + let wasi_unstable_exports = wasi_unstable_exports(store, ctx); imports! { "wasi_unstable" => wasi_unstable_exports } } -fn generate_import_object_snapshot1(ctx: &mut ContextMut<'_, WasiEnv>) -> Imports { - let wasi_snapshot_preview1_exports = wasi_snapshot_preview1_exports(ctx); +fn generate_import_object_snapshot1( + store: &mut impl AsStoreMut, + ctx: &FunctionEnv, +) -> Imports { + let wasi_snapshot_preview1_exports = wasi_snapshot_preview1_exports(store, ctx); imports! { "wasi_snapshot_preview1" => wasi_snapshot_preview1_exports } } /// Combines a state generating function with the import list for snapshot 1 -fn generate_import_object_wasix32_v1(ctx: &mut ContextMut<'_, WasiEnv>) -> Imports { +fn generate_import_object_wasix32_v1( + mut store: &mut impl AsStoreMut, + ctx: &FunctionEnv, +) -> Imports { use self::wasix32::*; imports! { "wasix_32v1" => { - "args_get" => Function::new_native(ctx, args_get), - "args_sizes_get" => Function::new_native(ctx, args_sizes_get), - "clock_res_get" => Function::new_native(ctx, clock_res_get), - "clock_time_get" => Function::new_native(ctx, clock_time_get), - "environ_get" => Function::new_native(ctx, environ_get), - "environ_sizes_get" => Function::new_native(ctx, environ_sizes_get), - "fd_advise" => Function::new_native(ctx, fd_advise), - "fd_allocate" => Function::new_native(ctx, fd_allocate), - "fd_close" => Function::new_native(ctx, fd_close), - "fd_datasync" => Function::new_native(ctx, fd_datasync), - "fd_fdstat_get" => Function::new_native(ctx, fd_fdstat_get), - "fd_fdstat_set_flags" => Function::new_native(ctx, fd_fdstat_set_flags), - "fd_fdstat_set_rights" => Function::new_native(ctx, fd_fdstat_set_rights), - "fd_filestat_get" => Function::new_native(ctx, fd_filestat_get), - "fd_filestat_set_size" => Function::new_native(ctx, fd_filestat_set_size), - "fd_filestat_set_times" => Function::new_native(ctx, fd_filestat_set_times), - "fd_pread" => Function::new_native(ctx, fd_pread), - "fd_prestat_get" => Function::new_native(ctx, fd_prestat_get), - "fd_prestat_dir_name" => Function::new_native(ctx, fd_prestat_dir_name), - "fd_pwrite" => Function::new_native(ctx, fd_pwrite), - "fd_read" => Function::new_native(ctx, fd_read), - "fd_readdir" => Function::new_native(ctx, fd_readdir), - "fd_renumber" => Function::new_native(ctx, fd_renumber), - "fd_dup" => Function::new_native(ctx, fd_dup), - "fd_event" => Function::new_native(ctx, fd_event), - "fd_seek" => Function::new_native(ctx, fd_seek), - "fd_sync" => Function::new_native(ctx, fd_sync), - "fd_tell" => Function::new_native(ctx, fd_tell), - "fd_write" => Function::new_native(ctx, fd_write), - "fd_pipe" => Function::new_native(ctx, fd_pipe), - "path_create_directory" => Function::new_native(ctx, path_create_directory), - "path_filestat_get" => Function::new_native(ctx, path_filestat_get), - "path_filestat_set_times" => Function::new_native(ctx, path_filestat_set_times), - "path_link" => Function::new_native(ctx, path_link), - "path_open" => Function::new_native(ctx, path_open), - "path_readlink" => Function::new_native(ctx, path_readlink), - "path_remove_directory" => Function::new_native(ctx, path_remove_directory), - "path_rename" => Function::new_native(ctx, path_rename), - "path_symlink" => Function::new_native(ctx, path_symlink), - "path_unlink_file" => Function::new_native(ctx, path_unlink_file), - "poll_oneoff" => Function::new_native(ctx, poll_oneoff), - "proc_exit" => Function::new_native(ctx, proc_exit), - "proc_raise" => Function::new_native(ctx, proc_raise), - "random_get" => Function::new_native(ctx, random_get), - "tty_get" => Function::new_native(ctx, tty_get), - "tty_set" => Function::new_native(ctx, tty_set), - "getcwd" => Function::new_native(ctx, getcwd), - "chdir" => Function::new_native(ctx, chdir), - "thread_spawn" => Function::new_native(ctx, thread_spawn), - "thread_sleep" => Function::new_native(ctx, thread_sleep), - "thread_id" => Function::new_native(ctx, thread_id), - "thread_join" => Function::new_native(ctx, thread_join), - "thread_parallelism" => Function::new_native(ctx, thread_parallelism), - "thread_exit" => Function::new_native(ctx, thread_exit), - "sched_yield" => Function::new_native(ctx, sched_yield), - "getpid" => Function::new_native(ctx, getpid), - "process_spawn" => Function::new_native(ctx, process_spawn), - "bus_open_local" => Function::new_native(ctx, bus_open_local), - "bus_open_remote" => Function::new_native(ctx, bus_open_remote), - "bus_close" => Function::new_native(ctx, bus_close), - "bus_call" => Function::new_native(ctx, bus_call), - "bus_subcall" => Function::new_native(ctx, bus_subcall), - "bus_poll" => Function::new_native(ctx, bus_poll), - "call_reply" => Function::new_native(ctx, call_reply), - "call_fault" => Function::new_native(ctx, call_fault), - "call_close" => Function::new_native(ctx, call_close), - "ws_connect" => Function::new_native(ctx, ws_connect), - "http_request" => Function::new_native(ctx, http_request), - "http_status" => Function::new_native(ctx, http_status), - "port_bridge" => Function::new_native(ctx, port_bridge), - "port_unbridge" => Function::new_native(ctx, port_unbridge), - "port_dhcp_acquire" => Function::new_native(ctx, port_dhcp_acquire), - "port_addr_add" => Function::new_native(ctx, port_addr_add), - "port_addr_remove" => Function::new_native(ctx, port_addr_remove), - "port_addr_clear" => Function::new_native(ctx, port_addr_clear), - "port_addr_list" => Function::new_native(ctx, port_addr_list), - "port_mac" => Function::new_native(ctx, port_mac), - "port_gateway_set" => Function::new_native(ctx, port_gateway_set), - "port_route_add" => Function::new_native(ctx, port_route_add), - "port_route_remove" => Function::new_native(ctx, port_route_remove), - "port_route_clear" => Function::new_native(ctx, port_route_clear), - "port_route_list" => Function::new_native(ctx, port_route_list), - "sock_status" => Function::new_native(ctx, sock_status), - "sock_addr_local" => Function::new_native(ctx, sock_addr_local), - "sock_addr_peer" => Function::new_native(ctx, sock_addr_peer), - "sock_open" => Function::new_native(ctx, sock_open), - "sock_set_opt_flag" => Function::new_native(ctx, sock_set_opt_flag), - "sock_get_opt_flag" => Function::new_native(ctx, sock_get_opt_flag), - "sock_set_opt_time" => Function::new_native(ctx, sock_set_opt_time), - "sock_get_opt_time" => Function::new_native(ctx, sock_get_opt_time), - "sock_set_opt_size" => Function::new_native(ctx, sock_set_opt_size), - "sock_get_opt_size" => Function::new_native(ctx, sock_get_opt_size), - "sock_join_multicast_v4" => Function::new_native(ctx, sock_join_multicast_v4), - "sock_leave_multicast_v4" => Function::new_native(ctx, sock_leave_multicast_v4), - "sock_join_multicast_v6" => Function::new_native(ctx, sock_join_multicast_v6), - "sock_leave_multicast_v6" => Function::new_native(ctx, sock_leave_multicast_v6), - "sock_bind" => Function::new_native(ctx, sock_bind), - "sock_listen" => Function::new_native(ctx, sock_listen), - "sock_accept" => Function::new_native(ctx, sock_accept), - "sock_connect" => Function::new_native(ctx, sock_connect), - "sock_recv" => Function::new_native(ctx, sock_recv), - "sock_recv_from" => Function::new_native(ctx, sock_recv_from), - "sock_send" => Function::new_native(ctx, sock_send), - "sock_send_to" => Function::new_native(ctx, sock_send_to), - "sock_send_file" => Function::new_native(ctx, sock_send_file), - "sock_shutdown" => Function::new_native(ctx, sock_shutdown), - "resolve" => Function::new_native(ctx, resolve), + "args_get" => Function::new_native(&mut store, ctx, args_get), + "args_sizes_get" => Function::new_native(&mut store, ctx, args_sizes_get), + "clock_res_get" => Function::new_native(&mut store, ctx, clock_res_get), + "clock_time_get" => Function::new_native(&mut store, ctx, clock_time_get), + "environ_get" => Function::new_native(&mut store, ctx, environ_get), + "environ_sizes_get" => Function::new_native(&mut store, ctx, environ_sizes_get), + "fd_advise" => Function::new_native(&mut store, ctx, fd_advise), + "fd_allocate" => Function::new_native(&mut store, ctx, fd_allocate), + "fd_close" => Function::new_native(&mut store, ctx, fd_close), + "fd_datasync" => Function::new_native(&mut store, ctx, fd_datasync), + "fd_fdstat_get" => Function::new_native(&mut store, ctx, fd_fdstat_get), + "fd_fdstat_set_flags" => Function::new_native(&mut store, ctx, fd_fdstat_set_flags), + "fd_fdstat_set_rights" => Function::new_native(&mut store, ctx, fd_fdstat_set_rights), + "fd_filestat_get" => Function::new_native(&mut store, ctx, fd_filestat_get), + "fd_filestat_set_size" => Function::new_native(&mut store, ctx, fd_filestat_set_size), + "fd_filestat_set_times" => Function::new_native(&mut store, ctx, fd_filestat_set_times), + "fd_pread" => Function::new_native(&mut store, ctx, fd_pread), + "fd_prestat_get" => Function::new_native(&mut store, ctx, fd_prestat_get), + "fd_prestat_dir_name" => Function::new_native(&mut store, ctx, fd_prestat_dir_name), + "fd_pwrite" => Function::new_native(&mut store, ctx, fd_pwrite), + "fd_read" => Function::new_native(&mut store, ctx, fd_read), + "fd_readdir" => Function::new_native(&mut store, ctx, fd_readdir), + "fd_renumber" => Function::new_native(&mut store, ctx, fd_renumber), + "fd_dup" => Function::new_native(&mut store, ctx, fd_dup), + "fd_event" => Function::new_native(&mut store, ctx, fd_event), + "fd_seek" => Function::new_native(&mut store, ctx, fd_seek), + "fd_sync" => Function::new_native(&mut store, ctx, fd_sync), + "fd_tell" => Function::new_native(&mut store, ctx, fd_tell), + "fd_write" => Function::new_native(&mut store, ctx, fd_write), + "fd_pipe" => Function::new_native(&mut store, ctx, fd_pipe), + "path_create_directory" => Function::new_native(&mut store, ctx, path_create_directory), + "path_filestat_get" => Function::new_native(&mut store, ctx, path_filestat_get), + "path_filestat_set_times" => Function::new_native(&mut store, ctx, path_filestat_set_times), + "path_link" => Function::new_native(&mut store, ctx, path_link), + "path_open" => Function::new_native(&mut store, ctx, path_open), + "path_readlink" => Function::new_native(&mut store, ctx, path_readlink), + "path_remove_directory" => Function::new_native(&mut store, ctx, path_remove_directory), + "path_rename" => Function::new_native(&mut store, ctx, path_rename), + "path_symlink" => Function::new_native(&mut store, ctx, path_symlink), + "path_unlink_file" => Function::new_native(&mut store, ctx, path_unlink_file), + "poll_oneoff" => Function::new_native(&mut store, ctx, poll_oneoff), + "proc_exit" => Function::new_native(&mut store, ctx, proc_exit), + "proc_raise" => Function::new_native(&mut store, ctx, proc_raise), + "random_get" => Function::new_native(&mut store, ctx, random_get), + "tty_get" => Function::new_native(&mut store, ctx, tty_get), + "tty_set" => Function::new_native(&mut store, ctx, tty_set), + "getcwd" => Function::new_native(&mut store, ctx, getcwd), + "chdir" => Function::new_native(&mut store, ctx, chdir), + "thread_spawn" => Function::new_native(&mut store, ctx, thread_spawn), + "thread_sleep" => Function::new_native(&mut store, ctx, thread_sleep), + "thread_id" => Function::new_native(&mut store, ctx, thread_id), + "thread_join" => Function::new_native(&mut store, ctx, thread_join), + "thread_parallelism" => Function::new_native(&mut store, ctx, thread_parallelism), + "thread_exit" => Function::new_native(&mut store, ctx, thread_exit), + "sched_yield" => Function::new_native(&mut store, ctx, sched_yield), + "getpid" => Function::new_native(&mut store, ctx, getpid), + "process_spawn" => Function::new_native(&mut store, ctx, process_spawn), + "bus_open_local" => Function::new_native(&mut store, ctx, bus_open_local), + "bus_open_remote" => Function::new_native(&mut store, ctx, bus_open_remote), + "bus_close" => Function::new_native(&mut store, ctx, bus_close), + "bus_call" => Function::new_native(&mut store, ctx, bus_call), + "bus_subcall" => Function::new_native(&mut store, ctx, bus_subcall), + "bus_poll" => Function::new_native(&mut store, ctx, bus_poll), + "call_reply" => Function::new_native(&mut store, ctx, call_reply), + "call_fault" => Function::new_native(&mut store, ctx, call_fault), + "call_close" => Function::new_native(&mut store, ctx, call_close), + "ws_connect" => Function::new_native(&mut store, ctx, ws_connect), + "http_request" => Function::new_native(&mut store, ctx, http_request), + "http_status" => Function::new_native(&mut store, ctx, http_status), + "port_bridge" => Function::new_native(&mut store, ctx, port_bridge), + "port_unbridge" => Function::new_native(&mut store, ctx, port_unbridge), + "port_dhcp_acquire" => Function::new_native(&mut store, ctx, port_dhcp_acquire), + "port_addr_add" => Function::new_native(&mut store, ctx, port_addr_add), + "port_addr_remove" => Function::new_native(&mut store, ctx, port_addr_remove), + "port_addr_clear" => Function::new_native(&mut store, ctx, port_addr_clear), + "port_addr_list" => Function::new_native(&mut store, ctx, port_addr_list), + "port_mac" => Function::new_native(&mut store, ctx, port_mac), + "port_gateway_set" => Function::new_native(&mut store, ctx, port_gateway_set), + "port_route_add" => Function::new_native(&mut store, ctx, port_route_add), + "port_route_remove" => Function::new_native(&mut store, ctx, port_route_remove), + "port_route_clear" => Function::new_native(&mut store, ctx, port_route_clear), + "port_route_list" => Function::new_native(&mut store, ctx, port_route_list), + "sock_status" => Function::new_native(&mut store, ctx, sock_status), + "sock_addr_local" => Function::new_native(&mut store, ctx, sock_addr_local), + "sock_addr_peer" => Function::new_native(&mut store, ctx, sock_addr_peer), + "sock_open" => Function::new_native(&mut store, ctx, sock_open), + "sock_set_opt_flag" => Function::new_native(&mut store, ctx, sock_set_opt_flag), + "sock_get_opt_flag" => Function::new_native(&mut store, ctx, sock_get_opt_flag), + "sock_set_opt_time" => Function::new_native(&mut store, ctx, sock_set_opt_time), + "sock_get_opt_time" => Function::new_native(&mut store, ctx, sock_get_opt_time), + "sock_set_opt_size" => Function::new_native(&mut store, ctx, sock_set_opt_size), + "sock_get_opt_size" => Function::new_native(&mut store, ctx, sock_get_opt_size), + "sock_join_multicast_v4" => Function::new_native(&mut store, ctx, sock_join_multicast_v4), + "sock_leave_multicast_v4" => Function::new_native(&mut store, ctx, sock_leave_multicast_v4), + "sock_join_multicast_v6" => Function::new_native(&mut store, ctx, sock_join_multicast_v6), + "sock_leave_multicast_v6" => Function::new_native(&mut store, ctx, sock_leave_multicast_v6), + "sock_bind" => Function::new_native(&mut store, ctx, sock_bind), + "sock_listen" => Function::new_native(&mut store, ctx, sock_listen), + "sock_accept" => Function::new_native(&mut store, ctx, sock_accept), + "sock_connect" => Function::new_native(&mut store, ctx, sock_connect), + "sock_recv" => Function::new_native(&mut store, ctx, sock_recv), + "sock_recv_from" => Function::new_native(&mut store, ctx, sock_recv_from), + "sock_send" => Function::new_native(&mut store, ctx, sock_send), + "sock_send_to" => Function::new_native(&mut store, ctx, sock_send_to), + "sock_send_file" => Function::new_native(&mut store, ctx, sock_send_file), + "sock_shutdown" => Function::new_native(&mut store, ctx, sock_shutdown), + "resolve" => Function::new_native(&mut store, ctx, resolve), } } } -fn generate_import_object_wasix64_v1(ctx: &mut ContextMut<'_, WasiEnv>) -> Imports { +fn generate_import_object_wasix64_v1( + mut store: &mut impl AsStoreMut, + ctx: &FunctionEnv, +) -> Imports { use self::wasix64::*; imports! { "wasix_64v1" => { - "args_get" => Function::new_native(ctx, args_get), - "args_sizes_get" => Function::new_native(ctx, args_sizes_get), - "clock_res_get" => Function::new_native(ctx, clock_res_get), - "clock_time_get" => Function::new_native(ctx, clock_time_get), - "environ_get" => Function::new_native(ctx, environ_get), - "environ_sizes_get" => Function::new_native(ctx, environ_sizes_get), - "fd_advise" => Function::new_native(ctx, fd_advise), - "fd_allocate" => Function::new_native(ctx, fd_allocate), - "fd_close" => Function::new_native(ctx, fd_close), - "fd_datasync" => Function::new_native(ctx, fd_datasync), - "fd_fdstat_get" => Function::new_native(ctx, fd_fdstat_get), - "fd_fdstat_set_flags" => Function::new_native(ctx, fd_fdstat_set_flags), - "fd_fdstat_set_rights" => Function::new_native(ctx, fd_fdstat_set_rights), - "fd_filestat_get" => Function::new_native(ctx, fd_filestat_get), - "fd_filestat_set_size" => Function::new_native(ctx, fd_filestat_set_size), - "fd_filestat_set_times" => Function::new_native(ctx, fd_filestat_set_times), - "fd_pread" => Function::new_native(ctx, fd_pread), - "fd_prestat_get" => Function::new_native(ctx, fd_prestat_get), - "fd_prestat_dir_name" => Function::new_native(ctx, fd_prestat_dir_name), - "fd_pwrite" => Function::new_native(ctx, fd_pwrite), - "fd_read" => Function::new_native(ctx, fd_read), - "fd_readdir" => Function::new_native(ctx, fd_readdir), - "fd_renumber" => Function::new_native(ctx, fd_renumber), - "fd_dup" => Function::new_native(ctx, fd_dup), - "fd_event" => Function::new_native(ctx, fd_event), - "fd_seek" => Function::new_native(ctx, fd_seek), - "fd_sync" => Function::new_native(ctx, fd_sync), - "fd_tell" => Function::new_native(ctx, fd_tell), - "fd_write" => Function::new_native(ctx, fd_write), - "fd_pipe" => Function::new_native(ctx, fd_pipe), - "path_create_directory" => Function::new_native(ctx, path_create_directory), - "path_filestat_get" => Function::new_native(ctx, path_filestat_get), - "path_filestat_set_times" => Function::new_native(ctx, path_filestat_set_times), - "path_link" => Function::new_native(ctx, path_link), - "path_open" => Function::new_native(ctx, path_open), - "path_readlink" => Function::new_native(ctx, path_readlink), - "path_remove_directory" => Function::new_native(ctx, path_remove_directory), - "path_rename" => Function::new_native(ctx, path_rename), - "path_symlink" => Function::new_native(ctx, path_symlink), - "path_unlink_file" => Function::new_native(ctx, path_unlink_file), - "poll_oneoff" => Function::new_native(ctx, poll_oneoff), - "proc_exit" => Function::new_native(ctx, proc_exit), - "proc_raise" => Function::new_native(ctx, proc_raise), - "random_get" => Function::new_native(ctx, random_get), - "tty_get" => Function::new_native(ctx, tty_get), - "tty_set" => Function::new_native(ctx, tty_set), - "getcwd" => Function::new_native(ctx, getcwd), - "chdir" => Function::new_native(ctx, chdir), - "thread_spawn" => Function::new_native(ctx, thread_spawn), - "thread_sleep" => Function::new_native(ctx, thread_sleep), - "thread_id" => Function::new_native(ctx, thread_id), - "thread_join" => Function::new_native(ctx, thread_join), - "thread_parallelism" => Function::new_native(ctx, thread_parallelism), - "thread_exit" => Function::new_native(ctx, thread_exit), - "sched_yield" => Function::new_native(ctx, sched_yield), - "getpid" => Function::new_native(ctx, getpid), - "process_spawn" => Function::new_native(ctx, process_spawn), - "bus_open_local" => Function::new_native(ctx, bus_open_local), - "bus_open_remote" => Function::new_native(ctx, bus_open_remote), - "bus_close" => Function::new_native(ctx, bus_close), - "bus_call" => Function::new_native(ctx, bus_call), - "bus_subcall" => Function::new_native(ctx, bus_subcall), - "bus_poll" => Function::new_native(ctx, bus_poll), - "call_reply" => Function::new_native(ctx, call_reply), - "call_fault" => Function::new_native(ctx, call_fault), - "call_close" => Function::new_native(ctx, call_close), - "ws_connect" => Function::new_native(ctx, ws_connect), - "http_request" => Function::new_native(ctx, http_request), - "http_status" => Function::new_native(ctx, http_status), - "port_bridge" => Function::new_native(ctx, port_bridge), - "port_unbridge" => Function::new_native(ctx, port_unbridge), - "port_dhcp_acquire" => Function::new_native(ctx, port_dhcp_acquire), - "port_addr_add" => Function::new_native(ctx, port_addr_add), - "port_addr_remove" => Function::new_native(ctx, port_addr_remove), - "port_addr_clear" => Function::new_native(ctx, port_addr_clear), - "port_addr_list" => Function::new_native(ctx, port_addr_list), - "port_mac" => Function::new_native(ctx, port_mac), - "port_gateway_set" => Function::new_native(ctx, port_gateway_set), - "port_route_add" => Function::new_native(ctx, port_route_add), - "port_route_remove" => Function::new_native(ctx, port_route_remove), - "port_route_clear" => Function::new_native(ctx, port_route_clear), - "port_route_list" => Function::new_native(ctx, port_route_list), - "sock_status" => Function::new_native(ctx, sock_status), - "sock_addr_local" => Function::new_native(ctx, sock_addr_local), - "sock_addr_peer" => Function::new_native(ctx, sock_addr_peer), - "sock_open" => Function::new_native(ctx, sock_open), - "sock_set_opt_flag" => Function::new_native(ctx, sock_set_opt_flag), - "sock_get_opt_flag" => Function::new_native(ctx, sock_get_opt_flag), - "sock_set_opt_time" => Function::new_native(ctx, sock_set_opt_time), - "sock_get_opt_time" => Function::new_native(ctx, sock_get_opt_time), - "sock_set_opt_size" => Function::new_native(ctx, sock_set_opt_size), - "sock_get_opt_size" => Function::new_native(ctx, sock_get_opt_size), - "sock_join_multicast_v4" => Function::new_native(ctx, sock_join_multicast_v4), - "sock_leave_multicast_v4" => Function::new_native(ctx, sock_leave_multicast_v4), - "sock_join_multicast_v6" => Function::new_native(ctx, sock_join_multicast_v6), - "sock_leave_multicast_v6" => Function::new_native(ctx, sock_leave_multicast_v6), - "sock_bind" => Function::new_native(ctx, sock_bind), - "sock_listen" => Function::new_native(ctx, sock_listen), - "sock_accept" => Function::new_native(ctx, sock_accept), - "sock_connect" => Function::new_native(ctx, sock_connect), - "sock_recv" => Function::new_native(ctx, sock_recv), - "sock_recv_from" => Function::new_native(ctx, sock_recv_from), - "sock_send" => Function::new_native(ctx, sock_send), - "sock_send_to" => Function::new_native(ctx, sock_send_to), - "sock_send_file" => Function::new_native(ctx, sock_send_file), - "sock_shutdown" => Function::new_native(ctx, sock_shutdown), - "resolve" => Function::new_native(ctx, resolve), + "args_get" => Function::new_native(&mut store, ctx, args_get), + "args_sizes_get" => Function::new_native(&mut store, ctx, args_sizes_get), + "clock_res_get" => Function::new_native(&mut store, ctx, clock_res_get), + "clock_time_get" => Function::new_native(&mut store, ctx, clock_time_get), + "environ_get" => Function::new_native(&mut store, ctx, environ_get), + "environ_sizes_get" => Function::new_native(&mut store, ctx, environ_sizes_get), + "fd_advise" => Function::new_native(&mut store, ctx, fd_advise), + "fd_allocate" => Function::new_native(&mut store, ctx, fd_allocate), + "fd_close" => Function::new_native(&mut store, ctx, fd_close), + "fd_datasync" => Function::new_native(&mut store, ctx, fd_datasync), + "fd_fdstat_get" => Function::new_native(&mut store, ctx, fd_fdstat_get), + "fd_fdstat_set_flags" => Function::new_native(&mut store, ctx, fd_fdstat_set_flags), + "fd_fdstat_set_rights" => Function::new_native(&mut store, ctx, fd_fdstat_set_rights), + "fd_filestat_get" => Function::new_native(&mut store, ctx, fd_filestat_get), + "fd_filestat_set_size" => Function::new_native(&mut store, ctx, fd_filestat_set_size), + "fd_filestat_set_times" => Function::new_native(&mut store, ctx, fd_filestat_set_times), + "fd_pread" => Function::new_native(&mut store, ctx, fd_pread), + "fd_prestat_get" => Function::new_native(&mut store, ctx, fd_prestat_get), + "fd_prestat_dir_name" => Function::new_native(&mut store, ctx, fd_prestat_dir_name), + "fd_pwrite" => Function::new_native(&mut store, ctx, fd_pwrite), + "fd_read" => Function::new_native(&mut store, ctx, fd_read), + "fd_readdir" => Function::new_native(&mut store, ctx, fd_readdir), + "fd_renumber" => Function::new_native(&mut store, ctx, fd_renumber), + "fd_dup" => Function::new_native(&mut store, ctx, fd_dup), + "fd_event" => Function::new_native(&mut store, ctx, fd_event), + "fd_seek" => Function::new_native(&mut store, ctx, fd_seek), + "fd_sync" => Function::new_native(&mut store, ctx, fd_sync), + "fd_tell" => Function::new_native(&mut store, ctx, fd_tell), + "fd_write" => Function::new_native(&mut store, ctx, fd_write), + "fd_pipe" => Function::new_native(&mut store, ctx, fd_pipe), + "path_create_directory" => Function::new_native(&mut store, ctx, path_create_directory), + "path_filestat_get" => Function::new_native(&mut store, ctx, path_filestat_get), + "path_filestat_set_times" => Function::new_native(&mut store, ctx, path_filestat_set_times), + "path_link" => Function::new_native(&mut store, ctx, path_link), + "path_open" => Function::new_native(&mut store, ctx, path_open), + "path_readlink" => Function::new_native(&mut store, ctx, path_readlink), + "path_remove_directory" => Function::new_native(&mut store, ctx, path_remove_directory), + "path_rename" => Function::new_native(&mut store, ctx, path_rename), + "path_symlink" => Function::new_native(&mut store, ctx, path_symlink), + "path_unlink_file" => Function::new_native(&mut store, ctx, path_unlink_file), + "poll_oneoff" => Function::new_native(&mut store, ctx, poll_oneoff), + "proc_exit" => Function::new_native(&mut store, ctx, proc_exit), + "proc_raise" => Function::new_native(&mut store, ctx, proc_raise), + "random_get" => Function::new_native(&mut store, ctx, random_get), + "tty_get" => Function::new_native(&mut store, ctx, tty_get), + "tty_set" => Function::new_native(&mut store, ctx, tty_set), + "getcwd" => Function::new_native(&mut store, ctx, getcwd), + "chdir" => Function::new_native(&mut store, ctx, chdir), + "thread_spawn" => Function::new_native(&mut store, ctx, thread_spawn), + "thread_sleep" => Function::new_native(&mut store, ctx, thread_sleep), + "thread_id" => Function::new_native(&mut store, ctx, thread_id), + "thread_join" => Function::new_native(&mut store, ctx, thread_join), + "thread_parallelism" => Function::new_native(&mut store, ctx, thread_parallelism), + "thread_exit" => Function::new_native(&mut store, ctx, thread_exit), + "sched_yield" => Function::new_native(&mut store, ctx, sched_yield), + "getpid" => Function::new_native(&mut store, ctx, getpid), + "process_spawn" => Function::new_native(&mut store, ctx, process_spawn), + "bus_open_local" => Function::new_native(&mut store, ctx, bus_open_local), + "bus_open_remote" => Function::new_native(&mut store, ctx, bus_open_remote), + "bus_close" => Function::new_native(&mut store, ctx, bus_close), + "bus_call" => Function::new_native(&mut store, ctx, bus_call), + "bus_subcall" => Function::new_native(&mut store, ctx, bus_subcall), + "bus_poll" => Function::new_native(&mut store, ctx, bus_poll), + "call_reply" => Function::new_native(&mut store, ctx, call_reply), + "call_fault" => Function::new_native(&mut store, ctx, call_fault), + "call_close" => Function::new_native(&mut store, ctx, call_close), + "ws_connect" => Function::new_native(&mut store, ctx, ws_connect), + "http_request" => Function::new_native(&mut store, ctx, http_request), + "http_status" => Function::new_native(&mut store, ctx, http_status), + "port_bridge" => Function::new_native(&mut store, ctx, port_bridge), + "port_unbridge" => Function::new_native(&mut store, ctx, port_unbridge), + "port_dhcp_acquire" => Function::new_native(&mut store, ctx, port_dhcp_acquire), + "port_addr_add" => Function::new_native(&mut store, ctx, port_addr_add), + "port_addr_remove" => Function::new_native(&mut store, ctx, port_addr_remove), + "port_addr_clear" => Function::new_native(&mut store, ctx, port_addr_clear), + "port_addr_list" => Function::new_native(&mut store, ctx, port_addr_list), + "port_mac" => Function::new_native(&mut store, ctx, port_mac), + "port_gateway_set" => Function::new_native(&mut store, ctx, port_gateway_set), + "port_route_add" => Function::new_native(&mut store, ctx, port_route_add), + "port_route_remove" => Function::new_native(&mut store, ctx, port_route_remove), + "port_route_clear" => Function::new_native(&mut store, ctx, port_route_clear), + "port_route_list" => Function::new_native(&mut store, ctx, port_route_list), + "sock_status" => Function::new_native(&mut store, ctx, sock_status), + "sock_addr_local" => Function::new_native(&mut store, ctx, sock_addr_local), + "sock_addr_peer" => Function::new_native(&mut store, ctx, sock_addr_peer), + "sock_open" => Function::new_native(&mut store, ctx, sock_open), + "sock_set_opt_flag" => Function::new_native(&mut store, ctx, sock_set_opt_flag), + "sock_get_opt_flag" => Function::new_native(&mut store, ctx, sock_get_opt_flag), + "sock_set_opt_time" => Function::new_native(&mut store, ctx, sock_set_opt_time), + "sock_get_opt_time" => Function::new_native(&mut store, ctx, sock_get_opt_time), + "sock_set_opt_size" => Function::new_native(&mut store, ctx, sock_set_opt_size), + "sock_get_opt_size" => Function::new_native(&mut store, ctx, sock_get_opt_size), + "sock_join_multicast_v4" => Function::new_native(&mut store, ctx, sock_join_multicast_v4), + "sock_leave_multicast_v4" => Function::new_native(&mut store, ctx, sock_leave_multicast_v4), + "sock_join_multicast_v6" => Function::new_native(&mut store, ctx, sock_join_multicast_v6), + "sock_leave_multicast_v6" => Function::new_native(&mut store, ctx, sock_leave_multicast_v6), + "sock_bind" => Function::new_native(&mut store, ctx, sock_bind), + "sock_listen" => Function::new_native(&mut store, ctx, sock_listen), + "sock_accept" => Function::new_native(&mut store, ctx, sock_accept), + "sock_connect" => Function::new_native(&mut store, ctx, sock_connect), + "sock_recv" => Function::new_native(&mut store, ctx, sock_recv), + "sock_recv_from" => Function::new_native(&mut store, ctx, sock_recv_from), + "sock_send" => Function::new_native(&mut store, ctx, sock_send), + "sock_send_to" => Function::new_native(&mut store, ctx, sock_send_to), + "sock_send_file" => Function::new_native(&mut store, ctx, sock_send_file), + "sock_shutdown" => Function::new_native(&mut store, ctx, sock_shutdown), + "resolve" => Function::new_native(&mut store, ctx, resolve), } } } diff --git a/lib/wasi/src/state/builder.rs b/lib/wasi/src/state/builder.rs index 541b0a4a923..3cacd30a24e 100644 --- a/lib/wasi/src/state/builder.rs +++ b/lib/wasi/src/state/builder.rs @@ -2,7 +2,7 @@ use crate::state::{default_fs_backing, WasiFs, WasiState}; use crate::syscalls::types::{__WASI_STDERR_FILENO, __WASI_STDIN_FILENO, __WASI_STDOUT_FILENO}; -use crate::{WasiEnv, WasiInodes}; +use crate::{WasiEnv, WasiFunctionEnv, WasiInodes}; use generational_arena::Arena; use std::collections::HashMap; use std::ops::{Deref, DerefMut}; @@ -10,6 +10,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::RwLock; use thiserror::Error; +use wasmer::AsStoreMut; use wasmer_vfs::{FsError, VirtualFile}; /// Creates an empty [`WasiStateBuilder`]. @@ -493,14 +494,17 @@ impl WasiStateBuilder { /// determinisic result. This method is calling [Self::build], /// which is changing the builder's internal state. See /// [Self::build]'s documentation to learn more. - pub fn finalize(&mut self) -> Result { + pub fn finalize( + &mut self, + store: &mut impl AsStoreMut, + ) -> Result { let state = self.build()?; let mut env = WasiEnv::new(state); if let Some(runtime) = self.runtime_override.as_ref() { env.runtime = runtime.clone(); } - Ok(env) + Ok(WasiFunctionEnv::new(store, env)) } } diff --git a/lib/wasi/src/state/pipe.rs b/lib/wasi/src/state/pipe.rs index 29ccb9373ba..2f419214537 100644 --- a/lib/wasi/src/state/pipe.rs +++ b/lib/wasi/src/state/pipe.rs @@ -8,7 +8,7 @@ use std::ops::DerefMut; use std::sync::mpsc; use std::sync::Mutex; use wasmer::MemorySize; -use wasmer::{ContextMut, Memory, WasmSlice}; +use wasmer::{FunctionEnvMut, Memory, WasmSlice}; #[derive(Debug)] pub struct WasiPipe { @@ -42,7 +42,7 @@ impl WasiPipe { pub fn recv( &mut self, - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, memory: &Memory, iov: WasmSlice<__wasi_iovec_t>, ) -> Result { @@ -64,7 +64,7 @@ impl WasiPipe { pub fn send( &mut self, - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, memory: &Memory, iov: WasmSlice<__wasi_ciovec_t>, ) -> Result { diff --git a/lib/wasi/src/state/socket.rs b/lib/wasi/src/state/socket.rs index d2ab0e7ae6a..ff4e92eca45 100644 --- a/lib/wasi/src/state/socket.rs +++ b/lib/wasi/src/state/socket.rs @@ -11,7 +11,7 @@ use std::sync::Mutex; use std::time::Duration; #[allow(unused_imports)] use tracing::{debug, error, info, warn}; -use wasmer::{ContextMut, Memory, MemorySize, WasmPtr, WasmSlice}; +use wasmer::{FunctionEnvMut, Memory, MemorySize, WasmPtr, WasmSlice}; use wasmer_vnet::{net_error_into_io_err, TimeType}; use wasmer_vnet::{ IpCidr, IpRoute, SocketHttpRequest, VirtualIcmpSocket, VirtualNetworking, VirtualRawSocket, @@ -769,7 +769,7 @@ impl InodeSocket { pub fn send( &mut self, - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, iov: WasmSlice<__wasi_ciovec_t>, ) -> Result { @@ -854,7 +854,7 @@ impl InodeSocket { pub fn send_to( &mut self, - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, iov: WasmSlice<__wasi_ciovec_t>, addr: WasmPtr<__wasi_addr_port_t, M>, @@ -885,7 +885,7 @@ impl InodeSocket { pub fn recv( &mut self, - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, iov: WasmSlice<__wasi_iovec_t>, ) -> Result { @@ -955,7 +955,7 @@ impl InodeSocket { pub fn recv_from( &mut self, - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, iov: WasmSlice<__wasi_iovec_t>, addr: WasmPtr<__wasi_addr_port_t, M>, @@ -1135,7 +1135,7 @@ impl Drop for InodeSocket { #[allow(dead_code)] pub(crate) fn read_ip( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_addr_t, M>, ) -> Result { @@ -1154,7 +1154,7 @@ pub(crate) fn read_ip( } pub(crate) fn read_ip_v4( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_addr_ip4_t, M>, ) -> Result { @@ -1166,7 +1166,7 @@ pub(crate) fn read_ip_v4( } pub(crate) fn read_ip_v6( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_addr_ip6_t, M>, ) -> Result { @@ -1178,7 +1178,7 @@ pub(crate) fn read_ip_v6( } pub(crate) fn write_ip( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_addr_t, M>, ip: IpAddr, @@ -1209,7 +1209,7 @@ pub(crate) fn write_ip( #[allow(dead_code)] pub(crate) fn read_cidr( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_cidr_t, M>, ) -> Result { @@ -1241,7 +1241,7 @@ pub(crate) fn read_cidr( #[allow(dead_code)] pub(crate) fn write_cidr( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_cidr_t, M>, cidr: IpCidr, @@ -1279,7 +1279,7 @@ pub(crate) fn write_cidr( } pub(crate) fn read_ip_port( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_addr_port_t, M>, ) -> Result<(IpAddr, u16), __wasi_errno_t> { @@ -1311,7 +1311,7 @@ pub(crate) fn read_ip_port( #[allow(dead_code)] pub(crate) fn write_ip_port( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_addr_port_t, M>, ip: IpAddr, @@ -1351,7 +1351,7 @@ pub(crate) fn write_ip_port( #[allow(dead_code)] pub(crate) fn read_route( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_route_t, M>, ) -> Result { @@ -1407,7 +1407,7 @@ pub(crate) fn read_route( } pub(crate) fn write_route( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut, memory: &Memory, ptr: WasmPtr<__wasi_route_t, M>, route: IpRoute, diff --git a/lib/wasi/src/syscalls/legacy/snapshot0.rs b/lib/wasi/src/syscalls/legacy/snapshot0.rs index 96a1eed7090..33c2f1f6427 100644 --- a/lib/wasi/src/syscalls/legacy/snapshot0.rs +++ b/lib/wasi/src/syscalls/legacy/snapshot0.rs @@ -1,7 +1,7 @@ use crate::syscalls; use crate::syscalls::types::{self, snapshot0}; use crate::{mem_error_to_wasi, Memory32, MemorySize, WasiEnv, WasiError, WasiThread}; -use wasmer::{AsContextMut, ContextMut, WasmPtr}; +use wasmer::{AsStoreMut, FunctionEnvMut, WasmPtr}; /// Wrapper around `syscalls::fd_filestat_get` with extra logic to handle the size /// difference of `wasi_filestat_t` @@ -10,7 +10,7 @@ use wasmer::{AsContextMut, ContextMut, WasmPtr}; /// Wasm memory. If the memory clobbered by the current syscall is also used by /// that syscall, then it may break. pub fn fd_filestat_get( - mut ctx: ContextMut<'_, WasiEnv>, + mut ctx: FunctionEnvMut, fd: types::__wasi_fd_t, buf: WasmPtr, ) -> types::__wasi_errno_t { @@ -27,7 +27,7 @@ pub fn fd_filestat_get( // Set up complete, make the call with the pointer that will write to the // struct and some unrelated memory after the struct. - let result = syscalls::fd_filestat_get::(ctx.as_context_mut(), fd, new_buf); + let result = syscalls::fd_filestat_get::(ctx.as_mut(), fd, new_buf); // reborrow memory let env = ctx.data(); @@ -61,7 +61,7 @@ pub fn fd_filestat_get( /// Wrapper around `syscalls::path_filestat_get` with extra logic to handle the size /// difference of `wasi_filestat_t` pub fn path_filestat_get( - mut ctx: ContextMut<'_, WasiEnv>, + mut ctx: FunctionEnvMut, fd: types::__wasi_fd_t, flags: types::__wasi_lookupflags_t, path: WasmPtr, @@ -75,14 +75,8 @@ pub fn path_filestat_get( let new_buf: WasmPtr = buf.cast(); let new_filestat_setup: types::__wasi_filestat_t = wasi_try_mem!(new_buf.read(&ctx, memory)); - let result = syscalls::path_filestat_get::( - ctx.as_context_mut(), - fd, - flags, - path, - path_len, - new_buf, - ); + let result = + syscalls::path_filestat_get::(ctx.as_mut(), fd, flags, path, path_len, new_buf); // need to re-borrow let env = ctx.data(); @@ -108,7 +102,7 @@ pub fn path_filestat_get( /// Wrapper around `syscalls::fd_seek` with extra logic to remap the values /// of `__wasi_whence_t` pub fn fd_seek( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: types::__wasi_fd_t, offset: types::__wasi_filedelta_t, whence: snapshot0::__wasi_whence_t, @@ -127,7 +121,7 @@ pub fn fd_seek( /// Wrapper around `syscalls::poll_oneoff` with extra logic to add the removed /// userdata field back pub fn poll_oneoff( - mut ctx: ContextMut<'_, WasiEnv>, + mut ctx: FunctionEnvMut, in_: WasmPtr, out_: WasmPtr, nsubscriptions: u32, @@ -173,7 +167,7 @@ pub fn poll_oneoff( // make the call let result = syscalls::poll_oneoff::( - ctx.as_context_mut(), + ctx.as_mut(), in_new_type_ptr, out_, nsubscriptions, diff --git a/lib/wasi/src/syscalls/mod.rs b/lib/wasi/src/syscalls/mod.rs index 1c2e04f3b11..32e1a09492a 100644 --- a/lib/wasi/src/syscalls/mod.rs +++ b/lib/wasi/src/syscalls/mod.rs @@ -47,8 +47,8 @@ use std::sync::{mpsc, Arc}; use std::time::Duration; use tracing::{debug, error, trace, warn}; use wasmer::{ - AsContextMut, ContextMut, Memory, Memory32, Memory64, MemorySize, RuntimeError, Value, WasmPtr, - WasmSlice, + AsStoreMut, FunctionEnvMut, Memory, Memory32, Memory64, MemorySize, RuntimeError, Value, + WasmPtr, WasmSlice, }; use wasmer_vbus::{FileDescriptor, StdioMode}; use wasmer_vfs::{FsError, VirtualFile}; @@ -79,7 +79,7 @@ fn from_offset(offset: M::Offset) -> Result( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, mut write_loc: T, memory: &Memory, iovs_arr_cell: WasmSlice<__wasi_ciovec_t>, @@ -99,7 +99,7 @@ fn write_bytes_inner( } pub(crate) fn write_bytes( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, mut write_loc: T, memory: &Memory, iovs_arr: WasmSlice<__wasi_ciovec_t>, @@ -110,7 +110,7 @@ pub(crate) fn write_bytes( } pub(crate) fn read_bytes( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, mut reader: T, memory: &Memory, iovs_arr: WasmSlice<__wasi_iovec_t>, @@ -141,7 +141,7 @@ fn has_rights(rights_set: __wasi_rights_t, rights_check_set: __wasi_rights_t) -> } fn __sock_actor( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, rights: __wasi_rights_t, actor: F, @@ -174,7 +174,7 @@ where } fn __sock_actor_mut( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, rights: __wasi_rights_t, actor: F, @@ -207,7 +207,7 @@ where } fn __sock_upgrade( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, rights: __wasi_rights_t, actor: F, @@ -247,7 +247,7 @@ where #[must_use] fn write_buffer_array( - ctx: &ContextMut<'_, WasiEnv>, + ctx: &FunctionEnvMut<'_, WasiEnv>, memory: &Memory, from: &[Vec], ptr_buffer: WasmPtr, M>, @@ -297,7 +297,7 @@ fn get_current_time_in_nanos() -> Result<__wasi_timestamp_t, __wasi_errno_t> { /// A pointer to a buffer to write the argument string data. /// pub fn args_get( - mut ctx: ContextMut<'_, WasiEnv>, + mut ctx: FunctionEnvMut<'_, WasiEnv>, argv: WasmPtr, M>, argv_buf: WasmPtr, ) -> __wasi_errno_t { @@ -329,7 +329,7 @@ pub fn args_get( /// - `size_t *argv_buf_size` /// The size of the argument string data. pub fn args_sizes_get( - mut ctx: ContextMut<'_, WasiEnv>, + mut ctx: FunctionEnvMut<'_, WasiEnv>, argc: WasmPtr, argv_buf_size: WasmPtr, ) -> __wasi_errno_t { @@ -361,7 +361,7 @@ pub fn args_sizes_get( /// - `__wasi_timestamp_t *resolution` /// The resolution of the clock in nanoseconds pub fn clock_res_get( - mut ctx: ContextMut<'_, WasiEnv>, + mut ctx: FunctionEnvMut<'_, WasiEnv>, clock_id: __wasi_clockid_t, resolution: WasmPtr<__wasi_timestamp_t, M>, ) -> __wasi_errno_t { @@ -386,7 +386,7 @@ pub fn clock_res_get( /// - `__wasi_timestamp_t *time` /// The value of the clock in nanoseconds pub fn clock_time_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, clock_id: __wasi_clockid_t, precision: __wasi_timestamp_t, time: WasmPtr<__wasi_timestamp_t, M>, @@ -419,7 +419,7 @@ pub fn clock_time_get( /// - `char *environ_buf` /// A pointer to a buffer to write the environment variable string data. pub fn environ_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, environ: WasmPtr, M>, environ_buf: WasmPtr, ) -> __wasi_errno_t { @@ -442,7 +442,7 @@ pub fn environ_get( /// - `size_t *environ_buf_size` /// The size of the environment variable string data. pub fn environ_sizes_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, environ_count: WasmPtr, environ_buf_size: WasmPtr, ) -> __wasi_errno_t { @@ -481,7 +481,7 @@ pub fn environ_sizes_get( /// - `__wasi_advice_t advice` /// The advice to give pub fn fd_advise( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, @@ -504,7 +504,7 @@ pub fn fd_advise( /// - `__wasi_filesize_t len` /// The length from the offset marking the end of the allocation pub fn fd_allocate( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, @@ -555,7 +555,7 @@ pub fn fd_allocate( /// If `fd` is a directory /// - `__WASI_EBADF` /// If `fd` is invalid or not open -pub fn fd_close(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub fn fd_close(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { debug!("wasi::fd_close: fd={}", fd); let env = ctx.data(); let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(0); @@ -572,7 +572,7 @@ pub fn fd_close(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t /// Inputs: /// - `__wasi_fd_t fd` /// The file descriptor to sync -pub fn fd_datasync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub fn fd_datasync(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { debug!("wasi::fd_datasync"); let env = ctx.data(); let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(0); @@ -597,7 +597,7 @@ pub fn fd_datasync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errn /// - `__wasi_fdstat_t *buf` /// The location where the metadata will be written pub fn fd_fdstat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, buf_ptr: WasmPtr<__wasi_fdstat_t, M>, ) -> __wasi_errno_t { @@ -625,7 +625,7 @@ pub fn fd_fdstat_get( /// - `__wasi_fdflags_t flags` /// The flags to apply to `fd` pub fn fd_fdstat_set_flags( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, flags: __wasi_fdflags_t, ) -> __wasi_errno_t { @@ -653,7 +653,7 @@ pub fn fd_fdstat_set_flags( /// - `__wasi_rights_t fs_rights_inheriting` /// The inheriting rights to apply to `fd` pub fn fd_fdstat_set_rights( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, fs_rights_base: __wasi_rights_t, fs_rights_inheriting: __wasi_rights_t, @@ -686,7 +686,7 @@ pub fn fd_fdstat_set_rights( /// - `__wasi_filestat_t *buf` /// Where the metadata from `fd` will be written pub fn fd_filestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, buf: WasmPtr<__wasi_filestat_t, M>, ) -> __wasi_errno_t { @@ -714,7 +714,7 @@ pub fn fd_filestat_get( /// - `__wasi_filesize_t st_size` /// New size that `fd` will be set to pub fn fd_filestat_set_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, st_size: __wasi_filesize_t, ) -> __wasi_errno_t { @@ -763,7 +763,7 @@ pub fn fd_filestat_set_size( /// - `__wasi_fstflags_t fst_flags` /// Bit-vector for controlling which times get set pub fn fd_filestat_set_times( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, st_atim: __wasi_timestamp_t, st_mtim: __wasi_timestamp_t, @@ -825,7 +825,7 @@ pub fn fd_filestat_set_times( /// - `size_t nread` /// The number of bytes read pub fn fd_pread( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, M>, iovs_len: M::Offset, @@ -916,7 +916,7 @@ pub fn fd_pread( /// - `__wasi_prestat *buf` /// Where the metadata will be written pub fn fd_prestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, buf: WasmPtr<__wasi_prestat_t, M>, ) -> __wasi_errno_t { @@ -931,7 +931,7 @@ pub fn fd_prestat_get( } pub fn fd_prestat_dir_name( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, path: WasmPtr, path_len: M::Offset, @@ -993,7 +993,7 @@ pub fn fd_prestat_dir_name( /// - `u32 *nwritten` /// Number of bytes written pub fn fd_pwrite( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, M>, iovs_len: M::Offset, @@ -1104,7 +1104,7 @@ pub fn fd_pwrite( /// Number of bytes read /// pub fn fd_read( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, M>, iovs_len: M::Offset, @@ -1263,7 +1263,7 @@ pub fn fd_read( /// The Number of bytes stored in `buf`; if less than `buf_len` then entire /// directory has been read pub fn fd_readdir( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, buf: WasmPtr, buf_len: M::Offset, @@ -1392,7 +1392,7 @@ pub fn fd_readdir( /// - `__wasi_fd_t to` /// Location to copy file descriptor to pub fn fd_renumber( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, from: __wasi_fd_t, to: __wasi_fd_t, ) -> __wasi_errno_t { @@ -1423,7 +1423,7 @@ pub fn fd_renumber( /// - `__wasi_fd_t fd` /// The new file handle that is a duplicate of the original pub fn fd_dup( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, ret_fd: WasmPtr<__wasi_fd_t, M>, ) -> __wasi_errno_t { @@ -1441,7 +1441,7 @@ pub fn fd_dup( /// ### `fd_event()` /// Creates a file handle for event notifications pub fn fd_event( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, initial_val: u64, flags: __wasi_eventfdflags, ret_fd: WasmPtr<__wasi_fd_t, M>, @@ -1484,7 +1484,7 @@ pub fn fd_event( /// - `__wasi_filesize_t *fd` /// The new offset relative to the start of the file pub fn fd_seek( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, offset: __wasi_filedelta_t, whence: __wasi_whence_t, @@ -1567,7 +1567,7 @@ pub fn fd_seek( /// TODO: figure out which errors this should return /// - `__WASI_EPERM` /// - `__WASI_ENOTCAPABLE` -pub fn fd_sync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub fn fd_sync(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { debug!("wasi::fd_sync"); debug!("=> fd={}", fd); let env = ctx.data(); @@ -1610,7 +1610,7 @@ pub fn fd_sync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t /// - `__wasi_filesize_t *offset` /// The offset of `fd` relative to the start of the file pub fn fd_tell( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, offset: WasmPtr<__wasi_filesize_t, M>, ) -> __wasi_errno_t { @@ -1645,7 +1645,7 @@ pub fn fd_tell( /// Errors: /// pub fn fd_write( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, M>, iovs_len: M::Offset, @@ -1781,7 +1781,7 @@ pub fn fd_write( /// - `__wasi_fd_t` /// Second file handle that represents the other end of the pipe pub fn fd_pipe( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ro_fd1: WasmPtr<__wasi_fd_t, M>, ro_fd2: WasmPtr<__wasi_fd_t, M>, ) -> __wasi_errno_t { @@ -1829,7 +1829,7 @@ pub fn fd_pipe( /// - __WASI_RIGHT_PATH_CREATE_DIRECTORY /// This right must be set on the directory that the file is created in (TODO: verify that this is true) pub fn path_create_directory( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, path: WasmPtr, path_len: M::Offset, @@ -1957,7 +1957,7 @@ pub fn path_create_directory( /// - `__wasi_file_stat_t *buf` /// The location where the metadata will be stored pub fn path_filestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr, @@ -2045,7 +2045,7 @@ pub fn path_filestat_get_internal( /// - `__wasi_fstflags_t fst_flags` /// A bitmask controlling which attributes are set pub fn path_filestat_set_times( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr, @@ -2123,7 +2123,7 @@ pub fn path_filestat_set_times( /// - `u32 old_path_len` /// Length of the `new_path` string pub fn path_link( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, old_fd: __wasi_fd_t, old_flags: __wasi_lookupflags_t, old_path: WasmPtr, @@ -2219,7 +2219,7 @@ pub fn path_link( /// Possible Errors: /// - `__WASI_EACCES`, `__WASI_EBADF`, `__WASI_EFAULT`, `__WASI_EFBIG?`, `__WASI_EINVAL`, `__WASI_EIO`, `__WASI_ELOOP`, `__WASI_EMFILE`, `__WASI_ENAMETOOLONG?`, `__WASI_ENFILE`, `__WASI_ENOENT`, `__WASI_ENOTDIR`, `__WASI_EROFS`, and `__WASI_ENOTCAPABLE` pub fn path_open( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, dirfd: __wasi_fd_t, dirflags: __wasi_lookupflags_t, path: WasmPtr, @@ -2462,7 +2462,7 @@ pub fn path_open( /// - `u32 buf_used` /// The number of bytes written to `buf` pub fn path_readlink( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, dir_fd: __wasi_fd_t, path: WasmPtr, path_len: M::Offset, @@ -2513,7 +2513,7 @@ pub fn path_readlink( /// Returns __WASI_ENOTEMTPY if directory is not empty pub fn path_remove_directory( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, path: WasmPtr, path_len: M::Offset, @@ -2598,7 +2598,7 @@ pub fn path_remove_directory( /// - `u32 new_path_len` /// The number of bytes to read from `new_path` pub fn path_rename( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, old_fd: __wasi_fd_t, old_path: WasmPtr, old_path_len: M::Offset, @@ -2762,7 +2762,7 @@ pub fn path_rename( /// - `u32 new_path_len` /// The number of bytes to read from `new_path` pub fn path_symlink( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, old_path: WasmPtr, old_path_len: M::Offset, fd: __wasi_fd_t, @@ -2862,7 +2862,7 @@ pub fn path_symlink( /// - `u32 path_len` /// The number of bytes in the `path` array pub fn path_unlink_file( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t, path: WasmPtr, path_len: M::Offset, @@ -2973,7 +2973,7 @@ pub fn path_unlink_file( /// - `u32 nevents` /// The number of events seen pub fn poll_oneoff( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, in_: WasmPtr<__wasi_subscription_t, M>, out_: WasmPtr<__wasi_event_t, M>, nsubscriptions: M::Offset, @@ -3223,7 +3223,10 @@ pub fn poll_oneoff( /// Inputs: /// - `__wasi_exitcode_t` /// Exit code to return to the operating system -pub fn proc_exit(ctx: ContextMut<'_, WasiEnv>, code: __wasi_exitcode_t) -> Result<(), WasiError> { +pub fn proc_exit( + ctx: FunctionEnvMut<'_, WasiEnv>, + code: __wasi_exitcode_t, +) -> Result<(), WasiError> { debug!("wasi::proc_exit, {}", code); Err(WasiError::Exit(code)) } @@ -3234,14 +3237,14 @@ pub fn proc_exit(ctx: ContextMut<'_, WasiEnv>, code: __wasi_exitcode_t) -> Resul /// Inputs: /// - `__wasi_signal_t` /// Signal to be raised for this process -pub fn proc_raise(ctx: ContextMut<'_, WasiEnv>, sig: __wasi_signal_t) -> __wasi_errno_t { +pub fn proc_raise(ctx: FunctionEnvMut<'_, WasiEnv>, sig: __wasi_signal_t) -> __wasi_errno_t { debug!("wasi::proc_raise"); unimplemented!("wasi::proc_raise") } /// ### `sched_yield()` /// Yields execution of the thread -pub fn sched_yield(ctx: ContextMut<'_, WasiEnv>) -> Result<__wasi_errno_t, WasiError> { +pub fn sched_yield(ctx: FunctionEnvMut<'_, WasiEnv>) -> Result<__wasi_errno_t, WasiError> { trace!("wasi::sched_yield"); let env = ctx.data(); env.yield_now()?; @@ -3256,7 +3259,7 @@ pub fn sched_yield(ctx: ContextMut<'_, WasiEnv>) -> Result<__wasi_errno_t, WasiE /// - `size_t buf_len` /// The number of bytes that will be written pub fn random_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, buf: WasmPtr, buf_len: M::Offset, ) -> __wasi_errno_t { @@ -3279,7 +3282,7 @@ pub fn random_get( /// ### `tty_get()` /// Retrieves the current state of the TTY pub fn tty_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, tty_state: WasmPtr<__wasi_tty_t, M>, ) -> __wasi_errno_t { debug!("wasi::tty_stdin"); @@ -3322,7 +3325,7 @@ pub fn tty_get( /// ### `tty_set()` /// Updates the properties of the rect pub fn tty_set( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, tty_state: WasmPtr<__wasi_tty_t, M>, ) -> __wasi_errno_t { debug!("wasi::tty_set"); @@ -3372,7 +3375,7 @@ pub fn tty_set( /// If the path exceeds the size of the buffer then this function /// will fill the path_len with the needed size and return EOVERFLOW pub fn getcwd( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, path: WasmPtr, path_len: WasmPtr, ) -> __wasi_errno_t { @@ -3413,7 +3416,7 @@ pub fn getcwd( /// ### `chdir()` /// Sets the current working directory pub fn chdir( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, path: WasmPtr, path_len: M::Offset, ) -> __wasi_errno_t { @@ -3445,7 +3448,7 @@ pub fn chdir( /// Returns the thread index of the newly created thread /// (indices always start from zero) pub fn thread_spawn( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, method: WasmPtr, method_len: M::Offset, user_data: u64, @@ -3532,7 +3535,7 @@ pub fn thread_spawn( /// /// * `duration` - Amount of time that the thread should sleep pub fn thread_sleep( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, duration: __wasi_timestamp_t, ) -> Result<__wasi_errno_t, WasiError> { debug!("wasi::thread_sleep"); @@ -3547,7 +3550,7 @@ pub fn thread_sleep( /// Returns the index of the current thread /// (threads indices are sequencial from zero) pub fn thread_id( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ret_tid: WasmPtr<__wasi_tid_t, M>, ) -> __wasi_errno_t { debug!("wasi::thread_id"); @@ -3566,7 +3569,7 @@ pub fn thread_id( /// /// * `tid` - Handle of the thread to wait on pub fn thread_join( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, tid: __wasi_tid_t, ) -> Result<__wasi_errno_t, WasiError> { debug!("wasi::thread_join"); @@ -3594,7 +3597,7 @@ pub fn thread_join( /// Returns the available parallelism which is normally the /// number of available cores that can run concurrently pub fn thread_parallelism( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ret_parallelism: WasmPtr, ) -> __wasi_errno_t { debug!("wasi::thread_parallelism"); @@ -3612,7 +3615,7 @@ pub fn thread_parallelism( /// ### `getpid()` /// Returns the handle of the current process pub fn getpid( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ret_pid: WasmPtr<__wasi_pid_t, M>, ) -> __wasi_errno_t { debug!("wasi::getpid"); @@ -3637,7 +3640,7 @@ pub fn getpid( /// /// * `rval` - The exit code returned by the process. pub fn thread_exit( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, exitcode: __wasi_exitcode_t, ) -> Result<__wasi_errno_t, WasiError> { debug!("wasi::thread_exit"); @@ -3664,7 +3667,7 @@ pub fn thread_exit( /// /// Returns a bus process id that can be used to invoke calls pub fn process_spawn( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, name: WasmPtr, name_len: M::Offset, chroot: __wasi_bool_t, @@ -3765,7 +3768,7 @@ pub fn process_spawn( /// /// Returns a bus process id that can be used to invoke calls pub fn bus_open_local( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, name: WasmPtr, name_len: M::Offset, reuse: __wasi_bool_t, @@ -3796,7 +3799,7 @@ pub fn bus_open_local( /// /// Returns a bus process id that can be used to invoke calls pub fn bus_open_remote( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, name: WasmPtr, name_len: M::Offset, reuse: __wasi_bool_t, @@ -3822,7 +3825,7 @@ pub fn bus_open_remote( } fn bus_open_local_internal( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, name: String, reuse: bool, instance: Option, @@ -3884,7 +3887,7 @@ fn bus_open_local_internal( /// ## Parameters /// /// * `bid` - Handle of the bus process handle to be closed -pub fn bus_close(ctx: ContextMut<'_, WasiEnv>, bid: __wasi_bid_t) -> __bus_errno_t { +pub fn bus_close(ctx: FunctionEnvMut<'_, WasiEnv>, bid: __wasi_bid_t) -> __bus_errno_t { trace!("wasi::bus_close (bid={})", bid); let bid: WasiBusProcessId = bid.into(); @@ -3907,7 +3910,7 @@ pub fn bus_close(ctx: ContextMut<'_, WasiEnv>, bid: __wasi_bid_t) -> __bus_errno /// * `format` - Format of the data pushed onto the bus /// * `buf` - The buffer where data to be transmitted is stored pub fn bus_call( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, bid: __wasi_bid_t, keep_alive: __wasi_bool_t, topic: WasmPtr, @@ -3944,7 +3947,7 @@ pub fn bus_call( /// * `format` - Format of the data pushed onto the bus /// * `buf` - The buffer where data to be transmitted is stored pub fn bus_subcall( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, parent: __wasi_cid_t, keep_alive: __wasi_bool_t, topic: WasmPtr, @@ -3984,7 +3987,7 @@ pub fn bus_subcall( /// /// Returns the number of events that have occured pub fn bus_poll( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, timeout: __wasi_timestamp_t, events: WasmPtr, nevents: M::Offset, @@ -4012,7 +4015,7 @@ pub fn bus_poll( /// * `format` - Format of the data pushed onto the bus /// * `buf` - The buffer where data to be transmitted is stored pub fn call_reply( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, cid: __wasi_cid_t, format: __wasi_busdataformat_t, buf: WasmPtr, @@ -4039,7 +4042,7 @@ pub fn call_reply( /// * `cid` - Handle of the call to raise a fault on /// * `fault` - Fault to be raised on the bus pub fn call_fault( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, cid: __wasi_cid_t, fault: __bus_errno_t, ) -> __bus_errno_t { @@ -4055,7 +4058,7 @@ pub fn call_fault( /// ## Parameters /// /// * `cid` - Handle of the bus call handle to be dropped -pub fn call_close(ctx: ContextMut<'_, WasiEnv>, cid: __wasi_cid_t) -> __bus_errno_t { +pub fn call_close(ctx: FunctionEnvMut<'_, WasiEnv>, cid: __wasi_cid_t) -> __bus_errno_t { let env = ctx.data(); let bus = env.runtime.bus(); trace!("wasi::call_close (cid={})", cid); @@ -4074,7 +4077,7 @@ pub fn call_close(ctx: ContextMut<'_, WasiEnv>, cid: __wasi_cid_t) -> __bus_errn /// /// Returns a socket handle which is used to send and receive data pub fn ws_connect( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, url: WasmPtr, url_len: M::Offset, ret_sock: WasmPtr<__wasi_fd_t, M>, @@ -4126,7 +4129,7 @@ pub fn ws_connect( /// The body of the response can be streamed from the returned /// file handle pub fn http_request( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, url: WasmPtr, url_len: M::Offset, method: WasmPtr, @@ -4233,7 +4236,7 @@ pub fn http_request( /// * `status` - Pointer to a buffer that will be filled with the current /// status of this HTTP request pub fn http_status( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, status: WasmPtr<__wasi_http_status_t, M>, ) -> __wasi_errno_t { @@ -4272,7 +4275,7 @@ pub fn http_status( /// * `token` - Access token used to authenticate with the network /// * `security` - Level of encryption to encapsulate the network connection with pub fn port_bridge( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, network: WasmPtr, network_len: M::Offset, token: WasmPtr, @@ -4301,7 +4304,7 @@ pub fn port_bridge( /// ### `port_unbridge()` /// Disconnects from a remote network -pub fn port_unbridge(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub fn port_unbridge(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { debug!("wasi::port_unbridge"); let env = ctx.data(); wasi_try!(env.net().unbridge().map_err(net_error_into_wasi_err)); @@ -4310,7 +4313,7 @@ pub fn port_unbridge(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { /// ### `port_dhcp_acquire()` /// Acquires a set of IP addresses using DHCP -pub fn port_dhcp_acquire(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub fn port_dhcp_acquire(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { debug!("wasi::port_dhcp_acquire"); let env = ctx.data(); wasi_try!(env.net().dhcp_acquire().map_err(net_error_into_wasi_err)); @@ -4324,7 +4327,7 @@ pub fn port_dhcp_acquire(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { /// /// * `addr` - Address to be added pub fn port_addr_add( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ip: WasmPtr<__wasi_cidr_t, M>, ) -> __wasi_errno_t { debug!("wasi::port_addr_add"); @@ -4345,7 +4348,7 @@ pub fn port_addr_add( /// /// * `addr` - Address to be removed pub fn port_addr_remove( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ip: WasmPtr<__wasi_addr_t, M>, ) -> __wasi_errno_t { debug!("wasi::port_addr_remove"); @@ -4358,7 +4361,7 @@ pub fn port_addr_remove( /// ### `port_addr_clear()` /// Clears all the addresses on the local port -pub fn port_addr_clear(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub fn port_addr_clear(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { debug!("wasi::port_addr_clear"); let env = ctx.data(); wasi_try!(env.net().ip_clear().map_err(net_error_into_wasi_err)); @@ -4368,7 +4371,7 @@ pub fn port_addr_clear(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { /// ### `port_mac()` /// Returns the MAC address of the local port pub fn port_mac( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ret_mac: WasmPtr<__wasi_hardwareaddress_t, M>, ) -> __wasi_errno_t { debug!("wasi::port_mac"); @@ -4394,7 +4397,7 @@ pub fn port_mac( /// /// The number of addresses returned. pub fn port_addr_list( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, addrs: WasmPtr<__wasi_cidr_t, M>, naddrs: WasmPtr, ) -> __wasi_errno_t { @@ -4429,7 +4432,7 @@ pub fn port_addr_list( /// /// * `addr` - Address of the default gateway pub fn port_gateway_set( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ip: WasmPtr<__wasi_addr_t, M>, ) -> __wasi_errno_t { debug!("wasi::port_gateway_set"); @@ -4444,7 +4447,7 @@ pub fn port_gateway_set( /// ### `port_route_add()` /// Adds a new route to the local port pub fn port_route_add( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, cidr: WasmPtr<__wasi_cidr_t, M>, via_router: WasmPtr<__wasi_addr_t, M>, preferred_until: WasmPtr<__wasi_option_timestamp_t, M>, @@ -4478,7 +4481,7 @@ pub fn port_route_add( /// ### `port_route_remove()` /// Removes an existing route from the local port pub fn port_route_remove( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, ip: WasmPtr<__wasi_addr_t, M>, ) -> __wasi_errno_t { debug!("wasi::port_route_remove"); @@ -4491,7 +4494,7 @@ pub fn port_route_remove( /// ### `port_route_clear()` /// Clears all the routes in the local port -pub fn port_route_clear(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub fn port_route_clear(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { debug!("wasi::port_route_clear"); let env = ctx.data(); wasi_try!(env.net().route_clear().map_err(net_error_into_wasi_err)); @@ -4508,7 +4511,7 @@ pub fn port_route_clear(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { /// /// * `routes` - The buffer where routes will be stored pub fn port_route_list( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, routes: WasmPtr<__wasi_route_t, M>, nroutes: WasmPtr, ) -> __wasi_errno_t { @@ -4551,7 +4554,7 @@ pub fn port_route_list( /// /// * `how` - Which channels on the socket to shut down. pub fn sock_shutdown( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, how: __wasi_sdflags_t, ) -> __wasi_errno_t { @@ -4578,7 +4581,7 @@ pub fn sock_shutdown( /// ### `sock_status()` /// Returns the current status of a socket pub fn sock_status( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, ret_status: WasmPtr<__wasi_sockstatus_t, M>, ) -> __wasi_errno_t { @@ -4612,7 +4615,7 @@ pub fn sock_status( /// /// * `fd` - Socket that the address is bound to pub fn sock_addr_local( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, ret_addr: WasmPtr<__wasi_addr_port_t, M>, ) -> __wasi_errno_t { @@ -4644,7 +4647,7 @@ pub fn sock_addr_local( /// /// * `fd` - Socket that the address is bound to pub fn sock_addr_peer( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, ro_addr: WasmPtr<__wasi_addr_port_t, M>, ) -> __wasi_errno_t { @@ -4682,7 +4685,7 @@ pub fn sock_addr_peer( /// /// The file descriptor of the socket that has been opened. pub fn sock_open( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, af: __wasi_addressfamily_t, ty: __wasi_socktype_t, pt: __wasi_sockproto_t, @@ -4738,7 +4741,7 @@ pub fn sock_open( /// * `sockopt` - Socket option to be set /// * `flag` - Value to set the option to pub fn sock_set_opt_flag( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, opt: __wasi_sockoption_t, flag: __wasi_bool_t, @@ -4767,7 +4770,7 @@ pub fn sock_set_opt_flag( /// * `fd` - Socket descriptor /// * `sockopt` - Socket option to be retrieved pub fn sock_get_opt_flag( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_flag: WasmPtr<__wasi_bool_t, M>, @@ -4799,7 +4802,7 @@ pub fn sock_get_opt_flag( /// * `sockopt` - Socket option to be set /// * `time` - Value to set the time to pub fn sock_set_opt_time( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, opt: __wasi_sockoption_t, time: WasmPtr<__wasi_option_timestamp_t, M>, @@ -4839,7 +4842,7 @@ pub fn sock_set_opt_time( /// * `fd` - Socket descriptor /// * `sockopt` - Socket option to be retrieved pub fn sock_get_opt_time( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_time: WasmPtr<__wasi_option_timestamp_t, M>, @@ -4886,7 +4889,7 @@ pub fn sock_get_opt_time( /// * `opt` - Socket option to be set /// * `size` - Buffer size pub fn sock_set_opt_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, opt: __wasi_sockoption_t, size: __wasi_filesize_t, @@ -4924,7 +4927,7 @@ pub fn sock_set_opt_size( /// * `fd` - Socket descriptor /// * `sockopt` - Socket option to be retrieved pub fn sock_get_opt_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_size: WasmPtr<__wasi_filesize_t, M>, @@ -4962,7 +4965,7 @@ pub fn sock_get_opt_size( /// * `multiaddr` - Multicast group to joined /// * `interface` - Interface that will join pub fn sock_join_multicast_v4( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip4_t, M>, iface: WasmPtr<__wasi_addr_ip4_t, M>, @@ -4988,7 +4991,7 @@ pub fn sock_join_multicast_v4( /// * `multiaddr` - Multicast group to leave /// * `interface` - Interface that will left pub fn sock_leave_multicast_v4( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip4_t, M>, iface: WasmPtr<__wasi_addr_ip4_t, M>, @@ -5014,7 +5017,7 @@ pub fn sock_leave_multicast_v4( /// * `multiaddr` - Multicast group to joined /// * `interface` - Interface that will join pub fn sock_join_multicast_v6( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip6_t, M>, iface: u32, @@ -5039,7 +5042,7 @@ pub fn sock_join_multicast_v6( /// * `multiaddr` - Multicast group to leave /// * `interface` - Interface that will left pub fn sock_leave_multicast_v6( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip6_t, M>, iface: u32, @@ -5064,7 +5067,7 @@ pub fn sock_leave_multicast_v6( /// * `fd` - File descriptor of the socket to be bind /// * `addr` - Address to bind the socket to pub fn sock_bind( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, addr: WasmPtr<__wasi_addr_port_t, M>, ) -> __wasi_errno_t { @@ -5095,7 +5098,7 @@ pub fn sock_bind( /// * `fd` - File descriptor of the socket to be bind /// * `backlog` - Maximum size of the queue for pending connections pub fn sock_listen( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, backlog: M::Offset, ) -> __wasi_errno_t { @@ -5125,7 +5128,7 @@ pub fn sock_listen( /// /// New socket connection pub fn sock_accept( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, fd_flags: __wasi_fdflags_t, ro_fd: WasmPtr<__wasi_fd_t, M>, @@ -5201,7 +5204,7 @@ pub fn sock_accept( /// * `fd` - Socket descriptor /// * `addr` - Address of the socket to connect to pub fn sock_connect( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, addr: WasmPtr<__wasi_addr_port_t, M>, ) -> __wasi_errno_t { @@ -5233,7 +5236,7 @@ pub fn sock_connect( /// /// Number of bytes stored in ri_data and message flags. pub fn sock_recv( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, ri_data: WasmPtr<__wasi_iovec_t, M>, ri_data_len: M::Offset, @@ -5275,7 +5278,7 @@ pub fn sock_recv( /// /// Number of bytes stored in ri_data and message flags. pub fn sock_recv_from( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, ri_data: WasmPtr<__wasi_iovec_t, M>, ri_data_len: M::Offset, @@ -5318,7 +5321,7 @@ pub fn sock_recv_from( /// /// Number of bytes transmitted. pub fn sock_send( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, si_data: WasmPtr<__wasi_ciovec_t, M>, si_data_len: M::Offset, @@ -5360,7 +5363,7 @@ pub fn sock_send( /// /// Number of bytes transmitted. pub fn sock_send_to( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, si_data: WasmPtr<__wasi_ciovec_t, M>, si_data_len: M::Offset, @@ -5401,7 +5404,7 @@ pub fn sock_send_to( /// /// Number of bytes transmitted. pub unsafe fn sock_send_file( - mut ctx: ContextMut<'_, WasiEnv>, + mut ctx: FunctionEnvMut<'_, WasiEnv>, sock: __wasi_fd_t, in_fd: __wasi_fd_t, offset: __wasi_filesize_t, @@ -5534,7 +5537,7 @@ pub unsafe fn sock_send_file( /// /// The number of IP addresses returned during the DNS resolution. pub fn resolve( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut<'_, WasiEnv>, host: WasmPtr, host_len: M::Offset, port: u16, diff --git a/lib/wasi/src/syscalls/wasi.rs b/lib/wasi/src/syscalls/wasi.rs index 14ab2200bbc..b2575f6e53c 100644 --- a/lib/wasi/src/syscalls/wasi.rs +++ b/lib/wasi/src/syscalls/wasi.rs @@ -1,13 +1,13 @@ #![deny(dead_code)] use crate::{WasiEnv, WasiError, WasiState, WasiThread}; -use wasmer::{ContextMut, Memory, Memory32, MemorySize, WasmPtr, WasmSlice}; +use wasmer::{StoreMut, Memory, Memory32, MemorySize, WasmPtr, WasmSlice}; use wasmer_wasi_types::*; type MemoryType = Memory32; type MemoryOffset = u32; pub(crate) fn args_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, argv: WasmPtr, MemoryType>, argv_buf: WasmPtr, ) -> __wasi_errno_t { @@ -15,7 +15,7 @@ pub(crate) fn args_get( } pub(crate) fn args_sizes_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, argc: WasmPtr, argv_buf_size: WasmPtr, ) -> __wasi_errno_t { @@ -23,7 +23,7 @@ pub(crate) fn args_sizes_get( } pub(crate) fn clock_res_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, clock_id: __wasi_clockid_t, resolution: WasmPtr<__wasi_timestamp_t, MemoryType>, ) -> __wasi_errno_t { @@ -31,7 +31,7 @@ pub(crate) fn clock_res_get( } pub(crate) fn clock_time_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, clock_id: __wasi_clockid_t, precision: __wasi_timestamp_t, time: WasmPtr<__wasi_timestamp_t, MemoryType>, @@ -40,7 +40,7 @@ pub(crate) fn clock_time_get( } pub(crate) fn environ_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, environ: WasmPtr, MemoryType>, environ_buf: WasmPtr, ) -> __wasi_errno_t { @@ -48,7 +48,7 @@ pub(crate) fn environ_get( } pub(crate) fn environ_sizes_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, environ_count: WasmPtr, environ_buf_size: WasmPtr, ) -> __wasi_errno_t { @@ -56,7 +56,7 @@ pub(crate) fn environ_sizes_get( } pub(crate) fn fd_advise( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, @@ -66,7 +66,7 @@ pub(crate) fn fd_advise( } pub(crate) fn fd_allocate( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, @@ -74,16 +74,16 @@ pub(crate) fn fd_allocate( super::fd_allocate(ctx, fd, offset, len) } -pub(crate) fn fd_close(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_close(ctx, fd) } -pub(crate) fn fd_datasync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_datasync(ctx, fd) } pub(crate) fn fd_fdstat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf_ptr: WasmPtr<__wasi_fdstat_t, MemoryType>, ) -> __wasi_errno_t { @@ -91,7 +91,7 @@ pub(crate) fn fd_fdstat_get( } pub(crate) fn fd_fdstat_set_flags( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_fdflags_t, ) -> __wasi_errno_t { @@ -99,7 +99,7 @@ pub(crate) fn fd_fdstat_set_flags( } pub(crate) fn fd_fdstat_set_rights( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, fs_rights_base: __wasi_rights_t, fs_rights_inheriting: __wasi_rights_t, @@ -108,7 +108,7 @@ pub(crate) fn fd_fdstat_set_rights( } pub(crate) fn fd_filestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr<__wasi_filestat_t, MemoryType>, ) -> __wasi_errno_t { @@ -116,7 +116,7 @@ pub(crate) fn fd_filestat_get( } pub(crate) fn fd_filestat_set_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, st_size: __wasi_filesize_t, ) -> __wasi_errno_t { @@ -124,7 +124,7 @@ pub(crate) fn fd_filestat_set_size( } pub(crate) fn fd_filestat_set_times( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, st_atim: __wasi_timestamp_t, st_mtim: __wasi_timestamp_t, @@ -134,7 +134,7 @@ pub(crate) fn fd_filestat_set_times( } pub(crate) fn fd_pread( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -145,7 +145,7 @@ pub(crate) fn fd_pread( } pub(crate) fn fd_prestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr<__wasi_prestat_t, MemoryType>, ) -> __wasi_errno_t { @@ -153,7 +153,7 @@ pub(crate) fn fd_prestat_get( } pub(crate) fn fd_prestat_dir_name( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -162,7 +162,7 @@ pub(crate) fn fd_prestat_dir_name( } pub(crate) fn fd_pwrite( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -173,7 +173,7 @@ pub(crate) fn fd_pwrite( } pub(crate) fn fd_read( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -183,7 +183,7 @@ pub(crate) fn fd_read( } pub(crate) fn fd_readdir( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr, buf_len: MemoryOffset, @@ -194,7 +194,7 @@ pub(crate) fn fd_readdir( } pub(crate) fn fd_renumber( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, from: __wasi_fd_t, to: __wasi_fd_t, ) -> __wasi_errno_t { @@ -202,7 +202,7 @@ pub(crate) fn fd_renumber( } pub(crate) fn fd_seek( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filedelta_t, whence: __wasi_whence_t, @@ -211,12 +211,12 @@ pub(crate) fn fd_seek( super::fd_seek::(ctx, fd, offset, whence, newoffset) } -pub(crate) fn fd_sync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_sync(ctx, fd) } pub(crate) fn fd_tell( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: WasmPtr<__wasi_filesize_t, MemoryType>, ) -> __wasi_errno_t { @@ -224,7 +224,7 @@ pub(crate) fn fd_tell( } pub(crate) fn fd_write( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -234,7 +234,7 @@ pub(crate) fn fd_write( } pub(crate) fn path_create_directory( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -243,7 +243,7 @@ pub(crate) fn path_create_directory( } pub(crate) fn path_filestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr, @@ -254,7 +254,7 @@ pub(crate) fn path_filestat_get( } pub(crate) fn path_filestat_set_times( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr, @@ -269,7 +269,7 @@ pub(crate) fn path_filestat_set_times( } pub(crate) fn path_link( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_fd: __wasi_fd_t, old_flags: __wasi_lookupflags_t, old_path: WasmPtr, @@ -291,7 +291,7 @@ pub(crate) fn path_link( } pub(crate) fn path_open( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, dirfd: __wasi_fd_t, dirflags: __wasi_lookupflags_t, path: WasmPtr, @@ -317,7 +317,7 @@ pub(crate) fn path_open( } pub(crate) fn path_readlink( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, dir_fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -329,7 +329,7 @@ pub(crate) fn path_readlink( } pub(crate) fn path_remove_directory( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -338,7 +338,7 @@ pub(crate) fn path_remove_directory( } pub(crate) fn path_rename( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_fd: __wasi_fd_t, old_path: WasmPtr, old_path_len: MemoryOffset, @@ -358,7 +358,7 @@ pub(crate) fn path_rename( } pub(crate) fn path_symlink( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_path: WasmPtr, old_path_len: MemoryOffset, fd: __wasi_fd_t, @@ -369,7 +369,7 @@ pub(crate) fn path_symlink( } pub(crate) fn path_unlink_file( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -378,7 +378,7 @@ pub(crate) fn path_unlink_file( } pub(crate) fn poll_oneoff( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, in_: WasmPtr<__wasi_subscription_t, MemoryType>, out_: WasmPtr<__wasi_event_t, MemoryType>, nsubscriptions: MemoryOffset, @@ -388,30 +388,30 @@ pub(crate) fn poll_oneoff( } pub(crate) fn proc_exit( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, code: __wasi_exitcode_t, ) -> Result<(), WasiError> { super::proc_exit(ctx, code) } -pub(crate) fn proc_raise(ctx: ContextMut<'_, WasiEnv>, sig: __wasi_signal_t) -> __wasi_errno_t { +pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> __wasi_errno_t { super::proc_raise(ctx, sig) } pub(crate) fn random_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, buf: WasmPtr, buf_len: MemoryOffset, ) -> __wasi_errno_t { super::random_get::(ctx, buf, buf_len) } -pub(crate) fn sched_yield(ctx: ContextMut<'_, WasiEnv>) -> Result<__wasi_errno_t, WasiError> { +pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result<__wasi_errno_t, WasiError> { super::sched_yield(ctx) } pub(crate) fn sock_recv( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, @@ -431,7 +431,7 @@ pub(crate) fn sock_recv( } pub(crate) fn sock_send( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, @@ -442,7 +442,7 @@ pub(crate) fn sock_send( } pub(crate) fn sock_shutdown( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, how: __wasi_sdflags_t, ) -> __wasi_errno_t { diff --git a/lib/wasi/src/syscalls/wasix32.rs b/lib/wasi/src/syscalls/wasix32.rs index 712c1a34eb9..5cb6899c3ef 100644 --- a/lib/wasi/src/syscalls/wasix32.rs +++ b/lib/wasi/src/syscalls/wasix32.rs @@ -1,13 +1,13 @@ #![deny(dead_code)] use crate::{WasiEnv, WasiError, WasiState, WasiThread}; -use wasmer::{ContextMut, Memory, Memory32, MemorySize, WasmPtr, WasmSlice}; +use wasmer::{FunctionEnvMut, Memory, Memory32, MemorySize, StoreMut, WasmPtr, WasmSlice}; use wasmer_wasi_types::*; type MemoryType = Memory32; type MemoryOffset = u32; pub(crate) fn args_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, argv: WasmPtr, MemoryType>, argv_buf: WasmPtr, ) -> __wasi_errno_t { @@ -15,7 +15,7 @@ pub(crate) fn args_get( } pub(crate) fn args_sizes_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, argc: WasmPtr, argv_buf_size: WasmPtr, ) -> __wasi_errno_t { @@ -23,7 +23,7 @@ pub(crate) fn args_sizes_get( } pub(crate) fn clock_res_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, clock_id: __wasi_clockid_t, resolution: WasmPtr<__wasi_timestamp_t, MemoryType>, ) -> __wasi_errno_t { @@ -31,7 +31,7 @@ pub(crate) fn clock_res_get( } pub(crate) fn clock_time_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, clock_id: __wasi_clockid_t, precision: __wasi_timestamp_t, time: WasmPtr<__wasi_timestamp_t, MemoryType>, @@ -40,7 +40,7 @@ pub(crate) fn clock_time_get( } pub(crate) fn environ_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, environ: WasmPtr, MemoryType>, environ_buf: WasmPtr, ) -> __wasi_errno_t { @@ -48,7 +48,7 @@ pub(crate) fn environ_get( } pub(crate) fn environ_sizes_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, environ_count: WasmPtr, environ_buf_size: WasmPtr, ) -> __wasi_errno_t { @@ -56,7 +56,7 @@ pub(crate) fn environ_sizes_get( } pub(crate) fn fd_advise( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, @@ -66,7 +66,7 @@ pub(crate) fn fd_advise( } pub(crate) fn fd_allocate( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, @@ -74,16 +74,16 @@ pub(crate) fn fd_allocate( super::fd_allocate(ctx, fd, offset, len) } -pub(crate) fn fd_close(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_close(ctx, fd) } -pub(crate) fn fd_datasync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_datasync(ctx, fd) } pub(crate) fn fd_fdstat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf_ptr: WasmPtr<__wasi_fdstat_t, MemoryType>, ) -> __wasi_errno_t { @@ -91,7 +91,7 @@ pub(crate) fn fd_fdstat_get( } pub(crate) fn fd_fdstat_set_flags( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_fdflags_t, ) -> __wasi_errno_t { @@ -99,7 +99,7 @@ pub(crate) fn fd_fdstat_set_flags( } pub(crate) fn fd_fdstat_set_rights( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, fs_rights_base: __wasi_rights_t, fs_rights_inheriting: __wasi_rights_t, @@ -108,7 +108,7 @@ pub(crate) fn fd_fdstat_set_rights( } pub(crate) fn fd_filestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr<__wasi_filestat_t, MemoryType>, ) -> __wasi_errno_t { @@ -116,7 +116,7 @@ pub(crate) fn fd_filestat_get( } pub(crate) fn fd_filestat_set_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, st_size: __wasi_filesize_t, ) -> __wasi_errno_t { @@ -124,7 +124,7 @@ pub(crate) fn fd_filestat_set_size( } pub(crate) fn fd_filestat_set_times( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, st_atim: __wasi_timestamp_t, st_mtim: __wasi_timestamp_t, @@ -134,7 +134,7 @@ pub(crate) fn fd_filestat_set_times( } pub(crate) fn fd_pread( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -145,7 +145,7 @@ pub(crate) fn fd_pread( } pub(crate) fn fd_prestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr<__wasi_prestat_t, MemoryType>, ) -> __wasi_errno_t { @@ -153,7 +153,7 @@ pub(crate) fn fd_prestat_get( } pub(crate) fn fd_prestat_dir_name( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -162,7 +162,7 @@ pub(crate) fn fd_prestat_dir_name( } pub(crate) fn fd_pwrite( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -173,7 +173,7 @@ pub(crate) fn fd_pwrite( } pub(crate) fn fd_read( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -183,7 +183,7 @@ pub(crate) fn fd_read( } pub(crate) fn fd_readdir( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr, buf_len: MemoryOffset, @@ -194,7 +194,7 @@ pub(crate) fn fd_readdir( } pub(crate) fn fd_renumber( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, from: __wasi_fd_t, to: __wasi_fd_t, ) -> __wasi_errno_t { @@ -202,7 +202,7 @@ pub(crate) fn fd_renumber( } pub(crate) fn fd_seek( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filedelta_t, whence: __wasi_whence_t, @@ -211,12 +211,12 @@ pub(crate) fn fd_seek( super::fd_seek::(ctx, fd, offset, whence, newoffset) } -pub(crate) fn fd_sync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_sync(ctx, fd) } pub(crate) fn fd_tell( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: WasmPtr<__wasi_filesize_t, MemoryType>, ) -> __wasi_errno_t { @@ -224,7 +224,7 @@ pub(crate) fn fd_tell( } pub(crate) fn fd_write( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -234,7 +234,7 @@ pub(crate) fn fd_write( } pub(crate) fn path_create_directory( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -243,7 +243,7 @@ pub(crate) fn path_create_directory( } pub(crate) fn path_filestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr, @@ -254,7 +254,7 @@ pub(crate) fn path_filestat_get( } pub(crate) fn path_filestat_set_times( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr, @@ -269,7 +269,7 @@ pub(crate) fn path_filestat_set_times( } pub(crate) fn path_link( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_fd: __wasi_fd_t, old_flags: __wasi_lookupflags_t, old_path: WasmPtr, @@ -291,7 +291,7 @@ pub(crate) fn path_link( } pub(crate) fn path_open( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, dirfd: __wasi_fd_t, dirflags: __wasi_lookupflags_t, path: WasmPtr, @@ -317,7 +317,7 @@ pub(crate) fn path_open( } pub(crate) fn path_readlink( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, dir_fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -329,7 +329,7 @@ pub(crate) fn path_readlink( } pub(crate) fn path_remove_directory( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -338,7 +338,7 @@ pub(crate) fn path_remove_directory( } pub(crate) fn path_rename( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_fd: __wasi_fd_t, old_path: WasmPtr, old_path_len: MemoryOffset, @@ -358,7 +358,7 @@ pub(crate) fn path_rename( } pub(crate) fn path_symlink( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_path: WasmPtr, old_path_len: MemoryOffset, fd: __wasi_fd_t, @@ -369,7 +369,7 @@ pub(crate) fn path_symlink( } pub(crate) fn path_unlink_file( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -378,7 +378,7 @@ pub(crate) fn path_unlink_file( } pub(crate) fn poll_oneoff( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, in_: WasmPtr<__wasi_subscription_t, MemoryType>, out_: WasmPtr<__wasi_event_t, MemoryType>, nsubscriptions: MemoryOffset, @@ -388,18 +388,18 @@ pub(crate) fn poll_oneoff( } pub(crate) fn proc_exit( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, code: __wasi_exitcode_t, ) -> Result<(), WasiError> { super::proc_exit(ctx, code) } -pub(crate) fn proc_raise(ctx: ContextMut<'_, WasiEnv>, sig: __wasi_signal_t) -> __wasi_errno_t { +pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> __wasi_errno_t { super::proc_raise(ctx, sig) } pub(crate) fn random_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, buf: WasmPtr, buf_len: MemoryOffset, ) -> __wasi_errno_t { @@ -407,7 +407,7 @@ pub(crate) fn random_get( } pub(crate) fn fd_dup( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, ret_fd: WasmPtr<__wasi_fd_t, MemoryType>, ) -> __wasi_errno_t { @@ -415,7 +415,7 @@ pub(crate) fn fd_dup( } pub(crate) fn fd_event( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, initial_val: u64, flags: __wasi_eventfdflags, ret_fd: WasmPtr<__wasi_fd_t, MemoryType>, @@ -424,7 +424,7 @@ pub(crate) fn fd_event( } pub(crate) fn fd_pipe( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ro_fd1: WasmPtr<__wasi_fd_t, MemoryType>, ro_fd2: WasmPtr<__wasi_fd_t, MemoryType>, ) -> __wasi_errno_t { @@ -432,21 +432,21 @@ pub(crate) fn fd_pipe( } pub(crate) fn tty_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, tty_state: WasmPtr<__wasi_tty_t, MemoryType>, ) -> __wasi_errno_t { super::tty_get::(ctx, tty_state) } pub(crate) fn tty_set( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, tty_state: WasmPtr<__wasi_tty_t, MemoryType>, ) -> __wasi_errno_t { super::tty_set::(ctx, tty_state) } pub(crate) fn getcwd( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, path: WasmPtr, path_len: WasmPtr, ) -> __wasi_errno_t { @@ -454,7 +454,7 @@ pub(crate) fn getcwd( } pub(crate) fn chdir( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, path: WasmPtr, path_len: MemoryOffset, ) -> __wasi_errno_t { @@ -462,7 +462,7 @@ pub(crate) fn chdir( } pub(crate) fn thread_spawn( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, method: WasmPtr, method_len: MemoryOffset, user_data: u64, @@ -473,53 +473,53 @@ pub(crate) fn thread_spawn( } pub(crate) fn thread_sleep( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, duration: __wasi_timestamp_t, ) -> Result<__wasi_errno_t, WasiError> { super::thread_sleep(ctx, duration) } pub(crate) fn thread_id( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ret_tid: WasmPtr<__wasi_tid_t, MemoryType>, ) -> __wasi_errno_t { super::thread_id::(ctx, ret_tid) } pub(crate) fn thread_join( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, tid: __wasi_tid_t, ) -> Result<__wasi_errno_t, WasiError> { super::thread_join(ctx, tid) } pub(crate) fn thread_parallelism( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ret_parallelism: WasmPtr, ) -> __wasi_errno_t { super::thread_parallelism::(ctx, ret_parallelism) } pub(crate) fn thread_exit( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, exitcode: __wasi_exitcode_t, ) -> Result<__wasi_errno_t, WasiError> { super::thread_exit(ctx, exitcode) } -pub(crate) fn sched_yield(ctx: ContextMut<'_, WasiEnv>) -> Result<__wasi_errno_t, WasiError> { +pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result<__wasi_errno_t, WasiError> { super::sched_yield(ctx) } pub(crate) fn getpid( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ret_pid: WasmPtr<__wasi_pid_t, MemoryType>, ) -> __wasi_errno_t { super::getpid::(ctx, ret_pid) } pub(crate) fn process_spawn( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, name: WasmPtr, name_len: MemoryOffset, chroot: __wasi_bool_t, @@ -553,7 +553,7 @@ pub(crate) fn process_spawn( } pub(crate) fn bus_open_local( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, name: WasmPtr, name_len: MemoryOffset, reuse: __wasi_bool_t, @@ -563,7 +563,7 @@ pub(crate) fn bus_open_local( } pub(crate) fn bus_open_remote( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, name: WasmPtr, name_len: MemoryOffset, reuse: __wasi_bool_t, @@ -586,12 +586,12 @@ pub(crate) fn bus_open_remote( ) } -pub(crate) fn bus_close(ctx: ContextMut<'_, WasiEnv>, bid: __wasi_bid_t) -> __bus_errno_t { +pub(crate) fn bus_close(ctx: FunctionEnvMut, bid: __wasi_bid_t) -> __bus_errno_t { super::bus_close(ctx, bid) } pub(crate) fn bus_call( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, bid: __wasi_bid_t, keep_alive: __wasi_bool_t, topic: WasmPtr, @@ -607,7 +607,7 @@ pub(crate) fn bus_call( } pub(crate) fn bus_subcall( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, parent: __wasi_cid_t, keep_alive: __wasi_bool_t, topic: WasmPtr, @@ -623,7 +623,7 @@ pub(crate) fn bus_subcall( } pub(crate) fn bus_poll( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, timeout: __wasi_timestamp_t, events: WasmPtr, nevents: MemoryOffset, @@ -643,7 +643,7 @@ pub(crate) fn bus_poll( } pub(crate) fn call_reply( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, cid: __wasi_cid_t, format: __wasi_busdataformat_t, buf: WasmPtr, @@ -653,19 +653,19 @@ pub(crate) fn call_reply( } pub(crate) fn call_fault( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, cid: __wasi_cid_t, fault: __bus_errno_t, ) -> __bus_errno_t { super::call_fault(ctx, cid, fault) } -pub(crate) fn call_close(ctx: ContextMut<'_, WasiEnv>, cid: __wasi_cid_t) -> __bus_errno_t { +pub(crate) fn call_close(ctx: FunctionEnvMut, cid: __wasi_cid_t) -> __bus_errno_t { super::call_close(ctx, cid) } pub(crate) fn port_bridge( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, network: WasmPtr, network_len: MemoryOffset, token: WasmPtr, @@ -675,34 +675,34 @@ pub(crate) fn port_bridge( super::port_bridge::(ctx, network, network_len, token, token_len, security) } -pub(crate) fn port_unbridge(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub(crate) fn port_unbridge(ctx: FunctionEnvMut) -> __wasi_errno_t { super::port_unbridge(ctx) } -pub(crate) fn port_dhcp_acquire(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub(crate) fn port_dhcp_acquire(ctx: FunctionEnvMut) -> __wasi_errno_t { super::port_dhcp_acquire(ctx) } pub(crate) fn port_addr_add( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, addr: WasmPtr<__wasi_cidr_t, MemoryType>, ) -> __wasi_errno_t { super::port_addr_add::(ctx, addr) } pub(crate) fn port_addr_remove( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, addr: WasmPtr<__wasi_addr_t, MemoryType>, ) -> __wasi_errno_t { super::port_addr_remove::(ctx, addr) } -pub(crate) fn port_addr_clear(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub(crate) fn port_addr_clear(ctx: FunctionEnvMut) -> __wasi_errno_t { super::port_addr_clear(ctx) } pub(crate) fn port_addr_list( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, addrs: WasmPtr<__wasi_cidr_t, MemoryType>, naddrs: WasmPtr, ) -> __wasi_errno_t { @@ -710,21 +710,21 @@ pub(crate) fn port_addr_list( } pub(crate) fn port_mac( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ret_mac: WasmPtr<__wasi_hardwareaddress_t, MemoryType>, ) -> __wasi_errno_t { super::port_mac::(ctx, ret_mac) } pub(crate) fn port_gateway_set( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ip: WasmPtr<__wasi_addr_t, MemoryType>, ) -> __wasi_errno_t { super::port_gateway_set::(ctx, ip) } pub(crate) fn port_route_add( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, cidr: WasmPtr<__wasi_cidr_t, MemoryType>, via_router: WasmPtr<__wasi_addr_t, MemoryType>, preferred_until: WasmPtr<__wasi_option_timestamp_t, MemoryType>, @@ -734,18 +734,18 @@ pub(crate) fn port_route_add( } pub(crate) fn port_route_remove( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ip: WasmPtr<__wasi_addr_t, MemoryType>, ) -> __wasi_errno_t { super::port_route_remove::(ctx, ip) } -pub(crate) fn port_route_clear(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub(crate) fn port_route_clear(ctx: FunctionEnvMut) -> __wasi_errno_t { super::port_route_clear(ctx) } pub(crate) fn port_route_list( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, routes: WasmPtr<__wasi_route_t, MemoryType>, nroutes: WasmPtr, ) -> __wasi_errno_t { @@ -753,7 +753,7 @@ pub(crate) fn port_route_list( } pub(crate) fn ws_connect( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, url: WasmPtr, url_len: MemoryOffset, ret_sock: WasmPtr<__wasi_fd_t, MemoryType>, @@ -762,7 +762,7 @@ pub(crate) fn ws_connect( } pub(crate) fn http_request( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, url: WasmPtr, url_len: MemoryOffset, method: WasmPtr, @@ -786,7 +786,7 @@ pub(crate) fn http_request( } pub(crate) fn http_status( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, status: WasmPtr<__wasi_http_status_t, MemoryType>, status_text: WasmPtr, @@ -798,7 +798,7 @@ pub(crate) fn http_status( } pub(crate) fn sock_status( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ret_status: WasmPtr<__wasi_sockstatus_t, MemoryType>, ) -> __wasi_errno_t { @@ -806,7 +806,7 @@ pub(crate) fn sock_status( } pub(crate) fn sock_addr_local( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ret_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ) -> __wasi_errno_t { @@ -814,7 +814,7 @@ pub(crate) fn sock_addr_local( } pub(crate) fn sock_addr_peer( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ) -> __wasi_errno_t { @@ -822,7 +822,7 @@ pub(crate) fn sock_addr_peer( } pub(crate) fn sock_open( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, af: __wasi_addressfamily_t, ty: __wasi_socktype_t, pt: __wasi_sockproto_t, @@ -832,7 +832,7 @@ pub(crate) fn sock_open( } pub(crate) fn sock_set_opt_flag( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, flag: __wasi_bool_t, @@ -841,7 +841,7 @@ pub(crate) fn sock_set_opt_flag( } pub(crate) fn sock_get_opt_flag( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_flag: WasmPtr<__wasi_bool_t, MemoryType>, @@ -850,7 +850,7 @@ pub(crate) fn sock_get_opt_flag( } pub fn sock_set_opt_time( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, time: WasmPtr<__wasi_option_timestamp_t, MemoryType>, @@ -859,7 +859,7 @@ pub fn sock_set_opt_time( } pub fn sock_get_opt_time( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_time: WasmPtr<__wasi_option_timestamp_t, MemoryType>, @@ -868,7 +868,7 @@ pub fn sock_get_opt_time( } pub fn sock_set_opt_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, size: __wasi_filesize_t, @@ -877,7 +877,7 @@ pub fn sock_set_opt_size( } pub fn sock_get_opt_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_size: WasmPtr<__wasi_filesize_t, MemoryType>, @@ -886,7 +886,7 @@ pub fn sock_get_opt_size( } pub(crate) fn sock_join_multicast_v4( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip4_t, MemoryType>, iface: WasmPtr<__wasi_addr_ip4_t, MemoryType>, @@ -895,7 +895,7 @@ pub(crate) fn sock_join_multicast_v4( } pub(crate) fn sock_leave_multicast_v4( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip4_t, MemoryType>, iface: WasmPtr<__wasi_addr_ip4_t, MemoryType>, @@ -904,7 +904,7 @@ pub(crate) fn sock_leave_multicast_v4( } pub(crate) fn sock_join_multicast_v6( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip6_t, MemoryType>, iface: u32, @@ -913,7 +913,7 @@ pub(crate) fn sock_join_multicast_v6( } pub(crate) fn sock_leave_multicast_v6( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip6_t, MemoryType>, iface: u32, @@ -922,7 +922,7 @@ pub(crate) fn sock_leave_multicast_v6( } pub(crate) fn sock_bind( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ) -> __wasi_errno_t { @@ -930,7 +930,7 @@ pub(crate) fn sock_bind( } pub(crate) fn sock_listen( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, backlog: MemoryOffset, ) -> __wasi_errno_t { @@ -938,7 +938,7 @@ pub(crate) fn sock_listen( } pub(crate) fn sock_accept( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, fd_flags: __wasi_fdflags_t, ro_fd: WasmPtr<__wasi_fd_t, MemoryType>, @@ -948,7 +948,7 @@ pub(crate) fn sock_accept( } pub(crate) fn sock_connect( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ) -> __wasi_errno_t { @@ -956,7 +956,7 @@ pub(crate) fn sock_connect( } pub(crate) fn sock_recv( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, @@ -976,7 +976,7 @@ pub(crate) fn sock_recv( } pub(crate) fn sock_recv_from( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, @@ -998,7 +998,7 @@ pub(crate) fn sock_recv_from( } pub(crate) fn sock_send( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, @@ -1009,7 +1009,7 @@ pub(crate) fn sock_send( } pub(crate) fn sock_send_to( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, @@ -1029,7 +1029,7 @@ pub(crate) fn sock_send_to( } pub(crate) fn sock_send_file( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, out_fd: __wasi_fd_t, in_fd: __wasi_fd_t, offset: __wasi_filesize_t, @@ -1040,7 +1040,7 @@ pub(crate) fn sock_send_file( } pub(crate) fn sock_shutdown( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, how: __wasi_sdflags_t, ) -> __wasi_errno_t { @@ -1048,7 +1048,7 @@ pub(crate) fn sock_shutdown( } pub(crate) fn resolve( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, host: WasmPtr, host_len: MemoryOffset, port: u16, diff --git a/lib/wasi/src/syscalls/wasix64.rs b/lib/wasi/src/syscalls/wasix64.rs index 4064232ae6f..b42307e0da8 100644 --- a/lib/wasi/src/syscalls/wasix64.rs +++ b/lib/wasi/src/syscalls/wasix64.rs @@ -1,13 +1,13 @@ #![deny(dead_code)] use crate::{WasiEnv, WasiError, WasiState, WasiThread}; -use wasmer::{ContextMut, Memory, Memory64, MemorySize, WasmPtr, WasmSlice}; +use wasmer::{FunctionEnvMut, Memory, Memory64, MemorySize, StoreMut, WasmPtr, WasmSlice}; use wasmer_wasi_types::*; type MemoryType = Memory64; type MemoryOffset = u64; pub(crate) fn args_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, argv: WasmPtr, MemoryType>, argv_buf: WasmPtr, ) -> __wasi_errno_t { @@ -15,7 +15,7 @@ pub(crate) fn args_get( } pub(crate) fn args_sizes_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, argc: WasmPtr, argv_buf_size: WasmPtr, ) -> __wasi_errno_t { @@ -23,7 +23,7 @@ pub(crate) fn args_sizes_get( } pub(crate) fn clock_res_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, clock_id: __wasi_clockid_t, resolution: WasmPtr<__wasi_timestamp_t, MemoryType>, ) -> __wasi_errno_t { @@ -31,7 +31,7 @@ pub(crate) fn clock_res_get( } pub(crate) fn clock_time_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, clock_id: __wasi_clockid_t, precision: __wasi_timestamp_t, time: WasmPtr<__wasi_timestamp_t, MemoryType>, @@ -40,7 +40,7 @@ pub(crate) fn clock_time_get( } pub(crate) fn environ_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, environ: WasmPtr, MemoryType>, environ_buf: WasmPtr, ) -> __wasi_errno_t { @@ -48,7 +48,7 @@ pub(crate) fn environ_get( } pub(crate) fn environ_sizes_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, environ_count: WasmPtr, environ_buf_size: WasmPtr, ) -> __wasi_errno_t { @@ -56,7 +56,7 @@ pub(crate) fn environ_sizes_get( } pub(crate) fn fd_advise( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, @@ -66,7 +66,7 @@ pub(crate) fn fd_advise( } pub(crate) fn fd_allocate( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filesize_t, len: __wasi_filesize_t, @@ -74,16 +74,16 @@ pub(crate) fn fd_allocate( super::fd_allocate(ctx, fd, offset, len) } -pub(crate) fn fd_close(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_close(ctx, fd) } -pub(crate) fn fd_datasync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_datasync(ctx, fd) } pub(crate) fn fd_fdstat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf_ptr: WasmPtr<__wasi_fdstat_t, MemoryType>, ) -> __wasi_errno_t { @@ -91,7 +91,7 @@ pub(crate) fn fd_fdstat_get( } pub(crate) fn fd_fdstat_set_flags( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_fdflags_t, ) -> __wasi_errno_t { @@ -99,7 +99,7 @@ pub(crate) fn fd_fdstat_set_flags( } pub(crate) fn fd_fdstat_set_rights( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, fs_rights_base: __wasi_rights_t, fs_rights_inheriting: __wasi_rights_t, @@ -108,7 +108,7 @@ pub(crate) fn fd_fdstat_set_rights( } pub(crate) fn fd_filestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr<__wasi_filestat_t, MemoryType>, ) -> __wasi_errno_t { @@ -116,7 +116,7 @@ pub(crate) fn fd_filestat_get( } pub(crate) fn fd_filestat_set_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, st_size: __wasi_filesize_t, ) -> __wasi_errno_t { @@ -124,7 +124,7 @@ pub(crate) fn fd_filestat_set_size( } pub(crate) fn fd_filestat_set_times( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, st_atim: __wasi_timestamp_t, st_mtim: __wasi_timestamp_t, @@ -134,7 +134,7 @@ pub(crate) fn fd_filestat_set_times( } pub(crate) fn fd_pread( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -145,7 +145,7 @@ pub(crate) fn fd_pread( } pub(crate) fn fd_prestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr<__wasi_prestat_t, MemoryType>, ) -> __wasi_errno_t { @@ -153,7 +153,7 @@ pub(crate) fn fd_prestat_get( } pub(crate) fn fd_prestat_dir_name( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -162,7 +162,7 @@ pub(crate) fn fd_prestat_dir_name( } pub(crate) fn fd_pwrite( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -173,7 +173,7 @@ pub(crate) fn fd_pwrite( } pub(crate) fn fd_read( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -183,7 +183,7 @@ pub(crate) fn fd_read( } pub(crate) fn fd_readdir( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, buf: WasmPtr, buf_len: MemoryOffset, @@ -194,7 +194,7 @@ pub(crate) fn fd_readdir( } pub(crate) fn fd_renumber( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, from: __wasi_fd_t, to: __wasi_fd_t, ) -> __wasi_errno_t { @@ -202,7 +202,7 @@ pub(crate) fn fd_renumber( } pub(crate) fn fd_seek( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: __wasi_filedelta_t, whence: __wasi_whence_t, @@ -211,12 +211,12 @@ pub(crate) fn fd_seek( super::fd_seek::(ctx, fd, offset, whence, newoffset) } -pub(crate) fn fd_sync(ctx: ContextMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { super::fd_sync(ctx, fd) } pub(crate) fn fd_tell( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, offset: WasmPtr<__wasi_filesize_t, MemoryType>, ) -> __wasi_errno_t { @@ -224,7 +224,7 @@ pub(crate) fn fd_tell( } pub(crate) fn fd_write( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, @@ -234,7 +234,7 @@ pub(crate) fn fd_write( } pub(crate) fn path_create_directory( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -243,7 +243,7 @@ pub(crate) fn path_create_directory( } pub(crate) fn path_filestat_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr, @@ -254,7 +254,7 @@ pub(crate) fn path_filestat_get( } pub(crate) fn path_filestat_set_times( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, flags: __wasi_lookupflags_t, path: WasmPtr, @@ -269,7 +269,7 @@ pub(crate) fn path_filestat_set_times( } pub(crate) fn path_link( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_fd: __wasi_fd_t, old_flags: __wasi_lookupflags_t, old_path: WasmPtr, @@ -291,7 +291,7 @@ pub(crate) fn path_link( } pub(crate) fn path_open( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, dirfd: __wasi_fd_t, dirflags: __wasi_lookupflags_t, path: WasmPtr, @@ -317,7 +317,7 @@ pub(crate) fn path_open( } pub(crate) fn path_readlink( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, dir_fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -329,7 +329,7 @@ pub(crate) fn path_readlink( } pub(crate) fn path_remove_directory( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -338,7 +338,7 @@ pub(crate) fn path_remove_directory( } pub(crate) fn path_rename( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_fd: __wasi_fd_t, old_path: WasmPtr, old_path_len: MemoryOffset, @@ -358,7 +358,7 @@ pub(crate) fn path_rename( } pub(crate) fn path_symlink( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, old_path: WasmPtr, old_path_len: MemoryOffset, fd: __wasi_fd_t, @@ -369,7 +369,7 @@ pub(crate) fn path_symlink( } pub(crate) fn path_unlink_file( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, path: WasmPtr, path_len: MemoryOffset, @@ -378,7 +378,7 @@ pub(crate) fn path_unlink_file( } pub(crate) fn poll_oneoff( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, in_: WasmPtr<__wasi_subscription_t, MemoryType>, out_: WasmPtr<__wasi_event_t, MemoryType>, nsubscriptions: MemoryOffset, @@ -388,18 +388,18 @@ pub(crate) fn poll_oneoff( } pub(crate) fn proc_exit( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, code: __wasi_exitcode_t, ) -> Result<(), WasiError> { super::proc_exit(ctx, code) } -pub(crate) fn proc_raise(ctx: ContextMut<'_, WasiEnv>, sig: __wasi_signal_t) -> __wasi_errno_t { +pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> __wasi_errno_t { super::proc_raise(ctx, sig) } pub(crate) fn random_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, buf: WasmPtr, buf_len: MemoryOffset, ) -> __wasi_errno_t { @@ -407,7 +407,7 @@ pub(crate) fn random_get( } pub(crate) fn fd_dup( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, fd: __wasi_fd_t, ret_fd: WasmPtr<__wasi_fd_t, MemoryType>, ) -> __wasi_errno_t { @@ -415,7 +415,7 @@ pub(crate) fn fd_dup( } pub(crate) fn fd_event( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, initial_val: u64, flags: __wasi_eventfdflags, ret_fd: WasmPtr<__wasi_fd_t, MemoryType>, @@ -424,7 +424,7 @@ pub(crate) fn fd_event( } pub(crate) fn fd_pipe( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ro_fd1: WasmPtr<__wasi_fd_t, MemoryType>, ro_fd2: WasmPtr<__wasi_fd_t, MemoryType>, ) -> __wasi_errno_t { @@ -432,21 +432,21 @@ pub(crate) fn fd_pipe( } pub(crate) fn tty_get( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, tty_state: WasmPtr<__wasi_tty_t, MemoryType>, ) -> __wasi_errno_t { super::tty_get::(ctx, tty_state) } pub(crate) fn tty_set( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, tty_state: WasmPtr<__wasi_tty_t, MemoryType>, ) -> __wasi_errno_t { super::tty_set::(ctx, tty_state) } pub(crate) fn getcwd( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, path: WasmPtr, path_len: WasmPtr, ) -> __wasi_errno_t { @@ -454,7 +454,7 @@ pub(crate) fn getcwd( } pub(crate) fn chdir( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, path: WasmPtr, path_len: MemoryOffset, ) -> __wasi_errno_t { @@ -462,7 +462,7 @@ pub(crate) fn chdir( } pub(crate) fn thread_spawn( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, method: WasmPtr, method_len: MemoryOffset, user_data: u64, @@ -473,53 +473,53 @@ pub(crate) fn thread_spawn( } pub(crate) fn thread_sleep( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, duration: __wasi_timestamp_t, ) -> Result<__wasi_errno_t, WasiError> { super::thread_sleep(ctx, duration) } pub(crate) fn thread_id( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ret_tid: WasmPtr<__wasi_tid_t, MemoryType>, ) -> __wasi_errno_t { super::thread_id::(ctx, ret_tid) } pub(crate) fn thread_join( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, tid: __wasi_tid_t, ) -> Result<__wasi_errno_t, WasiError> { super::thread_join(ctx, tid) } pub(crate) fn thread_parallelism( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ret_parallelism: WasmPtr, ) -> __wasi_errno_t { super::thread_parallelism::(ctx, ret_parallelism) } pub(crate) fn thread_exit( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, exitcode: __wasi_exitcode_t, ) -> Result<__wasi_errno_t, WasiError> { super::thread_exit(ctx, exitcode) } -pub(crate) fn sched_yield(ctx: ContextMut<'_, WasiEnv>) -> Result<__wasi_errno_t, WasiError> { +pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result<__wasi_errno_t, WasiError> { super::sched_yield(ctx) } pub(crate) fn getpid( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ret_pid: WasmPtr<__wasi_pid_t, MemoryType>, ) -> __wasi_errno_t { super::getpid::(ctx, ret_pid) } pub(crate) fn process_spawn( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, name: WasmPtr, name_len: MemoryOffset, chroot: __wasi_bool_t, @@ -553,7 +553,7 @@ pub(crate) fn process_spawn( } pub(crate) fn bus_open_local( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, name: WasmPtr, name_len: MemoryOffset, reuse: __wasi_bool_t, @@ -563,7 +563,7 @@ pub(crate) fn bus_open_local( } pub(crate) fn bus_open_remote( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, name: WasmPtr, name_len: MemoryOffset, reuse: __wasi_bool_t, @@ -586,12 +586,12 @@ pub(crate) fn bus_open_remote( ) } -pub(crate) fn bus_close(ctx: ContextMut<'_, WasiEnv>, bid: __wasi_bid_t) -> __bus_errno_t { +pub(crate) fn bus_close(ctx: FunctionEnvMut, bid: __wasi_bid_t) -> __bus_errno_t { super::bus_close(ctx, bid) } pub(crate) fn bus_call( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, bid: __wasi_bid_t, keep_alive: __wasi_bool_t, topic: WasmPtr, @@ -607,7 +607,7 @@ pub(crate) fn bus_call( } pub(crate) fn bus_subcall( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, parent: __wasi_cid_t, keep_alive: __wasi_bool_t, topic: WasmPtr, @@ -623,7 +623,7 @@ pub(crate) fn bus_subcall( } pub(crate) fn bus_poll( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, timeout: __wasi_timestamp_t, events: WasmPtr, nevents: MemoryOffset, @@ -643,7 +643,7 @@ pub(crate) fn bus_poll( } pub(crate) fn call_reply( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, cid: __wasi_cid_t, format: __wasi_busdataformat_t, buf: WasmPtr, @@ -653,19 +653,19 @@ pub(crate) fn call_reply( } pub(crate) fn call_fault( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, cid: __wasi_cid_t, fault: __bus_errno_t, ) -> __bus_errno_t { super::call_fault(ctx, cid, fault) } -pub(crate) fn call_close(ctx: ContextMut<'_, WasiEnv>, cid: __wasi_cid_t) -> __bus_errno_t { +pub(crate) fn call_close(ctx: FunctionEnvMut, cid: __wasi_cid_t) -> __bus_errno_t { super::call_close(ctx, cid) } pub(crate) fn port_bridge( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, network: WasmPtr, network_len: MemoryOffset, token: WasmPtr, @@ -675,34 +675,34 @@ pub(crate) fn port_bridge( super::port_bridge::(ctx, network, network_len, token, token_len, security) } -pub(crate) fn port_unbridge(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub(crate) fn port_unbridge(ctx: FunctionEnvMut) -> __wasi_errno_t { super::port_unbridge(ctx) } -pub(crate) fn port_dhcp_acquire(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub(crate) fn port_dhcp_acquire(ctx: FunctionEnvMut) -> __wasi_errno_t { super::port_dhcp_acquire(ctx) } pub(crate) fn port_addr_add( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, addr: WasmPtr<__wasi_cidr_t, MemoryType>, ) -> __wasi_errno_t { super::port_addr_add::(ctx, addr) } pub(crate) fn port_addr_remove( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, addr: WasmPtr<__wasi_addr_t, MemoryType>, ) -> __wasi_errno_t { super::port_addr_remove::(ctx, addr) } -pub(crate) fn port_addr_clear(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub(crate) fn port_addr_clear(ctx: FunctionEnvMut) -> __wasi_errno_t { super::port_addr_clear(ctx) } pub(crate) fn port_addr_list( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, addrs: WasmPtr<__wasi_cidr_t, MemoryType>, naddrs: WasmPtr, ) -> __wasi_errno_t { @@ -710,21 +710,21 @@ pub(crate) fn port_addr_list( } pub(crate) fn port_mac( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ret_mac: WasmPtr<__wasi_hardwareaddress_t, MemoryType>, ) -> __wasi_errno_t { super::port_mac::(ctx, ret_mac) } pub(crate) fn port_gateway_set( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ip: WasmPtr<__wasi_addr_t, MemoryType>, ) -> __wasi_errno_t { super::port_gateway_set::(ctx, ip) } pub(crate) fn port_route_add( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, cidr: WasmPtr<__wasi_cidr_t, MemoryType>, via_router: WasmPtr<__wasi_addr_t, MemoryType>, preferred_until: WasmPtr<__wasi_option_timestamp_t, MemoryType>, @@ -734,18 +734,18 @@ pub(crate) fn port_route_add( } pub(crate) fn port_route_remove( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, ip: WasmPtr<__wasi_addr_t, MemoryType>, ) -> __wasi_errno_t { super::port_route_remove::(ctx, ip) } -pub(crate) fn port_route_clear(ctx: ContextMut<'_, WasiEnv>) -> __wasi_errno_t { +pub(crate) fn port_route_clear(ctx: FunctionEnvMut) -> __wasi_errno_t { super::port_route_clear(ctx) } pub(crate) fn port_route_list( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, routes: WasmPtr<__wasi_route_t, MemoryType>, nroutes: WasmPtr, ) -> __wasi_errno_t { @@ -753,7 +753,7 @@ pub(crate) fn port_route_list( } pub(crate) fn ws_connect( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, url: WasmPtr, url_len: MemoryOffset, ret_sock: WasmPtr<__wasi_fd_t, MemoryType>, @@ -762,7 +762,7 @@ pub(crate) fn ws_connect( } pub(crate) fn http_request( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, url: WasmPtr, url_len: MemoryOffset, method: WasmPtr, @@ -786,7 +786,7 @@ pub(crate) fn http_request( } pub(crate) fn http_status( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, status: WasmPtr<__wasi_http_status_t, MemoryType>, status_text: WasmPtr, @@ -798,7 +798,7 @@ pub(crate) fn http_status( } pub(crate) fn sock_status( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ret_status: WasmPtr<__wasi_sockstatus_t, MemoryType>, ) -> __wasi_errno_t { @@ -806,7 +806,7 @@ pub(crate) fn sock_status( } pub(crate) fn sock_addr_local( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ret_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ) -> __wasi_errno_t { @@ -814,7 +814,7 @@ pub(crate) fn sock_addr_local( } pub(crate) fn sock_addr_peer( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ) -> __wasi_errno_t { @@ -822,7 +822,7 @@ pub(crate) fn sock_addr_peer( } pub(crate) fn sock_open( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, af: __wasi_addressfamily_t, ty: __wasi_socktype_t, pt: __wasi_sockproto_t, @@ -832,7 +832,7 @@ pub(crate) fn sock_open( } pub(crate) fn sock_set_opt_flag( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, flag: __wasi_bool_t, @@ -841,7 +841,7 @@ pub(crate) fn sock_set_opt_flag( } pub(crate) fn sock_get_opt_flag( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_flag: WasmPtr<__wasi_bool_t, MemoryType>, @@ -850,7 +850,7 @@ pub(crate) fn sock_get_opt_flag( } pub fn sock_set_opt_time( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, time: WasmPtr<__wasi_option_timestamp_t, MemoryType>, @@ -859,7 +859,7 @@ pub fn sock_set_opt_time( } pub fn sock_get_opt_time( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_time: WasmPtr<__wasi_option_timestamp_t, MemoryType>, @@ -868,7 +868,7 @@ pub fn sock_get_opt_time( } pub fn sock_set_opt_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, size: __wasi_filesize_t, @@ -877,7 +877,7 @@ pub fn sock_set_opt_size( } pub fn sock_get_opt_size( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, opt: __wasi_sockoption_t, ret_size: WasmPtr<__wasi_filesize_t, MemoryType>, @@ -886,7 +886,7 @@ pub fn sock_get_opt_size( } pub(crate) fn sock_join_multicast_v4( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip4_t, MemoryType>, iface: WasmPtr<__wasi_addr_ip4_t, MemoryType>, @@ -895,7 +895,7 @@ pub(crate) fn sock_join_multicast_v4( } pub(crate) fn sock_leave_multicast_v4( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip4_t, MemoryType>, iface: WasmPtr<__wasi_addr_ip4_t, MemoryType>, @@ -904,7 +904,7 @@ pub(crate) fn sock_leave_multicast_v4( } pub(crate) fn sock_join_multicast_v6( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip6_t, MemoryType>, iface: u32, @@ -913,7 +913,7 @@ pub(crate) fn sock_join_multicast_v6( } pub(crate) fn sock_leave_multicast_v6( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, multiaddr: WasmPtr<__wasi_addr_ip6_t, MemoryType>, iface: u32, @@ -922,7 +922,7 @@ pub(crate) fn sock_leave_multicast_v6( } pub(crate) fn sock_bind( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ) -> __wasi_errno_t { @@ -930,7 +930,7 @@ pub(crate) fn sock_bind( } pub(crate) fn sock_listen( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, backlog: MemoryOffset, ) -> __wasi_errno_t { @@ -938,7 +938,7 @@ pub(crate) fn sock_listen( } pub(crate) fn sock_accept( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, fd_flags: __wasi_fdflags_t, ro_fd: WasmPtr<__wasi_fd_t, MemoryType>, @@ -948,7 +948,7 @@ pub(crate) fn sock_accept( } pub(crate) fn sock_connect( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ) -> __wasi_errno_t { @@ -956,7 +956,7 @@ pub(crate) fn sock_connect( } pub(crate) fn sock_recv( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, @@ -976,7 +976,7 @@ pub(crate) fn sock_recv( } pub(crate) fn sock_recv_from( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, @@ -998,7 +998,7 @@ pub(crate) fn sock_recv_from( } pub(crate) fn sock_send( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, @@ -1009,7 +1009,7 @@ pub(crate) fn sock_send( } pub(crate) fn sock_send_to( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, @@ -1029,7 +1029,7 @@ pub(crate) fn sock_send_to( } pub(crate) fn sock_send_file( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, out_fd: __wasi_fd_t, in_fd: __wasi_fd_t, offset: __wasi_filesize_t, @@ -1040,7 +1040,7 @@ pub(crate) fn sock_send_file( } pub(crate) fn sock_shutdown( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, sock: __wasi_fd_t, how: __wasi_sdflags_t, ) -> __wasi_errno_t { @@ -1048,7 +1048,7 @@ pub(crate) fn sock_shutdown( } pub(crate) fn resolve( - ctx: ContextMut<'_, WasiEnv>, + ctx: FunctionEnvMut, host: WasmPtr, host_len: MemoryOffset, port: u16, diff --git a/lib/wasi/tests/stdio.rs b/lib/wasi/tests/stdio.rs index 3af490b8d74..78b93520e1a 100644 --- a/lib/wasi/tests/stdio.rs +++ b/lib/wasi/tests/stdio.rs @@ -1,6 +1,6 @@ use std::io::{Read, Write}; -use wasmer::{AsContextMut, Context, Instance, Module, Store}; +use wasmer::{Instance, Module, Store}; use wasmer_wasi::{Pipe, WasiState}; mod sys { @@ -41,8 +41,8 @@ mod js { } fn test_stdout() { - let store = Store::default(); - let module = Module::new(&store, br#" + let mut store = Store::default(); + let module = Module::new(&mut store, br#" (module ;; Import the required fd_write WASI function which will write the given io vectors to stdout ;; The function signature for fd_write is: @@ -74,28 +74,23 @@ fn test_stdout() { // Create the `WasiEnv`. let mut stdout = Pipe::default(); - let mut wasi_env = WasiState::new("command-name") + let wasi_env = WasiState::new("command-name") .args(&["Gordon"]) .stdout(Box::new(stdout.clone())) - .finalize() + .finalize(&mut store) .unwrap(); - // Create a context state that will hold all objects created by this Instance - let mut ctx = Context::new(&store, wasi_env.clone()); - // Generate an `ImportObject`. - let import_object = wasi_env - .import_object(&mut ctx.as_context_mut(), &module) - .unwrap(); + let import_object = wasi_env.import_object(&mut store, &module).unwrap(); // Let's instantiate the module with the imports. - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let memory = instance.exports.get_memory("memory").unwrap(); - ctx.data_mut().set_memory(memory.clone()); + wasi_env.data_mut(&mut store).set_memory(memory.clone()); // Let's call the `_start` function, which is our `main` function in Rust. let start = instance.exports.get_function("_start").unwrap(); - start.call(&mut ctx, &[]).unwrap(); + start.call(&mut store, &[]).unwrap(); let mut stdout_str = String::new(); stdout.read_to_string(&mut stdout_str).unwrap(); @@ -104,7 +99,7 @@ fn test_stdout() { } fn test_env() { - let store = Store::default(); + let mut store = Store::default(); let module = Module::new(&store, include_bytes!("envvar.wasm")).unwrap(); #[cfg(feature = "js")] @@ -123,27 +118,22 @@ fn test_env() { .env("TEST", "VALUE") .env("TEST2", "VALUE2"); // panic!("envs: {:?}", wasi_state_builder.envs); - let mut wasi_env = wasi_state_builder + let wasi_env = wasi_state_builder .stdout(Box::new(stdout.clone())) - .finalize() + .finalize(&mut store) .unwrap(); - // Create a context state that will hold all objects created by this Instance - let mut ctx = Context::new(&store, wasi_env.clone()); - // Generate an `ImportObject`. - let import_object = wasi_env - .import_object(&mut ctx.as_context_mut(), &module) - .unwrap(); + let import_object = wasi_env.import_object(&mut store, &module).unwrap(); // Let's instantiate the module with the imports. - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let memory = instance.exports.get_memory("memory").unwrap(); - ctx.data_mut().set_memory(memory.clone()); + wasi_env.data_mut(&mut store).set_memory(memory.clone()); // Let's call the `_start` function, which is our `main` function in Rust. let start = instance.exports.get_function("_start").unwrap(); - start.call(&mut ctx, &[]).unwrap(); + start.call(&mut store, &[]).unwrap(); let mut stdout_str = String::new(); stdout.read_to_string(&mut stdout_str).unwrap(); @@ -152,36 +142,31 @@ fn test_env() { } fn test_stdin() { - let store = Store::default(); + let mut store = Store::default(); let module = Module::new(&store, include_bytes!("stdin-hello.wasm")).unwrap(); // Create the `WasiEnv`. let mut stdin = Pipe::new(); - let mut wasi_env = WasiState::new("command-name") + let wasi_env = WasiState::new("command-name") .stdin(Box::new(stdin.clone())) - .finalize() + .finalize(&mut store) .unwrap(); // Write to STDIN let buf = "Hello, stdin!\n".as_bytes().to_owned(); stdin.write(&buf[..]).unwrap(); - // Create a context state that will hold all objects created by this Instance - let mut ctx = Context::new(&store, wasi_env.clone()); - // Generate an `ImportObject`. - let import_object = wasi_env - .import_object(&mut ctx.as_context_mut(), &module) - .unwrap(); + let import_object = wasi_env.import_object(&mut store, &module).unwrap(); // Let's instantiate the module with the imports. - let instance = Instance::new(&mut ctx, &module, &import_object).unwrap(); + let instance = Instance::new(&mut store, &module, &import_object).unwrap(); let memory = instance.exports.get_memory("memory").unwrap(); - ctx.data_mut().set_memory(memory.clone()); + wasi_env.data_mut(&mut store).set_memory(memory.clone()); // Let's call the `_start` function, which is our `main` function in Rust. let start = instance.exports.get_function("_start").unwrap(); - let result = start.call(&mut ctx, &[]); + let result = start.call(&mut store, &[]); assert!(!result.is_err()); // We assure stdin is now empty diff --git a/tests/compilers/deterministic.rs b/tests/compilers/deterministic.rs index 9c9070ce5c0..83a9a0ef2cb 100644 --- a/tests/compilers/deterministic.rs +++ b/tests/compilers/deterministic.rs @@ -1,8 +1,8 @@ use anyhow::Result; -use wasmer::{wat2wasm, Module}; +use wasmer::{wat2wasm, Module, Store}; fn compile_and_compare(wasm: &[u8]) -> Result<()> { - let store = Default::default(); + let store = Store::default(); // compile for first time let module = Module::new(&store, wasm)?; diff --git a/tests/compilers/imports.rs b/tests/compilers/imports.rs index 232103d0a86..558e4fa51bd 100644 --- a/tests/compilers/imports.rs +++ b/tests/compilers/imports.rs @@ -8,7 +8,7 @@ use std::sync::{ atomic::{AtomicUsize, Ordering::SeqCst}, Arc, }; -use wasmer::Context as WasmerContext; +use wasmer::FunctionEnv; use wasmer::Type as ValueType; use wasmer::*; @@ -47,28 +47,28 @@ fn get_module(store: &Store) -> Result { #[compiler_test(imports)] #[serial_test::serial(dynamic_function)] fn dynamic_function(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module(&store)?; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); static HITS: AtomicUsize = AtomicUsize::new(0); let imports = imports! { "host" => { - "0" => Function::new(&mut ctx, FunctionType::new(vec![], vec![]), |_ctx, _values| { + "0" => Function::new(&mut store, &env, FunctionType::new(vec![], vec![]), |_ctx, _values| { assert_eq!(HITS.fetch_add(1, SeqCst), 0); Ok(vec![]) }), - "1" => Function::new(&mut ctx, FunctionType::new(vec![ValueType::I32], vec![ValueType::I32]), |_ctx, values| { + "1" => Function::new(&mut store, &env, FunctionType::new(vec![ValueType::I32], vec![ValueType::I32]), |_ctx, values| { assert_eq!(values[0], Value::I32(0)); assert_eq!(HITS.fetch_add(1, SeqCst), 1); Ok(vec![Value::I32(1)]) }), - "2" => Function::new(&mut ctx, FunctionType::new(vec![ValueType::I32, ValueType::I64], vec![]), |_ctx, values| { + "2" => Function::new(&mut store, &env, FunctionType::new(vec![ValueType::I32, ValueType::I64], vec![]), |_ctx, values| { assert_eq!(values[0], Value::I32(2)); assert_eq!(values[1], Value::I64(3)); assert_eq!(HITS.fetch_add(1, SeqCst), 2); Ok(vec![]) }), - "3" => Function::new(&mut ctx, FunctionType::new(vec![ValueType::I32, ValueType::I64, ValueType::I32, ValueType::F32, ValueType::F64], vec![]), |_ctx, values| { + "3" => Function::new(&mut store, &env, FunctionType::new(vec![ValueType::I32, ValueType::I64, ValueType::I32, ValueType::F32, ValueType::F64], vec![]), |_ctx, values| { assert_eq!(values[0], Value::I32(100)); assert_eq!(values[1], Value::I64(200)); assert_eq!(values[2], Value::I32(300)); @@ -79,14 +79,14 @@ fn dynamic_function(config: crate::Config) -> Result<()> { }), } }; - Instance::new(&mut ctx, &module, &imports)?; + Instance::new(&mut store, &module, &imports)?; assert_eq!(HITS.swap(0, SeqCst), 4); Ok(()) } #[compiler_test(imports)] fn dynamic_function_with_env(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module(&store)?; #[derive(Clone)] @@ -104,9 +104,10 @@ fn dynamic_function_with_env(config: crate::Config) -> Result<()> { let env: Env = Env { counter: Arc::new(AtomicUsize::new(0)), }; - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); let f0 = Function::new( - &mut ctx, + &mut store, + &env, FunctionType::new(vec![], vec![]), |ctx, _values| { assert_eq!(ctx.data().fetch_add(1, SeqCst), 0); @@ -114,7 +115,8 @@ fn dynamic_function_with_env(config: crate::Config) -> Result<()> { }, ); let f1 = Function::new( - &mut ctx, + &mut store, + &env, FunctionType::new(vec![ValueType::I32], vec![ValueType::I32]), |ctx, values| { assert_eq!(values[0], Value::I32(0)); @@ -123,7 +125,8 @@ fn dynamic_function_with_env(config: crate::Config) -> Result<()> { }, ); let f2 = Function::new( - &mut ctx, + &mut store, + &env, FunctionType::new(vec![ValueType::I32, ValueType::I64], vec![]), |ctx, values| { assert_eq!(values[0], Value::I32(2)); @@ -133,7 +136,8 @@ fn dynamic_function_with_env(config: crate::Config) -> Result<()> { }, ); let f3 = Function::new( - &mut ctx, + &mut store, + &env, FunctionType::new( vec![ ValueType::I32, @@ -155,7 +159,7 @@ fn dynamic_function_with_env(config: crate::Config) -> Result<()> { }, ); Instance::new( - &mut ctx, + &mut store, &module, &imports! { "host" => { @@ -166,34 +170,39 @@ fn dynamic_function_with_env(config: crate::Config) -> Result<()> { }, }, )?; - assert_eq!(ctx.data_mut().load(SeqCst), 4); + assert_eq!(env.as_mut(&mut store).load(SeqCst), 4); Ok(()) } #[compiler_test(imports)] #[serial_test::serial(static_function)] fn static_function(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module(&store)?; static HITS: AtomicUsize = AtomicUsize::new(0); - let mut ctx = WasmerContext::new(&store, ()); - let f0 = Function::new_native(&mut ctx, |_ctx: ContextMut<_>| { + let mut env = FunctionEnv::new(&mut store, ()); + let f0 = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<_>| { assert_eq!(HITS.fetch_add(1, SeqCst), 0); }); - let f1 = Function::new_native(&mut ctx, |_ctx: ContextMut<_>, x: i32| -> i32 { + let f1 = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<_>, x: i32| -> i32 { assert_eq!(x, 0); assert_eq!(HITS.fetch_add(1, SeqCst), 1); 1 }); - let f2 = Function::new_native(&mut ctx, |_ctx: ContextMut<_>, x: i32, y: i64| { - assert_eq!(x, 2); - assert_eq!(y, 3); - assert_eq!(HITS.fetch_add(1, SeqCst), 2); - }); + let f2 = Function::new_native( + &mut store, + &env, + |_ctx: FunctionEnvMut<_>, x: i32, y: i64| { + assert_eq!(x, 2); + assert_eq!(y, 3); + assert_eq!(HITS.fetch_add(1, SeqCst), 2); + }, + ); let f3 = Function::new_native( - &mut ctx, - |_ctx: ContextMut<_>, a: i32, b: i64, c: i32, d: f32, e: f64| { + &mut store, + &env, + |_ctx: FunctionEnvMut<_>, a: i32, b: i64, c: i32, d: f32, e: f64| { assert_eq!(a, 100); assert_eq!(b, 200); assert_eq!(c, 300); @@ -203,7 +212,7 @@ fn static_function(config: crate::Config) -> Result<()> { }, ); Instance::new( - &mut ctx, + &mut store, &module, &imports! { "host" => { @@ -221,30 +230,36 @@ fn static_function(config: crate::Config) -> Result<()> { #[compiler_test(imports)] #[serial_test::serial(static_function_with_results)] fn static_function_with_results(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module(&store)?; static HITS: AtomicUsize = AtomicUsize::new(0); - let mut ctx = WasmerContext::new(&store, ()); - let f0 = Function::new_native(&mut ctx, |_ctx: ContextMut<_>| { + let mut env = FunctionEnv::new(&mut store, ()); + let f0 = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<_>| { assert_eq!(HITS.fetch_add(1, SeqCst), 0); }); let f1 = Function::new_native( - &mut ctx, - |_ctx: ContextMut<_>, x: i32| -> Result { + &mut store, + &env, + |_ctx: FunctionEnvMut<_>, x: i32| -> Result { assert_eq!(x, 0); assert_eq!(HITS.fetch_add(1, SeqCst), 1); Ok(1) }, ); - let f2 = Function::new_native(&mut ctx, |_ctx: ContextMut<_>, x: i32, y: i64| { - assert_eq!(x, 2); - assert_eq!(y, 3); - assert_eq!(HITS.fetch_add(1, SeqCst), 2); - }); + let f2 = Function::new_native( + &mut store, + &env, + |_ctx: FunctionEnvMut<_>, x: i32, y: i64| { + assert_eq!(x, 2); + assert_eq!(y, 3); + assert_eq!(HITS.fetch_add(1, SeqCst), 2); + }, + ); let f3 = Function::new_native( - &mut ctx, - |_ctx: ContextMut<_>, a: i32, b: i64, c: i32, d: f32, e: f64| { + &mut store, + &env, + |_ctx: FunctionEnvMut<_>, a: i32, b: i64, c: i32, d: f32, e: f64| { assert_eq!(a, 100); assert_eq!(b, 200); assert_eq!(c, 300); @@ -254,7 +269,7 @@ fn static_function_with_results(config: crate::Config) -> Result<()> { }, ); Instance::new( - &mut ctx, + &mut store, &module, &imports! { "host" => { @@ -271,7 +286,7 @@ fn static_function_with_results(config: crate::Config) -> Result<()> { #[compiler_test(imports)] fn static_function_with_env(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module(&store)?; #[derive(Clone)] @@ -285,23 +300,32 @@ fn static_function_with_env(config: crate::Config) -> Result<()> { } let env: Env = Env(Arc::new(AtomicUsize::new(0))); - let mut ctx = WasmerContext::new(&store, env); - let f0 = Function::new_native(&mut ctx, |ctx: ContextMut| { + let mut env = FunctionEnv::new(&mut store, env); + let f0 = Function::new_native(&mut store, &env, |ctx: FunctionEnvMut| { assert_eq!(ctx.data().fetch_add(1, SeqCst), 0); }); - let f1 = Function::new_native(&mut ctx, |ctx: ContextMut, x: i32| -> i32 { - assert_eq!(x, 0); - assert_eq!(ctx.data().fetch_add(1, SeqCst), 1); - 1 - }); - let f2 = Function::new_native(&mut ctx, |ctx: ContextMut, x: i32, y: i64| { - assert_eq!(x, 2); - assert_eq!(y, 3); - assert_eq!(ctx.data().fetch_add(1, SeqCst), 2); - }); + let f1 = Function::new_native( + &mut store, + &env, + |ctx: FunctionEnvMut, x: i32| -> i32 { + assert_eq!(x, 0); + assert_eq!(ctx.data().fetch_add(1, SeqCst), 1); + 1 + }, + ); + let f2 = Function::new_native( + &mut store, + &env, + |ctx: FunctionEnvMut, x: i32, y: i64| { + assert_eq!(x, 2); + assert_eq!(y, 3); + assert_eq!(ctx.data().fetch_add(1, SeqCst), 2); + }, + ); let f3 = Function::new_native( - &mut ctx, - |ctx: ContextMut, a: i32, b: i64, c: i32, d: f32, e: f64| { + &mut store, + &env, + |ctx: FunctionEnvMut, a: i32, b: i64, c: i32, d: f32, e: f64| { assert_eq!(a, 100); assert_eq!(b, 200); assert_eq!(c, 300); @@ -311,7 +335,7 @@ fn static_function_with_env(config: crate::Config) -> Result<()> { }, ); Instance::new( - &mut ctx, + &mut store, &module, &imports! { "host" => { @@ -322,13 +346,13 @@ fn static_function_with_env(config: crate::Config) -> Result<()> { }, }, )?; - assert_eq!(ctx.data_mut().load(SeqCst), 4); + assert_eq!(env.as_mut(&mut store).load(SeqCst), 4); Ok(()) } #[compiler_test(imports)] fn static_function_that_fails(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (import "host" "0" (func)) @@ -339,15 +363,16 @@ fn static_function_that_fails(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, &wat)?; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let f0 = Function::new_native( - &mut ctx, - |_ctx: ContextMut<_>| -> Result { + &mut store, + &env, + |_ctx: FunctionEnvMut<_>| -> Result { Err(RuntimeError::new("oops")) }, ); let result = Instance::new( - &mut ctx, + &mut store, &module, &imports! { "host" => { @@ -384,7 +409,7 @@ fn get_module2(store: &Store) -> Result { #[compiler_test(imports)] fn dynamic_function_with_env_wasmer_env_init_works(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module2(&store)?; #[allow(dead_code)] @@ -394,9 +419,10 @@ fn dynamic_function_with_env_wasmer_env_init_works(config: crate::Config) -> Res } let env: Env = Env { memory: None }; - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); let f0 = Function::new( - &mut ctx, + &mut store, + &env, FunctionType::new(vec![], vec![]), |ctx, _values| { assert!(ctx.data().memory.as_ref().is_some()); @@ -404,7 +430,7 @@ fn dynamic_function_with_env_wasmer_env_init_works(config: crate::Config) -> Res }, ); let instance = Instance::new( - &mut ctx, + &mut store, &module, &imports! { "host" => { @@ -413,15 +439,15 @@ fn dynamic_function_with_env_wasmer_env_init_works(config: crate::Config) -> Res }, )?; let memory = instance.exports.get_memory("memory")?; - ctx.data_mut().memory = Some(memory.clone()); - let f: TypedFunction<(), ()> = instance.exports.get_typed_function(&ctx, "main")?; - f.call(&mut ctx)?; + env.as_mut(&mut store).memory = Some(memory.clone()); + let f: TypedFunction<(), ()> = instance.exports.get_typed_function(&mut store, "main")?; + f.call(&mut store)?; Ok(()) } #[compiler_test(imports)] fn multi_use_host_fn_manages_memory_correctly(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module2(&store)?; #[allow(dead_code)] @@ -439,30 +465,30 @@ fn multi_use_host_fn_manages_memory_correctly(config: crate::Config) -> Result<( }*/ let env: Env = Env { memory: None }; - let mut ctx = WasmerContext::new(&store, env); - fn host_fn(ctx: ContextMut) { + let mut env = FunctionEnv::new(&mut store, env); + fn host_fn(ctx: FunctionEnvMut) { assert!(ctx.data().memory.is_some()); println!("Hello, world!"); } let imports = imports! { "host" => { - "fn" => Function::new_native(&mut ctx, host_fn), + "fn" => Function::new_native(&mut store, &env, host_fn), }, }; - let instance1 = Instance::new(&mut ctx, &module, &imports)?; - let instance2 = Instance::new(&mut ctx, &module, &imports)?; + let instance1 = Instance::new(&mut store, &module, &imports)?; + let instance2 = Instance::new(&mut store, &module, &imports)?; { - let f1: TypedFunction<(), ()> = instance1.exports.get_typed_function(&mut ctx, "main")?; + let f1: TypedFunction<(), ()> = instance1.exports.get_typed_function(&mut store, "main")?; let memory = instance1.exports.get_memory("memory")?; - ctx.data_mut().memory = Some(memory.clone()); - f1.call(&mut ctx)?; + env.as_mut(&mut store).memory = Some(memory.clone()); + f1.call(&mut store)?; } drop(instance1); { - let f2: TypedFunction<(), ()> = instance2.exports.get_typed_function(&mut ctx, "main")?; + let f2: TypedFunction<(), ()> = instance2.exports.get_typed_function(&mut store, "main")?; let memory = instance2.exports.get_memory("memory")?; - ctx.data_mut().memory = Some(memory.clone()); - f2.call(&mut ctx)?; + env.as_mut(&mut store).memory = Some(memory.clone()); + f2.call(&mut store)?; } drop(instance2); Ok(()) @@ -470,15 +496,15 @@ fn multi_use_host_fn_manages_memory_correctly(config: crate::Config) -> Result<( #[compiler_test(imports)] fn instance_local_memory_lifetime(config: crate::Config) -> Result<()> { - let store = config.store(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = config.store(); + let mut env = FunctionEnv::new(&mut store, ()); let memory: Memory = { let wat = r#"(module (memory $mem 1) (export "memory" (memory $mem)) )"#; let module = Module::new(&store, wat)?; - let instance = Instance::new(&mut ctx, &module, &imports! {})?; + let instance = Instance::new(&mut store, &module, &imports! {})?; instance.exports.get_memory("memory")?.clone() }; @@ -499,13 +525,13 @@ fn instance_local_memory_lifetime(config: crate::Config) -> Result<()> { "memory" => memory, }, }; - let instance = Instance::new(&mut ctx, &module, &imports)?; + let instance = Instance::new(&mut store, &module, &imports)?; let set_at: TypedFunction<(i32, i32), ()> = - instance.exports.get_typed_function(&mut ctx, "set_at")?; + instance.exports.get_typed_function(&mut store, "set_at")?; let get_at: TypedFunction = - instance.exports.get_typed_function(&mut ctx, "get_at")?; - set_at.call(&mut ctx, 200, 123)?; - assert_eq!(get_at.call(&mut ctx, 200)?, 123); + instance.exports.get_typed_function(&mut store, "get_at")?; + set_at.call(&mut store, 200, 123)?; + assert_eq!(get_at.call(&mut store, 200)?, 123); Ok(()) } diff --git a/tests/compilers/issues.rs b/tests/compilers/issues.rs index 07064cc95ca..03a301e8690 100644 --- a/tests/compilers/issues.rs +++ b/tests/compilers/issues.rs @@ -1,6 +1,6 @@ //! This file is mainly to assure specific issues are working well use anyhow::Result; -use wasmer::Context as WasmerContext; +use wasmer::FunctionEnv; use wasmer::*; /// Corruption of WasmerEnv when using call indirect. @@ -11,7 +11,7 @@ use wasmer::*; /// https://github.com/wasmerio/wasmer/issues/2329 #[compiler_test(issues)] fn issue_2329(mut config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); #[derive(Clone, Default)] pub struct Env { @@ -24,8 +24,8 @@ fn issue_2329(mut config: crate::Config) -> Result<()> { } } - pub fn read_memory(ctx: ContextMut, guest_ptr: u32) -> u32 { - dbg!(ctx.data().memory.as_ref()); + pub fn read_memory(mut ctx: FunctionEnvMut, guest_ptr: u32) -> u32 { + dbg!(ctx.data_mut().memory.as_ref()); dbg!(guest_ptr); 0 } @@ -61,26 +61,27 @@ fn issue_2329(mut config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, wat)?; let env = Env::new(); - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); let imports: Imports = imports! { "env" => { "__read_memory" => Function::new_native( - &mut ctx, + &mut store, + &env, read_memory ), } }; - let instance = Instance::new(&mut ctx, &module, &imports)?; + let instance = Instance::new(&mut store, &module, &imports)?; instance .exports .get_function("read_memory")? - .call(&mut ctx, &[])?; + .call(&mut store, &[])?; Ok(()) } #[compiler_test(issues)] fn call_with_static_data_pointers(mut config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); #[derive(Clone)] pub struct Env { @@ -88,7 +89,7 @@ fn call_with_static_data_pointers(mut config: crate::Config) -> Result<()> { } pub fn banana( - mut ctx: ContextMut, + mut ctx: FunctionEnvMut, a: u64, b: u64, c: u64, @@ -100,24 +101,24 @@ fn call_with_static_data_pointers(mut config: crate::Config) -> Result<()> { ) -> u64 { println!("{:?}", (a, b, c, d, e, f, g, h)); let mut buf = vec![0; d as usize]; - let memory = ctx.data().memory.as_ref().unwrap(); - memory.read(&ctx, e, &mut buf).unwrap(); + let memory = ctx.data_mut().memory.as_ref().unwrap().clone(); + memory.read(&mut ctx, e, &mut buf).unwrap(); let input_string = std::str::from_utf8(&buf).unwrap(); assert_eq!(input_string, "bananapeach"); 0 } - pub fn mango(ctx: ContextMut, a: u64) {} + pub fn mango(ctx: FunctionEnvMut, a: u64) {} - pub fn chaenomeles(ctx: ContextMut, a: u64) -> u64 { + pub fn chaenomeles(ctx: FunctionEnvMut, a: u64) -> u64 { 0 } - pub fn peach(ctx: ContextMut, a: u64, b: u64) -> u64 { + pub fn peach(ctx: FunctionEnvMut, a: u64, b: u64) -> u64 { 0 } - pub fn gas(ctx: ContextMut, a: u32) {} + pub fn gas(ctx: FunctionEnvMut, a: u32) {} let wat = r#" (module @@ -187,27 +188,30 @@ fn call_with_static_data_pointers(mut config: crate::Config) -> Result<()> { let module = Module::new(&store, wat)?; let env = Env { memory: None }; - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); let memory = Memory::new( - &mut ctx, + &mut store, MemoryType::new(Pages(1024), Some(Pages(2048)), false), ) .unwrap(); - ctx.data_mut().memory = Some(memory.clone()); + env.as_mut(&mut store).memory = Some(memory.clone()); let mut exports = Exports::new(); exports.insert("memory", memory); - exports.insert("banana", Function::new_native(&mut ctx, banana)); - exports.insert("peach", Function::new_native(&mut ctx, peach)); - exports.insert("chaenomeles", Function::new_native(&mut ctx, chaenomeles)); - exports.insert("mango", Function::new_native(&mut ctx, mango)); - exports.insert("gas", Function::new_native(&mut ctx, gas)); + exports.insert("banana", Function::new_native(&mut store, &env, banana)); + exports.insert("peach", Function::new_native(&mut store, &env, peach)); + exports.insert( + "chaenomeles", + Function::new_native(&mut store, &env, chaenomeles), + ); + exports.insert("mango", Function::new_native(&mut store, &env, mango)); + exports.insert("gas", Function::new_native(&mut store, &env, gas)); let mut imports = Imports::new(); imports.register_namespace("env", exports); - let instance = Instance::new(&mut ctx, &module, &imports)?; + let instance = Instance::new(&mut store, &module, &imports)?; instance .exports .get_function("repro")? - .call(&mut ctx, &[])?; + .call(&mut store, &[])?; Ok(()) } @@ -217,7 +221,7 @@ fn call_with_static_data_pointers(mut config: crate::Config) -> Result<()> { /// available compilers. #[compiler_test(issues)] fn regression_gpr_exhaustion_for_calls(mut config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module (type (;0;) (func (param f64) (result i32))) @@ -244,9 +248,9 @@ fn regression_gpr_exhaustion_for_calls(mut config: crate::Config) -> Result<()> i32.const 0) (table (;0;) 1 1 funcref)) "#; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let module = Module::new(&store, wat)?; let imports: Imports = imports! {}; - let instance = Instance::new(&mut ctx, &module, &imports)?; + let instance = Instance::new(&mut store, &module, &imports)?; Ok(()) } diff --git a/tests/compilers/metering.rs b/tests/compilers/metering.rs index faf43e3ee55..4df524aad4b 100644 --- a/tests/compilers/metering.rs +++ b/tests/compilers/metering.rs @@ -3,7 +3,7 @@ use wasmer_middlewares::Metering; use std::sync::Arc; use wasmer::wasmparser::Operator; -use wasmer::Context as WasmerContext; +use wasmer::FunctionEnv; use wasmer::*; fn cost_always_one(_: &Operator) -> u64 { @@ -14,21 +14,22 @@ fn run_add_with_limit(mut config: crate::Config, limit: u64) -> Result<()> { config .middlewares .push(Arc::new(Metering::new(limit, cost_always_one))); - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func (export "add") (param i32 i32) (result i32) (i32.add (local.get 0) (local.get 1))) )"#; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! {}; let module = Module::new(&store, wat).unwrap(); - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; - let f: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut ctx, "add")?; - f.call(&mut ctx, 4, 6)?; + let f: TypedFunction<(i32, i32), i32> = + instance.exports.get_typed_function(&mut store, "add")?; + f.call(&mut store, 4, 6)?; Ok(()) } @@ -36,7 +37,7 @@ fn run_loop(mut config: crate::Config, limit: u64, iter_count: i32) -> Result<() config .middlewares .push(Arc::new(Metering::new(limit, cost_always_one))); - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func (export "test") (param i32) (local i32) @@ -53,14 +54,14 @@ fn run_loop(mut config: crate::Config, limit: u64, iter_count: i32) -> Result<() ) )"#; let module = Module::new(&store, wat).unwrap(); - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! {}; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; - let f: TypedFunction = instance.exports.get_typed_function(&mut ctx, "test")?; - f.call(&mut ctx, iter_count)?; + let f: TypedFunction = instance.exports.get_typed_function(&mut store, "test")?; + f.call(&mut store, iter_count)?; Ok(()) } @@ -154,20 +155,20 @@ fn complex_loop(mut config: crate::Config) -> Result<()> { config .middlewares .push(Arc::new(Metering::new(100, cost_always_one))); - let store = config.store(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = config.store(); + let mut env = FunctionEnv::new(&mut store, ()); let module = Module::new(&store, WAT).unwrap(); let import_object = imports! {}; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; let f: TypedFunction<(i32, i32), i32> = - instance.exports.get_typed_function(&mut ctx, "add_to")?; + instance.exports.get_typed_function(&mut store, "add_to")?; // FIXME: Since now a metering error is signaled with an `unreachable`, it is impossible to verify // the error type. Fix this later. - f.call(&mut ctx, 10_000_000, 4).unwrap_err(); + f.call(&mut store, 10_000_000, 4).unwrap_err(); Ok(()) } diff --git a/tests/compilers/middlewares.rs b/tests/compilers/middlewares.rs index 700051da7b7..b7687ba4bf2 100644 --- a/tests/compilers/middlewares.rs +++ b/tests/compilers/middlewares.rs @@ -2,7 +2,7 @@ use anyhow::Result; use std::sync::Arc; use wasmer::wasmparser::Operator; -use wasmer::Context as WasmerContext; +use wasmer::FunctionEnv; use wasmer::*; #[derive(Debug)] @@ -93,21 +93,22 @@ fn middleware_basic(mut config: crate::Config) -> Result<()> { config.set_middlewares(vec![ Arc::new(Add2MulGen { value_off: 0 }) as Arc ]); - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func (export "add") (param i32 i32) (result i32) (i32.add (local.get 0) (local.get 1))) )"#; let module = Module::new(&store, wat).unwrap(); - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! {}; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; - let f: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut ctx, "add")?; - let result = f.call(&mut ctx, 4, 6)?; + let f: TypedFunction<(i32, i32), i32> = + instance.exports.get_typed_function(&mut store, "add")?; + let result = f.call(&mut store, 4, 6)?; assert_eq!(result, 24); Ok(()) } @@ -117,20 +118,21 @@ fn middleware_one_to_multi(mut config: crate::Config) -> Result<()> { config.set_middlewares(vec![ Arc::new(Add2MulGen { value_off: 1 }) as Arc ]); - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func (export "add") (param i32 i32) (result i32) (i32.add (local.get 0) (local.get 1))) )"#; let module = Module::new(&store, wat).unwrap(); - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! {}; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; - let f: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut ctx, "add")?; - let result = f.call(&mut ctx, 4, 6)?; + let f: TypedFunction<(i32, i32), i32> = + instance.exports.get_typed_function(&mut store, "add")?; + let result = f.call(&mut store, 4, 6)?; assert_eq!(result, 25); Ok(()) } @@ -138,7 +140,7 @@ fn middleware_one_to_multi(mut config: crate::Config) -> Result<()> { #[compiler_test(middlewares)] fn middleware_multi_to_one(mut config: crate::Config) -> Result<()> { config.set_middlewares(vec![Arc::new(FusionGen) as Arc]); - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func (export "testfunc") (param i32 i32) (result i32) (local.get 0) @@ -148,14 +150,15 @@ fn middleware_multi_to_one(mut config: crate::Config) -> Result<()> { (i32.mul)) )"#; let module = Module::new(&store, wat).unwrap(); - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! {}; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; - let f: TypedFunction<(i32, i32), i32> = - instance.exports.get_typed_function(&mut ctx, "testfunc")?; - let result = f.call(&mut ctx, 10, 20)?; + let f: TypedFunction<(i32, i32), i32> = instance + .exports + .get_typed_function(&mut store, "testfunc")?; + let result = f.call(&mut store, 10, 20)?; assert_eq!(result, 10); Ok(()) } @@ -166,20 +169,20 @@ fn middleware_chain_order_1(mut config: crate::Config) -> Result<()> { Arc::new(Add2MulGen { value_off: 0 }) as Arc, Arc::new(Add2MulGen { value_off: 2 }) as Arc, ]); - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func (export "add") (param i32 i32) (result i32) (i32.add (local.get 0) (local.get 1))) )"#; let module = Module::new(&store, wat).unwrap(); - let mut ctx = WasmerContext::new(&store, ()); let import_object = imports! {}; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; - let f: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut ctx, "add")?; - let result = f.call(&mut ctx, 4, 6)?; + let f: TypedFunction<(i32, i32), i32> = + instance.exports.get_typed_function(&mut store, "add")?; + let result = f.call(&mut store, 4, 6)?; assert_eq!(result, 24); Ok(()) } @@ -190,20 +193,20 @@ fn middleware_chain_order_2(mut config: crate::Config) -> Result<()> { Arc::new(Add2MulGen { value_off: 2 }) as Arc, Arc::new(Add2MulGen { value_off: 0 }) as Arc, ]); - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func (export "add") (param i32 i32) (result i32) (i32.add (local.get 0) (local.get 1))) )"#; let module = Module::new(&store, wat).unwrap(); - let mut ctx = WasmerContext::new(&store, ()); let import_object = imports! {}; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; - let f: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut ctx, "add")?; - let result = f.call(&mut ctx, 4, 6)?; + let f: TypedFunction<(i32, i32), i32> = + instance.exports.get_typed_function(&mut store, "add")?; + let result = f.call(&mut store, 4, 6)?; assert_eq!(result, 48); Ok(()) } diff --git a/tests/compilers/multi_value_imports.rs b/tests/compilers/multi_value_imports.rs index d260bc0635d..26f291938b3 100644 --- a/tests/compilers/multi_value_imports.rs +++ b/tests/compilers/multi_value_imports.rs @@ -37,7 +37,7 @@ macro_rules! mvr_test { #[compiler_test(multi_value_imports)] fn native(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module(&store)?; let instance = wasmer::Instance::new( &module, @@ -62,7 +62,7 @@ macro_rules! mvr_test { #[compiler_test(multi_value_imports)] fn dynamic(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); + let mut store = config.store(); let module = get_module(&store)?; let callback_fn = wasmer::Function::new(&store, &wasmer::FunctionType::new(vec![wasmer::ValType::I32], vec![ $( <$result_type>::expected_valtype() ),* ]), dynamic_callback_fn); let instance = wasmer::Instance::new( diff --git a/tests/compilers/native_functions.rs b/tests/compilers/native_functions.rs index fc756576a26..3f6ecac790c 100644 --- a/tests/compilers/native_functions.rs +++ b/tests/compilers/native_functions.rs @@ -2,12 +2,12 @@ use anyhow::Result; use std::convert::Infallible; use std::sync::{Arc, Mutex}; -use wasmer::Context as WasmerContext; +use wasmer::FunctionEnv; use wasmer::Type as ValueType; use wasmer::*; fn long_f( - _ctx: ContextMut<()>, + _ctx: FunctionEnvMut<()>, a: u32, b: u32, c: u32, @@ -31,7 +31,7 @@ fn long_f( + a as u64 * 1000000000 } -fn long_f_dynamic(_ctx: ContextMut<()>, values: &[Value]) -> Result, RuntimeError> { +fn long_f_dynamic(_ctx: FunctionEnvMut<()>, values: &[Value]) -> Result, RuntimeError> { Ok(vec![Value::I64( values[9].unwrap_i32() as i64 + values[8].unwrap_i32() as i64 * 10 @@ -48,7 +48,7 @@ fn long_f_dynamic(_ctx: ContextMut<()>, values: &[Value]) -> Result, #[compiler_test(native_functions)] fn native_function_works_for_wasm(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func $multiply (import "env" "multiply") (param i32 i32) (result i32)) (func (export "add") (param i32 i32) (result i32) @@ -59,32 +59,32 @@ fn native_function_works_for_wasm(config: crate::Config) -> anyhow::Result<()> { (call $multiply (local.get 1) (i32.const 2)))) )"#; let module = Module::new(&store, wat).unwrap(); - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! { "env" => { - "multiply" => Function::new_native(&mut ctx, |_ctx: ContextMut<_>, a: i32, b: i32| a * b), + "multiply" => Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<_>, a: i32, b: i32| a * b), }, }; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; { let f: TypedFunction<(i32, i32), i32> = - instance.exports.get_typed_function(&mut ctx, "add")?; - let result = f.call(&mut ctx, 4, 6)?; + instance.exports.get_typed_function(&mut store, "add")?; + let result = f.call(&mut store, 4, 6)?; assert_eq!(result, 10); } { let f: &Function = instance.exports.get("double_then_add")?; - let result = f.call(&mut ctx, &[Value::I32(4), Value::I32(6)])?; + let result = f.call(&mut store, &[Value::I32(4), Value::I32(6)])?; assert_eq!(result[0], Value::I32(20)); } { let dyn_f: &Function = instance.exports.get("double_then_add")?; - let f: TypedFunction<(i32, i32), i32> = dyn_f.native(&mut ctx).unwrap(); - let result = f.call(&mut ctx, 4, 6)?; + let f: TypedFunction<(i32, i32), i32> = dyn_f.native(&mut store).unwrap(); + let result = f.call(&mut store, 4, 6)?; assert_eq!(result, 20); } @@ -93,28 +93,32 @@ fn native_function_works_for_wasm(config: crate::Config) -> anyhow::Result<()> { #[compiler_test(native_functions)] fn native_host_function_closure_panics(config: crate::Config) { - let store = config.store(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = config.store(); + let mut env = FunctionEnv::new(&mut store, ()); let state = 3; - Function::new_native(&mut ctx, move |_ctx: ContextMut<_>, _: i32| { + Function::new_native(&mut store, &env, move |_ctx: FunctionEnvMut<_>, _: i32| { println!("{}", state); }); } #[compiler_test(native_functions)] fn native_with_env_host_function_closure_panics(config: crate::Config) { - let store = config.store(); + let mut store = config.store(); let env: i32 = 4; - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); let state = 3; - Function::new_native(&mut ctx, move |_ctx: ContextMut, _: i32| { - println!("{}", state); - }); + Function::new_native( + &mut store, + &env, + move |_ctx: FunctionEnvMut, _: i32| { + println!("{}", state); + }, + ); } #[compiler_test(native_functions)] fn non_native_functions_and_closures_with_no_env_work(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func $multiply1 (import "env" "multiply1") (param i32 i32) (result i32)) (func $multiply2 (import "env" "multiply2") (param i32 i32) (result i32)) @@ -134,38 +138,38 @@ fn non_native_functions_and_closures_with_no_env_work(config: crate::Config) -> )"#; let module = Module::new(&store, wat).unwrap(); let env: i32 = 10; - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); let ty = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]); let captured_by_closure = 20; let import_object = imports! { "env" => { - "multiply1" => Function::new(&mut ctx, &ty, move |_ctx, args| { + "multiply1" => Function::new(&mut store, &env, &ty, move |_ctx, args| { if let (Value::I32(v1), Value::I32(v2)) = (&args[0], &args[1]) { Ok(vec![Value::I32(v1 * v2 * captured_by_closure)]) } else { panic!("Invalid arguments"); } }), - "multiply2" => Function::new(&mut ctx, &ty, move |ctx, args| { + "multiply2" => Function::new(&mut store, &env, &ty, move |ctx, args| { if let (Value::I32(v1), Value::I32(v2)) = (&args[0], &args[1]) { Ok(vec![Value::I32(v1 * v2 * captured_by_closure * ctx.data())]) } else { panic!("Invalid arguments"); } }), - "multiply3" => Function::new_native(&mut ctx, |_ctx: ContextMut<_>, arg1: i32, arg2: i32| -> i32 + "multiply3" => Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<_>, arg1: i32, arg2: i32| -> i32 {arg1 * arg2 }), - "multiply4" => Function::new_native(&mut ctx, |ctx: ContextMut, arg1: i32, arg2: i32| -> i32 + "multiply4" => Function::new_native(&mut store, &env, |ctx: FunctionEnvMut, arg1: i32, arg2: i32| -> i32 {arg1 * arg2 * ctx.data() }), }, }; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; let test: TypedFunction<(i32, i32, i32, i32, i32), i32> = - instance.exports.get_typed_function(&mut ctx, "test")?; + instance.exports.get_typed_function(&mut store, "test")?; - let result = test.call(&mut ctx, 2, 3, 4, 5, 6)?; + let result = test.call(&mut store, 2, 3, 4, 5, 6)?; let manually_computed_result = 6 * (5 * (4 * (3 * 2 * 20) * 10 * 20)) * 10; assert_eq!(result, manually_computed_result); Ok(()) @@ -173,7 +177,7 @@ fn non_native_functions_and_closures_with_no_env_work(config: crate::Config) -> #[compiler_test(native_functions)] fn native_function_works_for_wasm_function_manyparams(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#"(module (func $longf (import "env" "longf") (param i32 i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i64)) (func (export "longf_pure") (param i32 i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i64) @@ -182,27 +186,27 @@ fn native_function_works_for_wasm_function_manyparams(config: crate::Config) -> (call $longf (i32.const 1) (i32.const 2) (i32.const 3) (i32.const 4) (i32.const 5) (i32.const 6) (i64.const 7) (i64.const 8) (i32.const 9) (i32.const 0))) )"#; let module = Module::new(&store, wat).unwrap(); - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let import_object = imports! { "env" => { - "longf" => Function::new_native(&mut ctx, long_f), + "longf" => Function::new_native(&mut store, &env, long_f), }, }; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; { let dyn_f: &Function = instance.exports.get("longf")?; - let f: TypedFunction<(), i64> = dyn_f.native(&mut ctx).unwrap(); - let result = f.call(&mut ctx)?; + let f: TypedFunction<(), i64> = dyn_f.native(&mut store).unwrap(); + let result = f.call(&mut store)?; assert_eq!(result, 1234567890); } { let dyn_f: &Function = instance.exports.get("longf_pure")?; let f: TypedFunction<(u32, u32, u32, u32, u32, u16, u64, u64, u16, u32), i64> = - dyn_f.native(&mut ctx).unwrap(); - let result = f.call(&mut ctx, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)?; + dyn_f.native(&mut store).unwrap(); + let result = f.call(&mut store, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)?; assert_eq!(result, 1234567890); } @@ -213,8 +217,8 @@ fn native_function_works_for_wasm_function_manyparams(config: crate::Config) -> fn native_function_works_for_wasm_function_manyparams_dynamic( config: crate::Config, ) -> anyhow::Result<()> { - let store = config.store(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = config.store(); + let mut env = FunctionEnv::new(&mut store, ()); let wat = r#"(module (func $longf (import "env" "longf") (param i32 i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i64)) (func (export "longf_pure") (param i32 i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i64) @@ -226,24 +230,24 @@ fn native_function_works_for_wasm_function_manyparams_dynamic( let import_object = imports! { "env" => { - "longf" => Function::new(&mut ctx, FunctionType::new(vec![ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I64 , ValueType::I64 ,ValueType::I32, ValueType::I32], vec![ValueType::I64]), long_f_dynamic), + "longf" => Function::new(&mut store, &env, FunctionType::new(vec![ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I64 , ValueType::I64 ,ValueType::I32, ValueType::I32], vec![ValueType::I64]), long_f_dynamic), }, }; - let instance = Instance::new(&mut ctx, &module, &import_object)?; + let instance = Instance::new(&mut store, &module, &import_object)?; { let dyn_f: &Function = instance.exports.get("longf")?; - let f: TypedFunction<(), i64> = dyn_f.native(&mut ctx).unwrap(); - let result = f.call(&mut ctx)?; + let f: TypedFunction<(), i64> = dyn_f.native(&mut store).unwrap(); + let result = f.call(&mut store)?; assert_eq!(result, 1234567890); } { let dyn_f: &Function = instance.exports.get("longf_pure")?; let f: TypedFunction<(u32, u32, u32, u32, u32, u16, u64, u64, u16, u32), i64> = - dyn_f.native(&mut ctx).unwrap(); - let result = f.call(&mut ctx, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)?; + dyn_f.native(&mut store).unwrap(); + let result = f.call(&mut store, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)?; assert_eq!(result, 1234567890); } @@ -252,15 +256,15 @@ fn native_function_works_for_wasm_function_manyparams_dynamic( #[compiler_test(native_functions)] fn static_host_function_without_env(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = config.store(); + let mut env = FunctionEnv::new(&mut store, ()); - fn f(_ctx: ContextMut<()>, a: i32, b: i64, c: f32, d: f64) -> (f64, f32, i64, i32) { + fn f(_ctx: FunctionEnvMut<()>, a: i32, b: i64, c: f32, d: f64) -> (f64, f32, i64, i32) { (d * 4.0, c * 3.0, b * 2, a * 1) } fn f_ok( - _ctx: ContextMut<()>, + _ctx: FunctionEnvMut<()>, a: i32, b: i64, c: f32, @@ -270,7 +274,7 @@ fn static_host_function_without_env(config: crate::Config) -> anyhow::Result<()> } fn long_f( - _ctx: ContextMut<()>, + _ctx: FunctionEnvMut<()>, a: u32, b: u32, c: u32, @@ -291,30 +295,30 @@ fn static_host_function_without_env(config: crate::Config) -> anyhow::Result<()> // Native static host function that returns a tuple. { - let f = Function::new_native(&mut ctx, f); + let f = Function::new_native(&mut store, &env, f); let f_native: TypedFunction<(i32, i64, f32, f64), (f64, f32, i64, i32)> = - f.native(&mut ctx).unwrap(); - let result = f_native.call(&mut ctx, 1, 3, 5.0, 7.0)?; + f.native(&mut store).unwrap(); + let result = f_native.call(&mut store, 1, 3, 5.0, 7.0)?; assert_eq!(result, (28.0, 15.0, 6, 1)); } // Native static host function that returns a tuple. { - let long_f = Function::new_native(&mut ctx, long_f); + let long_f = Function::new_native(&mut store, &env, long_f); let long_f_native: TypedFunction< (u32, u32, u32, u32, u32, u16, u64, u64, u16, u32), (u32, u64, u32), - > = long_f.native(&mut ctx).unwrap(); - let result = long_f_native.call(&mut ctx, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)?; + > = long_f.native(&mut store).unwrap(); + let result = long_f_native.call(&mut store, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)?; assert_eq!(result, (654321, 87, 09)); } // Native static host function that returns a result of a tuple. { - let f = Function::new_native(&mut ctx, f_ok); + let f = Function::new_native(&mut store, &env, f_ok); let f_native: TypedFunction<(i32, i64, f32, f64), (f64, f32, i64, i32)> = - f.native(&mut ctx).unwrap(); - let result = f_native.call(&mut ctx, 1, 3, 5.0, 7.0)?; + f.native(&mut store).unwrap(); + let result = f_native.call(&mut store, 1, 3, 5.0, 7.0)?; assert_eq!(result, (28.0, 15.0, 6, 1)); } @@ -323,9 +327,9 @@ fn static_host_function_without_env(config: crate::Config) -> anyhow::Result<()> #[compiler_test(native_functions)] fn static_host_function_with_env(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); + let mut store = config.store(); - fn f(mut ctx: ContextMut, a: i32, b: i64, c: f32, d: f64) -> (f64, f32, i64, i32) { + fn f(mut ctx: FunctionEnvMut, a: i32, b: i64, c: f32, d: f64) -> (f64, f32, i64, i32) { let mut guard = ctx.data_mut().0.lock().unwrap(); assert_eq!(*guard, 100); *guard = 101; @@ -334,7 +338,7 @@ fn static_host_function_with_env(config: crate::Config) -> anyhow::Result<()> { } fn f_ok( - mut ctx: ContextMut, + mut ctx: FunctionEnvMut, a: i32, b: i64, c: f32, @@ -360,35 +364,35 @@ fn static_host_function_with_env(config: crate::Config) -> anyhow::Result<()> { // Native static host function that returns a tuple. { let env = Env(Arc::new(Mutex::new(100))); - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); - let f = Function::new_native(&mut ctx, f); + let f = Function::new_native(&mut store, &env, f); let f_native: TypedFunction<(i32, i64, f32, f64), (f64, f32, i64, i32)> = - f.native(&mut ctx).unwrap(); + f.native(&mut store).unwrap(); - assert_eq!(*ctx.data_mut().0.lock().unwrap(), 100); + assert_eq!(*env.as_mut(&mut store).0.lock().unwrap(), 100); - let result = f_native.call(&mut ctx, 1, 3, 5.0, 7.0)?; + let result = f_native.call(&mut store, 1, 3, 5.0, 7.0)?; assert_eq!(result, (28.0, 15.0, 6, 1)); - assert_eq!(*ctx.data_mut().0.lock().unwrap(), 101); + assert_eq!(*env.as_mut(&mut store).0.lock().unwrap(), 101); } // Native static host function that returns a result of a tuple. { let env = Env(Arc::new(Mutex::new(100))); - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); - let f = Function::new_native(&mut ctx, f_ok); + let f = Function::new_native(&mut store, &env, f_ok); let f_native: TypedFunction<(i32, i64, f32, f64), (f64, f32, i64, i32)> = - f.native(&mut ctx).unwrap(); + f.native(&mut store).unwrap(); - assert_eq!(*ctx.data_mut().0.lock().unwrap(), 100); + assert_eq!(*env.as_mut(&mut store).0.lock().unwrap(), 100); - let result = f_native.call(&mut ctx, 1, 3, 5.0, 7.0)?; + let result = f_native.call(&mut store, 1, 3, 5.0, 7.0)?; assert_eq!(result, (28.0, 15.0, 6, 1)); - assert_eq!(*ctx.data_mut().0.lock().unwrap(), 101); + assert_eq!(*env.as_mut(&mut store).0.lock().unwrap(), 101); } Ok(()) @@ -396,10 +400,11 @@ fn static_host_function_with_env(config: crate::Config) -> anyhow::Result<()> { #[compiler_test(native_functions)] fn dynamic_host_function_without_env(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); - let mut ctx = WasmerContext::new(&store, ()); + let mut store = config.store(); + let mut env = FunctionEnv::new(&mut store, ()); let f = Function::new( - &mut ctx, + &mut store, + &env, FunctionType::new( vec![ ValueType::I32, @@ -414,7 +419,7 @@ fn dynamic_host_function_without_env(config: crate::Config) -> anyhow::Result<() ValueType::I32, ], ), - |_ctx: ContextMut<_>, values| { + |_ctx: FunctionEnvMut<_>, values| { Ok(vec![ Value::F64(values[3].unwrap_f64() * 4.0), Value::F32(values[2].unwrap_f32() * 3.0), @@ -424,8 +429,8 @@ fn dynamic_host_function_without_env(config: crate::Config) -> anyhow::Result<() }, ); let f_native: TypedFunction<(i32, i64, f32, f64), (f64, f32, i64, i32)> = - f.native(&mut ctx).unwrap(); - let result = f_native.call(&mut ctx, 1, 3, 5.0, 7.0)?; + f.native(&mut store).unwrap(); + let result = f_native.call(&mut store, 1, 3, 5.0, 7.0)?; assert_eq!(result, (28.0, 15.0, 6, 1)); @@ -434,7 +439,7 @@ fn dynamic_host_function_without_env(config: crate::Config) -> anyhow::Result<() #[compiler_test(native_functions)] fn dynamic_host_function_with_env(config: crate::Config) -> anyhow::Result<()> { - let store = config.store(); + let mut store = config.store(); #[derive(Clone)] struct Env(Arc>); @@ -447,9 +452,10 @@ fn dynamic_host_function_with_env(config: crate::Config) -> anyhow::Result<()> { } let env = Env(Arc::new(Mutex::new(100))); - let mut ctx = WasmerContext::new(&store, env); + let mut env = FunctionEnv::new(&mut store, env); let f = Function::new( - &mut ctx, + &mut store, + &env, FunctionType::new( vec![ ValueType::I32, @@ -480,14 +486,14 @@ fn dynamic_host_function_with_env(config: crate::Config) -> anyhow::Result<()> { ); let f_native: TypedFunction<(i32, i64, f32, f64), (f64, f32, i64, i32)> = - f.native(&mut ctx).unwrap(); + f.native(&mut store).unwrap(); - assert_eq!(*ctx.data().0.lock().unwrap(), 100); + assert_eq!(*env.as_mut(&mut store).0.lock().unwrap(), 100); - let result = f_native.call(&mut ctx, 1, 3, 5.0, 7.0)?; + let result = f_native.call(&mut store, 1, 3, 5.0, 7.0)?; assert_eq!(result, (28.0, 15.0, 6, 1)); - assert_eq!(*ctx.data().0.lock().unwrap(), 101); + assert_eq!(*env.as_mut(&mut store).0.lock().unwrap(), 101); Ok(()) } diff --git a/tests/compilers/serialize.rs b/tests/compilers/serialize.rs index 96306f0666a..1b796bf58c5 100644 --- a/tests/compilers/serialize.rs +++ b/tests/compilers/serialize.rs @@ -1,10 +1,10 @@ use anyhow::Result; -use wasmer::Context as WasmerContext; +use wasmer::FunctionEnv; use wasmer::*; #[compiler_test(serialize)] fn test_serialize(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module (func $hello (import "" "hello")) @@ -20,7 +20,7 @@ fn test_serialize(config: crate::Config) -> Result<()> { #[compiler_test(serialize)] fn test_deserialize(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module $name (import "host" "sum_part" (func (param i32 i64 i32 f32 f64) (result i64))) @@ -54,8 +54,8 @@ fn test_deserialize(config: crate::Config) -> Result<()> { vec![Type::I32, Type::I64, Type::I32, Type::F32, Type::F64], vec![Type::I64], ); - let mut ctx = WasmerContext::new(&store, ()); - let f0 = Function::new(&mut ctx, &func_type, |_ctx, params| { + let mut env = FunctionEnv::new(&mut store, ()); + let f0 = Function::new(&mut store, &env, &func_type, |_ctx, params| { let param_0: i64 = params[0].unwrap_i32() as i64; let param_1: i64 = params[1].unwrap_i64() as i64; let param_2: i64 = params[2].unwrap_i32() as i64; @@ -66,7 +66,7 @@ fn test_deserialize(config: crate::Config) -> Result<()> { )]) }); let instance = Instance::new( - &mut ctx, + &mut store, &module, &imports! { "host" => { @@ -76,7 +76,7 @@ fn test_deserialize(config: crate::Config) -> Result<()> { )?; let test_call = instance.exports.get_function("test_call")?; - let result = test_call.call(&mut ctx, &[])?; + let result = test_call.call(&mut store, &[])?; assert_eq!(result.to_vec(), vec![Value::I64(1500)]); Ok(()) } diff --git a/tests/compilers/traps.rs b/tests/compilers/traps.rs index 4cf7d4226fb..fff22c69e05 100644 --- a/tests/compilers/traps.rs +++ b/tests/compilers/traps.rs @@ -1,11 +1,11 @@ use anyhow::Result; use std::panic::{self, AssertUnwindSafe}; -use wasmer::Context as WasmerContext; +use wasmer::FunctionEnv; use wasmer::*; #[compiler_test(traps)] fn test_trap_return(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module (func $hello (import "" "hello")) @@ -14,14 +14,14 @@ fn test_trap_return(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, wat)?; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let hello_type = FunctionType::new(vec![], vec![]); - let hello_func = Function::new(&mut ctx, &hello_type, |_ctx, _| { + let hello_func = Function::new(&mut store, &env, &hello_type, |_ctx, _| { Err(RuntimeError::new("test 123")) }); let instance = Instance::new( - &mut ctx, + &mut store, &module, &imports! { "" => { @@ -35,7 +35,7 @@ fn test_trap_return(config: crate::Config) -> Result<()> { .expect("expected function export"); let e = run_func - .call(&mut ctx, &[]) + .call(&mut store, &[]) .err() .expect("error calling function"); @@ -47,7 +47,7 @@ fn test_trap_return(config: crate::Config) -> Result<()> { #[cfg_attr(target_env = "musl", ignore)] #[compiler_test(traps)] fn test_trap_trace(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module $hello_mod (func (export "run") (call $hello)) @@ -55,16 +55,16 @@ fn test_trap_trace(config: crate::Config) -> Result<()> { ) "#; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let module = Module::new(&store, wat)?; - let instance = Instance::new(&mut ctx, &module, &imports! {})?; + let instance = Instance::new(&mut store, &module, &imports! {})?; let run_func = instance .exports .get_function("run") .expect("expected function export"); let e = run_func - .call(&mut ctx, &[]) + .call(&mut store, &[]) .err() .expect("error calling function"); @@ -87,7 +87,7 @@ fn test_trap_trace(config: crate::Config) -> Result<()> { #[compiler_test(traps)] fn test_trap_trace_cb(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module $hello_mod (import "" "throw" (func $throw)) @@ -96,15 +96,15 @@ fn test_trap_trace_cb(config: crate::Config) -> Result<()> { ) "#; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let fn_type = FunctionType::new(vec![], vec![]); - let fn_func = Function::new(&mut ctx, &fn_type, |_ctx, _| { + let fn_func = Function::new(&mut store, &env, &fn_type, |_ctx, _| { Err(RuntimeError::new("cb throw")) }); let module = Module::new(&store, wat)?; let instance = Instance::new( - &mut ctx, + &mut store, &module, &imports! { "" => { @@ -118,7 +118,7 @@ fn test_trap_trace_cb(config: crate::Config) -> Result<()> { .expect("expected function export"); let e = run_func - .call(&mut ctx, &[]) + .call(&mut store, &[]) .err() .expect("error calling function"); @@ -138,7 +138,7 @@ fn test_trap_trace_cb(config: crate::Config) -> Result<()> { #[cfg_attr(target_env = "musl", ignore)] #[compiler_test(traps)] fn test_trap_stack_overflow(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module $rec_mod (func $run (export "run") (call $run)) @@ -146,15 +146,15 @@ fn test_trap_stack_overflow(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, wat)?; - let mut ctx = WasmerContext::new(&store, ()); - let instance = Instance::new(&mut ctx, &module, &imports! {})?; + let mut env = FunctionEnv::new(&mut store, ()); + let instance = Instance::new(&mut store, &module, &imports! {})?; let run_func = instance .exports .get_function("run") .expect("expected function export"); let e = run_func - .call(&mut ctx, &[]) + .call(&mut store, &[]) .err() .expect("error calling function"); @@ -169,7 +169,7 @@ fn test_trap_stack_overflow(config: crate::Config) -> Result<()> { #[cfg_attr(target_env = "musl", ignore)] #[compiler_test(traps)] fn trap_display_pretty(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module $m (func $die unreachable) @@ -180,15 +180,15 @@ fn trap_display_pretty(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, wat)?; - let mut ctx = WasmerContext::new(&store, ()); - let instance = Instance::new(&mut ctx, &module, &imports! {})?; + let mut env = FunctionEnv::new(&mut store, ()); + let instance = Instance::new(&mut store, &module, &imports! {})?; let run_func = instance .exports .get_function("bar") .expect("expected function export"); let e = run_func - .call(&mut ctx, &[]) + .call(&mut store, &[]) .err() .expect("error calling function"); assert_eq!( @@ -206,7 +206,7 @@ RuntimeError: unreachable #[cfg_attr(target_env = "musl", ignore)] #[compiler_test(traps)] fn trap_display_multi_module(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module $a (func $die unreachable) @@ -217,8 +217,8 @@ fn trap_display_multi_module(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, wat)?; - let mut ctx = WasmerContext::new(&store, ()); - let instance = Instance::new(&mut ctx, &module, &imports! {})?; + let mut env = FunctionEnv::new(&mut store, ()); + let instance = Instance::new(&mut store, &module, &imports! {})?; let bar = instance.exports.get_function("bar")?.clone(); let wat = r#" @@ -230,7 +230,7 @@ fn trap_display_multi_module(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, wat)?; let instance = Instance::new( - &mut ctx, + &mut store, &module, &imports! { "" => { @@ -244,7 +244,7 @@ fn trap_display_multi_module(config: crate::Config) -> Result<()> { .expect("expected function export"); let e = bar2 - .call(&mut ctx, &[]) + .call(&mut store, &[]) .err() .expect("error calling function"); assert_eq!( @@ -263,7 +263,7 @@ RuntimeError: unreachable #[compiler_test(traps)] fn trap_start_function_import(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let binary = r#" (module $a (import "" "" (func $foo)) @@ -272,13 +272,13 @@ fn trap_start_function_import(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, &binary)?; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let sig = FunctionType::new(vec![], vec![]); - let func = Function::new(&mut ctx, &sig, |_ctx, _| { + let func = Function::new(&mut store, &env, &sig, |_ctx, _| { Err(RuntimeError::new("user trap")) }); let err = Instance::new( - &mut ctx, + &mut store, &module, &imports! { "" => { @@ -290,7 +290,7 @@ fn trap_start_function_import(config: crate::Config) -> Result<()> { .unwrap(); match err { InstantiationError::Link(_) - | InstantiationError::BadContext + | InstantiationError::DifferentStores | InstantiationError::CpuFeature(_) => { panic!("It should be a start error") } @@ -304,7 +304,7 @@ fn trap_start_function_import(config: crate::Config) -> Result<()> { #[compiler_test(traps)] fn rust_panic_import(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let binary = r#" (module $a (import "" "foo" (func $foo)) @@ -315,14 +315,14 @@ fn rust_panic_import(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, &binary)?; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let sig = FunctionType::new(vec![], vec![]); - let func = Function::new(&mut ctx, &sig, |_ctx, _| panic!("this is a panic")); - let f0 = Function::new_native(&mut ctx, |_ctx: ContextMut<_>| { + let func = Function::new(&mut store, &env, &sig, |_ctx, _| panic!("this is a panic")); + let f0 = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<_>| { panic!("this is another panic") }); let instance = Instance::new( - &mut ctx, + &mut store, &module, &imports! { "" => { @@ -333,7 +333,7 @@ fn rust_panic_import(config: crate::Config) -> Result<()> { )?; let func = instance.exports.get_function("foo")?.clone(); let err = panic::catch_unwind(AssertUnwindSafe(|| { - drop(func.call(&mut ctx, &[])); + drop(func.call(&mut store, &[])); })) .unwrap_err(); assert_eq!(err.downcast_ref::<&'static str>(), Some(&"this is a panic")); @@ -354,7 +354,7 @@ fn rust_panic_import(config: crate::Config) -> Result<()> { #[compiler_test(traps)] fn rust_panic_start_function(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let binary = r#" (module $a (import "" "" (func $foo)) @@ -363,12 +363,12 @@ fn rust_panic_start_function(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, &binary)?; - let mut ctx = WasmerContext::new(&store, ()); + let mut env = FunctionEnv::new(&mut store, ()); let sig = FunctionType::new(vec![], vec![]); - let func = Function::new(&mut ctx, &sig, |_ctx, _| panic!("this is a panic")); + let func = Function::new(&mut store, &env, &sig, |_ctx, _| panic!("this is a panic")); let err = panic::catch_unwind(AssertUnwindSafe(|| { drop(Instance::new( - &mut ctx, + &mut store, &module, &imports! { "" => { @@ -380,12 +380,12 @@ fn rust_panic_start_function(config: crate::Config) -> Result<()> { .unwrap_err(); assert_eq!(err.downcast_ref::<&'static str>(), Some(&"this is a panic")); - let func = Function::new_native(&mut ctx, |_ctx: ContextMut<_>| { + let func = Function::new_native(&mut store, &env, |_ctx: FunctionEnvMut<_>| { panic!("this is another panic") }); let err = panic::catch_unwind(AssertUnwindSafe(|| { drop(Instance::new( - &mut ctx, + &mut store, &module, &imports! { "" => { @@ -404,7 +404,7 @@ fn rust_panic_start_function(config: crate::Config) -> Result<()> { #[compiler_test(traps)] fn mismatched_arguments(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let binary = r#" (module $a (func (export "foo") (param i32)) @@ -412,21 +412,21 @@ fn mismatched_arguments(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, &binary)?; - let mut ctx = WasmerContext::new(&store, ()); - let instance = Instance::new(&mut ctx, &module, &imports! {})?; + let mut env = FunctionEnv::new(&mut store, ()); + let instance = Instance::new(&mut store, &module, &imports! {})?; let func: &Function = instance.exports.get("foo")?; assert_eq!( - func.call(&mut ctx, &[]).unwrap_err().message(), + func.call(&mut store, &[]).unwrap_err().message(), "Parameters of type [] did not match signature [I32] -> []" ); assert_eq!( - func.call(&mut ctx, &[Value::F32(0.0)]) + func.call(&mut store, &[Value::F32(0.0)]) .unwrap_err() .message(), "Parameters of type [F32] did not match signature [I32] -> []", ); assert_eq!( - func.call(&mut ctx, &[Value::I32(0), Value::I32(1)]) + func.call(&mut store, &[Value::I32(0), Value::I32(1)]) .unwrap_err() .message(), "Parameters of type [I32, I32] did not match signature [I32] -> []" @@ -437,7 +437,7 @@ fn mismatched_arguments(config: crate::Config) -> Result<()> { #[cfg_attr(target_env = "musl", ignore)] #[compiler_test(traps)] fn call_signature_mismatch(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let binary = r#" (module $a (func $foo @@ -452,8 +452,8 @@ fn call_signature_mismatch(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, &binary)?; - let mut ctx = WasmerContext::new(&store, ()); - let err = Instance::new(&mut ctx, &module, &imports! {}) + let mut env = FunctionEnv::new(&mut store, ()); + let err = Instance::new(&mut store, &module, &imports! {}) .err() .expect("expected error"); assert_eq!( @@ -469,7 +469,7 @@ RuntimeError: indirect call type mismatch #[compiler_test(traps)] #[cfg_attr(target_env = "musl", ignore)] fn start_trap_pretty(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let wat = r#" (module $m (func $die unreachable) @@ -481,8 +481,8 @@ fn start_trap_pretty(config: crate::Config) -> Result<()> { "#; let module = Module::new(&store, wat)?; - let mut ctx = WasmerContext::new(&store, ()); - let err = Instance::new(&mut ctx, &module, &imports! {}) + let mut env = FunctionEnv::new(&mut store, ()); + let err = Instance::new(&mut store, &module, &imports! {}) .err() .expect("expected error"); @@ -501,18 +501,18 @@ RuntimeError: unreachable #[compiler_test(traps)] fn present_after_module_drop(config: crate::Config) -> Result<()> { - let store = config.store(); + let mut store = config.store(); let module = Module::new(&store, r#"(func (export "foo") unreachable)"#)?; - let mut ctx = WasmerContext::new(&store, ()); - let instance = Instance::new(&mut ctx, &module, &imports! {})?; + let mut env = FunctionEnv::new(&mut store, ()); + let instance = Instance::new(&mut store, &module, &imports! {})?; let func: Function = instance.exports.get_function("foo")?.clone(); println!("asserting before we drop modules"); - assert_trap(func.call(&mut ctx, &[]).unwrap_err()); + assert_trap(func.call(&mut store, &[]).unwrap_err()); drop((instance, module)); println!("asserting after drop"); - assert_trap(func.call(&mut ctx, &[]).unwrap_err()); + assert_trap(func.call(&mut store, &[]).unwrap_err()); return Ok(()); fn assert_trap(t: RuntimeError) { diff --git a/tests/compilers/wasi.rs b/tests/compilers/wasi.rs index be339e3db78..ffe37657c3e 100644 --- a/tests/compilers/wasi.rs +++ b/tests/compilers/wasi.rs @@ -23,7 +23,7 @@ pub fn run_wasi( filesystem_kind: WasiFileSystemKind, ) -> anyhow::Result<()> { println!("Running wasi wast `{}`", wast_path); - let store = config.store(); + let mut store = config.store(); let source = { let mut out = String::new(); @@ -34,7 +34,7 @@ pub fn run_wasi( let tokens = WasiTest::lex_string(&source)?; let wasi_test = WasiTest::parse_tokens(&tokens)?; - let succeeded = wasi_test.run(&store, base_dir, filesystem_kind)?; + let succeeded = wasi_test.run(&mut store, base_dir, filesystem_kind)?; assert!(succeeded); diff --git a/tests/compilers/wast.rs b/tests/compilers/wast.rs index 0910c279867..0f6e3f36cb9 100644 --- a/tests/compilers/wast.rs +++ b/tests/compilers/wast.rs @@ -1,4 +1,4 @@ -use ::wasmer::{Context, Features}; +use ::wasmer::Features; use std::path::Path; use wasmer_wast::Wast; @@ -34,9 +34,8 @@ pub fn run_wast(mut config: crate::Config, wast_path: &str) -> anyhow::Result<() config.set_features(features); config.set_nan_canonicalization(try_nan_canonicalization); - let store = config.store(); - let context = Context::new(&store, ()); - let mut wast = Wast::new_with_spectest(context); + let mut store = config.store(); + let mut wast = Wast::new_with_spectest(store); // `bulk-memory-operations/bulk.wast` checks for a message that // specifies which element is uninitialized, but our traps don't // shepherd that information out. diff --git a/tests/lib/wast/src/spectest.rs b/tests/lib/wast/src/spectest.rs index 36d0d848a36..389a5c4e16c 100644 --- a/tests/lib/wast/src/spectest.rs +++ b/tests/lib/wast/src/spectest.rs @@ -2,39 +2,41 @@ use wasmer::*; /// Return an instance implementing the "spectest" interface used in the /// spec testsuite. -pub fn spectest_importobject(context: &mut Context<()>) -> Imports { - let print = Function::new_native(context, |_: ContextMut<'_, ()>| {}); - let print_i32 = Function::new_native(context, |_: ContextMut<'_, ()>, val: i32| { +pub fn spectest_importobject(store: &mut Store, context: &FunctionEnv<()>) -> Imports { + let print = Function::new_native(store, context, |_: FunctionEnvMut<()>| {}); + let print_i32 = Function::new_native(store, context, |_: FunctionEnvMut<()>, val: i32| { println!("{}: i32", val) }); - let print_i64 = Function::new_native(context, |_: ContextMut<'_, ()>, val: i64| { + let print_i64 = Function::new_native(store, context, |_: FunctionEnvMut<()>, val: i64| { println!("{}: i64", val) }); - let print_f32 = Function::new_native(context, |_: ContextMut<'_, ()>, val: f32| { + let print_f32 = Function::new_native(store, context, |_: FunctionEnvMut<()>, val: f32| { println!("{}: f32", val) }); - let print_f64 = Function::new_native(context, |_: ContextMut<'_, ()>, val: f64| { + let print_f64 = Function::new_native(store, context, |_: FunctionEnvMut<()>, val: f64| { println!("{}: f64", val) }); - let print_i32_f32 = Function::new_native(context, |_: ContextMut<'_, ()>, i: i32, f: f32| { - println!("{}: i32", i); - println!("{}: f32", f); - }); - let print_f64_f64 = Function::new_native(context, |_: ContextMut<'_, ()>, f1: f64, f2: f64| { - println!("{}: f64", f1); - println!("{}: f64", f2); - }); + let print_i32_f32 = + Function::new_native(store, context, |_: FunctionEnvMut<()>, i: i32, f: f32| { + println!("{}: i32", i); + println!("{}: f32", f); + }); + let print_f64_f64 = + Function::new_native(store, context, |_: FunctionEnvMut<()>, f1: f64, f2: f64| { + println!("{}: f64", f1); + println!("{}: f64", f2); + }); - let global_i32 = Global::new(context, Value::I32(666)); - let global_i64 = Global::new(context, Value::I64(666)); - let global_f32 = Global::new(context, Value::F32(f32::from_bits(0x4426_8000))); - let global_f64 = Global::new(context, Value::F64(f64::from_bits(0x4084_d000_0000_0000))); + let global_i32 = Global::new(store, Value::I32(666)); + let global_i64 = Global::new(store, Value::I64(666)); + let global_f32 = Global::new(store, Value::F32(f32::from_bits(0x4426_8000))); + let global_f64 = Global::new(store, Value::F64(f64::from_bits(0x4084_d000_0000_0000))); let ty = TableType::new(Type::FuncRef, 10, Some(20)); - let table = Table::new(context, ty, Value::FuncRef(None)).unwrap(); + let table = Table::new(store, ty, Value::FuncRef(None)).unwrap(); let ty = MemoryType::new(1, Some(2), false); - let memory = Memory::new(context, ty).unwrap(); + let memory = Memory::new(store, ty).unwrap(); imports! { "spectest" => { diff --git a/tests/lib/wast/src/wasi_wast.rs b/tests/lib/wast/src/wasi_wast.rs index a9934ec3f14..6b2e13aac4c 100644 --- a/tests/lib/wast/src/wasi_wast.rs +++ b/tests/lib/wast/src/wasi_wast.rs @@ -3,13 +3,13 @@ use std::fs::{read_dir, File, OpenOptions, ReadDir}; use std::io::{self, Read, Seek, Write}; use std::path::{Path, PathBuf}; use std::sync::{mpsc, Arc, Mutex}; -use wasmer::Context as WasmerContext; -use wasmer::{AsContextMut, ContextMut, Imports, Instance, Module, Store}; +use wasmer::FunctionEnv; +use wasmer::{Imports, Instance, Module, Store}; use wasmer_vfs::{host_fs, mem_fs, FileSystem}; use wasmer_wasi::types::{__wasi_filesize_t, __wasi_timestamp_t}; use wasmer_wasi::{ - generate_import_object_from_ctx, get_wasi_version, FsError, Pipe, VirtualFile, WasiEnv, - WasiState, WasiVersion, + generate_import_object_from_env, get_wasi_version, FsError, Pipe, VirtualFile, WasiEnv, + WasiFunctionEnv, WasiState, WasiVersion, }; use wast::parser::{self, Parse, ParseBuffer, Parser}; @@ -70,7 +70,7 @@ impl<'a> WasiTest<'a> { /// Execute the WASI test and assert. pub fn run( &self, - store: &Store, + mut store: &mut Store, base_path: &str, filesystem_kind: WasiFileSystemKind, ) -> anyhow::Result { @@ -83,24 +83,25 @@ impl<'a> WasiTest<'a> { out }; let module = Module::new(store, &wasm_bytes)?; - let (env, _tempdirs, stdout_rx, stderr_rx) = self.create_wasi_env(filesystem_kind)?; - let mut ctx = WasmerContext::new(store, env.clone()); - let imports = self.get_imports(&mut ctx.as_context_mut(), &module)?; - let instance = Instance::new(&mut ctx, &module, &imports)?; + let (env, _tempdirs, stdout_rx, stderr_rx) = + self.create_wasi_env(store, filesystem_kind)?; + let imports = self.get_imports(store, &env.env, &module)?; + let instance = Instance::new(&mut store, &module, &imports)?; let start = instance.exports.get_function("_start")?; let memory = instance.exports.get_memory("memory")?; - ctx.data_mut().set_memory(memory.clone()); + let wasi_env = env.data_mut(&mut store); + wasi_env.set_memory(memory.clone()); if let Some(stdin) = &self.stdin { - let state = env.state(); + let state = wasi_env.state(); let mut wasi_stdin = state.stdin().unwrap().unwrap(); // Then we can write to it! write!(wasi_stdin, "{}", stdin.stream)?; } // TODO: handle errors here when the error fix gets shipped - match start.call(&mut ctx, &[]) { + match start.call(&mut store, &[]) { Ok(_) => {} Err(e) => { let stdout_str = get_stdio_output(&stdout_rx)?; @@ -132,9 +133,10 @@ impl<'a> WasiTest<'a> { #[allow(clippy::type_complexity)] fn create_wasi_env( &self, + mut store: &mut Store, filesystem_kind: WasiFileSystemKind, ) -> anyhow::Result<( - WasiEnv, + WasiFunctionEnv, Vec, mpsc::Receiver>, mpsc::Receiver>, @@ -217,7 +219,7 @@ impl<'a> WasiTest<'a> { //.env("RUST_BACKTRACE", "1") .stdout(Box::new(stdout)) .stderr(Box::new(stderr)) - .finalize()?; + .finalize(&mut store)?; Ok((out, host_temp_dirs_to_not_drop, stdout_rx, stderr_rx)) } @@ -233,11 +235,12 @@ impl<'a> WasiTest<'a> { /// [`WasiEnv`]. fn get_imports( &self, - ctx: &mut ContextMut<'_, WasiEnv>, + store: &mut Store, + ctx: &FunctionEnv, module: &Module, ) -> anyhow::Result { let version = self.get_version(module)?; - Ok(generate_import_object_from_ctx(ctx, version)) + Ok(generate_import_object_from_env(store, ctx, version)) } } diff --git a/tests/lib/wast/src/wast.rs b/tests/lib/wast/src/wast.rs index 3eb689b40b8..89fb7e08314 100644 --- a/tests/lib/wast/src/wast.rs +++ b/tests/lib/wast/src/wast.rs @@ -8,6 +8,7 @@ use wasmer::*; /// The wast test script language allows modules to be defined and actions /// to be performed on them. +#[allow(dead_code)] pub struct Wast { /// Wast files have a concept of a "current" module, which is the most /// recently defined. @@ -23,8 +24,10 @@ pub struct Wast { match_trap_messages: HashMap, /// If the current module was an allowed failure, we allow test to fail current_is_allowed_failure: bool, + /// The store in which the tests are executing. + store: Store, /// The context in which the tests are executing. - context: Context<()>, + context: FunctionEnv<()>, /// A flag indicating if Wast tests should stop as soon as one test fails. pub fail_fast: bool, /// A flag indicating that assert_trap and assert_exhaustion should be skipped. @@ -34,9 +37,10 @@ pub struct Wast { impl Wast { /// Construct a new instance of `Wast` with a given imports. - pub fn new(context: Context<()>, import_object: Imports) -> Self { + pub fn new(store: Store, context: FunctionEnv<()>, import_object: Imports) -> Self { Self { current: None, + store, context, import_object, allowed_instantiation_failures: HashSet::new(), @@ -68,9 +72,10 @@ impl Wast { } /// Construct a new instance of `Wast` with the spectests imports. - pub fn new_with_spectest(mut context: Context<()>) -> Self { - let import_object = spectest_importobject(&mut context); - Self::new(context, import_object) + pub fn new_with_spectest(mut store: Store) -> Self { + let context = FunctionEnv::new(&mut store, ()); + let import_object = spectest_importobject(&mut store, &context); + Self::new(store, context, import_object) } fn get_instance(&self, instance_name: Option<&str>) -> Result { @@ -366,7 +371,7 @@ impl Wast { } fn instantiate(&mut self, module: &[u8]) -> Result { - let module = Module::new(self.context.store(), module)?; + let module = Module::new(&self.store, module)?; let mut imports = self.import_object.clone(); for import in module.imports() { @@ -381,7 +386,7 @@ impl Wast { imports.register_namespace(module_name, instance.exports.clone()); } - let instance = Instance::new(&mut self.context, &module, &imports)?; + let instance = Instance::new(&mut self.store, &module, &imports)?; Ok(instance) } @@ -401,7 +406,7 @@ impl Wast { ) -> Result> { let instance = self.get_instance(instance_name)?; let func: &Function = instance.exports.get(field)?; - match func.call(&mut self.context, args) { + match func.call(&mut self.store, args) { Ok(result) => Ok(result.into()), Err(e) => Err(e.into()), } @@ -411,7 +416,7 @@ impl Wast { fn get(&mut self, instance_name: Option<&str>, field: &str) -> Result> { let instance = self.get_instance(instance_name)?; let global: &Global = instance.exports.get(field)?; - Ok(vec![global.get(&mut self.context)]) + Ok(vec![global.get(&mut self.store)]) } /// Translate from a `script::Value` to a `Value`. @@ -429,7 +434,7 @@ impl Wast { V128Const(x) => Value::V128(u128::from_le_bytes(x.to_le_bytes())), RefNull(wast::HeapType::Func) => Value::FuncRef(None), RefNull(wast::HeapType::Extern) => Value::null(), - RefExtern(number) => Value::ExternRef(Some(ExternRef::new(&mut self.context, *number))), + RefExtern(number) => Value::ExternRef(Some(ExternRef::new(&mut self.store, *number))), other => bail!("couldn't convert {:?} to a runtime value", other), }) } @@ -489,7 +494,7 @@ impl Wast { (Value::ExternRef(Some(_)), wast::AssertExpression::RefNull(_)) => false, (Value::ExternRef(Some(extern_ref)), wast::AssertExpression::RefExtern(num)) => { - extern_ref.downcast(&self.context) == Some(num) + extern_ref.downcast(&self.store) == Some(num) } _ => bail!( "don't know how to compare {:?} and {:?} yet",