diff --git a/examples/compiler_cranelift.rs b/examples/compiler_cranelift.rs index f19b7ce8191..8c6aff08dfa 100644 --- a/examples/compiler_cranelift.rs +++ b/examples/compiler_cranelift.rs @@ -10,7 +10,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -34,6 +34,7 @@ fn main() -> Result<(), Box> { // Create the store let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut ctx = Context::new(&store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -44,14 +45,14 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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(&[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut ctx, &[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 c62a1102064..b762443c415 100644 --- a/examples/compiler_llvm.rs +++ b/examples/compiler_llvm.rs @@ -10,7 +10,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_llvm::LLVM; @@ -34,6 +34,7 @@ fn main() -> Result<(), Box> { // Create the store let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut ctx = Context::new(&store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -44,14 +45,14 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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(&[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut ctx, &[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 39d12551c0d..2b7f87bea99 100644 --- a/examples/compiler_singlepass.rs +++ b/examples/compiler_singlepass.rs @@ -10,7 +10,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_singlepass::Singlepass; @@ -34,6 +34,7 @@ fn main() -> Result<(), Box> { // Create the store let store = Store::new_with_engine(&Universal::new(compiler).engine()); + let mut ctx = Context::new(&store, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -44,14 +45,14 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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(&[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut ctx, &[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 0206be52c2b..9e2181cfd9b 100644 --- a/examples/early_exit.rs +++ b/examples/early_exit.rs @@ -16,7 +16,9 @@ use anyhow::bail; use std::fmt; -use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, TypedFunction}; +use wasmer::{ + imports, wat2wasm, Context, ContextMut, Function, Instance, Module, Store, TypedFunction, +}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -56,13 +58,14 @@ fn main() -> anyhow::Result<()> { // 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, ()); 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() -> Result<(), ExitCode> { + fn early_exit(_ctx: ContextMut<()>) -> Result<(), ExitCode> { // This is where it happens. Err(ExitCode(1)) } @@ -70,22 +73,23 @@ fn main() -> anyhow::Result<()> { // Create an import object. let import_object = imports! { "env" => { - "early_exit" => Function::new_native(&store, early_exit), + "early_exit" => Function::new_native(&mut ctx, early_exit), } }; println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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("run")?; + let run_func: TypedFunction<(i32, i32), i32> = + instance.exports.get_typed_function(&mut ctx, "run")?; // When we call a function it can either succeed or fail. We expect it to fail. - match run_func.call(1, 7) { + match run_func.call(&mut ctx, 1, 7) { Ok(result) => { bail!( "Expected early termination with `ExitCode`, found: {}", diff --git a/examples/engine_headless.rs b/examples/engine_headless.rs index 3c0af060e68..4d84f0e38ae 100644 --- a/examples/engine_headless.rs +++ b/examples/engine_headless.rs @@ -47,6 +47,7 @@ use tempfile::NamedTempFile; use wasmer::imports; use wasmer::wat2wasm; +use wasmer::Context; use wasmer::Instance; use wasmer::Module; use wasmer::Store; @@ -106,6 +107,7 @@ fn main() -> Result<(), Box> { // We create a headless Universal engine. let engine = Universal::headless().engine(); let store = Store::new_with_engine(&engine); + let mut ctx = Context::new(&store, ()); println!("Deserializing module..."); // Here we go. @@ -125,12 +127,12 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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(&[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut ctx, &[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 530449c0df2..819879669cb 100644 --- a/examples/engine_universal.rs +++ b/examples/engine_universal.rs @@ -18,7 +18,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -53,6 +53,7 @@ fn main() -> Result<(), Box> { // Create a store, that holds the engine. let store = Store::new_with_engine(&engine); + let mut ctx = Context::new(&store, ()); println!("Compiling module..."); // Here we go. @@ -72,12 +73,12 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // And here we go again. Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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(&[Value::I32(1), Value::I32(2)])?; + let results = sum.call(&mut ctx, &[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 a9b2d93ed65..cf701dd1fb7 100644 --- a/examples/errors.rs +++ b/examples/errors.rs @@ -13,7 +13,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Store}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -40,6 +40,7 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -50,7 +51,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // Here we go. // @@ -59,14 +60,14 @@ fn main() -> Result<(), Box> { // produce an error. // // Let's get it. - let div_by_zero = instance + let div_by_zero: TypedFunction<(), i32> = instance .exports .get_function("div_by_zero")? - .native::<(), i32>()?; + .native(&mut ctx)?; println!("Calling `div_by_zero` function..."); // Let's call the `div_by_zero` exported function. - let result = div_by_zero.call(); + let result = div_by_zero.call(&mut ctx); // 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 bf873061799..4ab86beac7f 100644 --- a/examples/exports_function.rs +++ b/examples/exports_function.rs @@ -17,7 +17,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -41,6 +41,7 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -51,7 +52,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // Here we go. // @@ -73,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(&args)?; + let result = sum.call(&mut ctx, &args)?; println!("Results: {:?}", result); assert_eq!(result.to_vec(), vec![Value::I32(3)]); @@ -86,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 = sum.native::<(i32, i32), i32>()?; + let sum_native: TypedFunction<(i32, i32), i32> = sum.native(&mut ctx)?; 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(3, 4)?; + let result = sum_native.call(&mut ctx, 3, 4)?; println!("Results: {:?}", result); assert_eq!(result, 7); diff --git a/examples/exports_global.rs b/examples/exports_global.rs index 3aaa1035783..19687fb3209 100644 --- a/examples/exports_global.rs +++ b/examples/exports_global.rs @@ -15,7 +15,9 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Mutability, Store, Type, Value}; +use wasmer::{ + imports, wat2wasm, Context, Instance, Module, Mutability, Store, Type, TypedFunction, Value, +}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -39,6 +41,7 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -49,7 +52,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // Here we go. // @@ -70,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(); - let some_type = some.ty(); + let one_type = one.ty(&mut ctx); + let some_type = some.ty(&mut ctx); println!("`one` type: {:?} {:?}", one_type.mutability, one_type.ty); assert_eq!(one_type.mutability, Mutability::Const); @@ -88,13 +91,11 @@ fn main() -> Result<(), Box> { // // We will use an exported function for the `one` global // and the Global API for `some`. - let get_one = instance - .exports - .get_function("get_one")? - .native::<(), f32>()?; + let get_one: TypedFunction<(), f32> = + instance.exports.get_function("get_one")?.native(&mut ctx)?; - let one_value = get_one.call()?; - let some_value = some.get(); + let one_value = get_one.call(&mut ctx)?; + let some_value = some.get(&mut ctx); println!("`one` value: {:?}", one_value); assert_eq!(one_value, 1.0); @@ -105,13 +106,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(Value::F32(42.0)); + let result = one.set(&mut ctx, Value::F32(42.0)); assert_eq!( result.expect_err("Expected an error").message(), "Attempted to set an immutable global" ); - let one_result = one.get(); + let one_result = one.get(&mut ctx); println!("`one` value after `set`: {:?}", one_result); assert_eq!(one_result, Value::F32(1.0)); @@ -120,17 +121,17 @@ fn main() -> Result<(), Box> { // 2. Using the Global API directly. // // We will use both for the `some` global. - let set_some = instance + let set_some: TypedFunction = instance .exports .get_function("set_some")? - .native::()?; - set_some.call(21.0)?; - let some_result = some.get(); + .native(&mut ctx)?; + set_some.call(&mut ctx, 21.0)?; + let some_result = some.get(&mut ctx); println!("`some` value after `set_some`: {:?}", some_result); assert_eq!(some_result, Value::F32(21.0)); - some.set(Value::F32(42.0))?; - let some_result = some.get(); + some.set(&mut ctx, Value::F32(42.0))?; + let some_result = some.get(&mut ctx); 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 0f7cb533a0e..f8f5b29feb7 100644 --- a/examples/exports_memory.rs +++ b/examples/exports_memory.rs @@ -11,7 +11,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Store, WasmPtr}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction, WasmPtr}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -38,6 +38,7 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -48,11 +49,10 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; - let load = instance - .exports - .get_typed_function::<(), (WasmPtr, i32)>("load")?; + let load: TypedFunction<(), (WasmPtr, i32)> = + instance.exports.get_typed_function(&mut ctx, "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()); - println!("Memory size (bytes) {:?}", memory.data_size()); + println!("Memory size (pages) {:?}", memory.size(&mut ctx)); + println!("Memory size (bytes) {:?}", memory.data_size(&mut ctx)); // 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()?; + let (ptr, length) = load.call(&mut ctx)?; println!("String offset: {:?}", ptr.offset()); println!("String length: {:?}", length); @@ -80,7 +80,9 @@ 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(memory, length as u32).unwrap(); + let str = ptr + .read_utf8_string(&mut ctx, memory, length as u32) + .unwrap(); println!("Memory contents: {:?}", str); // What about changing the contents of the memory with a more @@ -89,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(memory, new_str.len() as u32).unwrap(); + let values = ptr.slice(&mut ctx, memory, new_str.len() as u32).unwrap(); for i in 0..new_str.len() { values.index(i as u64).write(new_str[i]).unwrap(); } @@ -101,7 +103,9 @@ fn main() -> Result<(), Box> { // before. println!("New string length: {:?}", new_str.len()); - let str = ptr.read_utf8_string(memory, new_str.len() as u32).unwrap(); + let str = ptr + .read_utf8_string(&mut ctx, memory, new_str.len() as u32) + .unwrap(); println!("New memory contents: {:?}", str); // Much better, don't you think? diff --git a/examples/features.rs b/examples/features.rs index f60d24f17d1..d4f8058ce60 100644 --- a/examples/features.rs +++ b/examples/features.rs @@ -10,7 +10,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Features, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Context, Features, Instance, Module, Store, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -40,15 +40,16 @@ fn main() -> anyhow::Result<()> { // 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 module = Module::new(&store, wasm_bytes)?; // Finally, let's instantiate the module, and execute something // :-). let import_object = imports! {}; - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; let swap = instance.exports.get_function("swap")?; - let results = swap.call(&[Value::I32(1), Value::I64(2)])?; + let results = swap.call(&mut ctx, &[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 21b16c9f367..39ea01df73b 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -58,7 +58,7 @@ fn main() -> anyhow::Result<()> { // 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: ContextMut<'_, ()>) { println!("Hello, world!") } diff --git a/examples/imports_exports.rs b/examples/imports_exports.rs index 2cde8af885b..fc07e22a1eb 100644 --- a/examples/imports_exports.rs +++ b/examples/imports_exports.rs @@ -16,8 +16,8 @@ //! Ready? use wasmer::{ - imports, wat2wasm, Function, FunctionType, Global, Instance, Memory, Module, Store, Table, - Type, Value, + imports, wat2wasm, Context, Function, FunctionType, Global, Instance, Memory, Module, Store, + Table, Type, Value, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -45,6 +45,7 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -59,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(&store, &host_function_signature, |_args| { + let host_function = Function::new(&mut ctx, &host_function_signature, |_ctx, _args| { Ok(vec![Value::I32(42)]) }); println!("Creating the imported global..."); - let host_global = Global::new(&store, Value::I32(42)); + let host_global = Global::new(&mut ctx, Value::I32(42)); // Create an import object. // @@ -89,7 +90,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // Here we go. // @@ -102,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()); + println!("Got exported function of type: {:?}", function.ty(&mut ctx)); println!("Getting the exported global..."); let global = instance.exports.get::("guest_global")?; - println!("Got exported global of type: {:?}", global.ty()); + println!("Got exported global of type: {:?}", global.ty(&mut ctx)); println!("Getting the exported memory..."); let memory = instance.exports.get::("guest_memory")?; - println!("Got exported memory of type: {:?}", memory.ty()); + println!("Got exported memory of type: {:?}", memory.ty(&mut ctx)); println!("Getting the exported table..."); let table = instance.exports.get::("guest_table")?; - println!("Got exported table of type: {:?}", table.ty()); + println!("Got exported table of type: {:?}", table.ty(&mut ctx)); Ok(()) } diff --git a/examples/imports_function.rs b/examples/imports_function.rs index 919debec005..ca1bdebf39d 100644 --- a/examples/imports_function.rs +++ b/examples/imports_function.rs @@ -17,7 +17,10 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Function, FunctionType, Instance, Module, Store, Type, Value}; +use wasmer::{ + imports, wat2wasm, Context, ContextMut, Function, FunctionType, Instance, Module, Store, Type, + TypedFunction, Value, +}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -43,6 +46,7 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -50,7 +54,7 @@ fn main() -> Result<(), Box> { // Create the functions let multiply_dynamic_signature = FunctionType::new(vec![Type::I32], vec![Type::I32]); - let multiply_dynamic = Function::new(&store, &multiply_dynamic_signature, |args| { + let multiply_dynamic = Function::new(&mut ctx, &multiply_dynamic_signature, |_ctx, args| { println!("Calling `multiply_dynamic`..."); let result = args[0].unwrap_i32() * 2; @@ -60,7 +64,7 @@ fn main() -> Result<(), Box> { Ok(vec![Value::I32(result)]) }); - fn multiply(a: i32) -> i32 { + fn multiply(_ctx: ContextMut<()>, a: i32) -> i32 { println!("Calling `multiply_native`..."); let result = a * 3; @@ -68,7 +72,7 @@ fn main() -> Result<(), Box> { result } - let multiply_native = Function::new_native(&store, multiply); + let multiply_native = Function::new_native(&mut ctx, multiply); // Create an import object. let import_object = imports! { @@ -80,20 +84,18 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // Here we go. // // The Wasm module exports a function called `sum`. Let's get it. - let sum = instance - .exports - .get_function("sum")? - .native::<(i32, i32), i32>()?; + let sum: TypedFunction<(i32, i32), i32> = + instance.exports.get_function("sum")?.native(&mut ctx)?; println!("Calling `sum` function..."); // Let's call the `sum` exported function. It will call each // of the imported functions. - let result = sum.call(1, 2)?; + let result = sum.call(&mut ctx, 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 b1b534e033f..9f0fcafda96 100644 --- a/examples/imports_function_env.rs +++ b/examples/imports_function_env.rs @@ -20,7 +20,9 @@ //! Ready? use std::sync::{Arc, Mutex}; -use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, WasmerEnv}; +use wasmer::{ + imports, wat2wasm, Context, ContextMut, Function, Instance, Module, Store, TypedFunction, +}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -63,47 +65,54 @@ 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 functions. + // to our imported functionsvia the Context. // // 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 - // implement the `Sized` trait) and that it implement the `WasmerEnv` trait. - // We derive a default implementation of `WasmerEnv` here. - #[derive(WasmerEnv, Clone)] + // implement the `Sized` trait). + // The Env is then accessed using `data()` or `data_mut()` method. + #[derive(Clone)] struct Env { counter: Arc>, } // Create the functions - fn get_counter(env: &Env) -> i32 { - *env.counter.lock().unwrap() + fn get_counter(ctx: ContextMut) -> i32 { + *ctx.data().counter.lock().unwrap() } - fn add_to_counter(env: &Env, add: i32) -> i32 { - let mut counter_ref = env.counter.lock().unwrap(); + fn add_to_counter(mut ctx: ContextMut, add: i32) -> i32 { + let mut counter_ref = ctx.data_mut().counter.lock().unwrap(); *counter_ref += add; *counter_ref } + let mut ctx = Context::new( + &store, + Env { + counter: shared_counter.clone(), + }, + ); + // Create an import object. let import_object = imports! { "env" => { - "get_counter" => Function::new_native_with_env(&store, Env { counter: shared_counter.clone() }, get_counter), - "add_to_counter" => Function::new_native_with_env(&store, Env { counter: shared_counter.clone() }, add_to_counter), + "get_counter" => Function::new_native(&mut ctx, get_counter), + "add_to_counter" => Function::new_native(&mut ctx, add_to_counter), } }; println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // Here we go. // // The Wasm module exports a function called `increment_counter_loop`. Let's get it. - let increment_counter_loop = instance + let increment_counter_loop: TypedFunction = instance .exports .get_function("increment_counter_loop")? - .native::()?; + .native(&mut ctx)?; let counter_value: i32 = *shared_counter.lock().unwrap(); println!("Initial ounter value: {:?}", counter_value); @@ -112,7 +121,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(5)?; + let result = increment_counter_loop.call(&mut ctx, 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 af91acf83e0..7e6eaaddb5f 100644 --- a/examples/imports_global.rs +++ b/examples/imports_global.rs @@ -15,7 +15,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Global, Instance, Module, Store, Value}; +use wasmer::{imports, wat2wasm, Context, Global, Instance, Module, Store, TypedFunction, Value}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -39,14 +39,15 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. let module = Module::new(&store, wasm_bytes)?; // Create the globals - let some = Global::new(&store, Value::F32(1.0)); - let other = Global::new_mut(&store, Value::F32(2.0)); + let some = Global::new(&mut ctx, Value::F32(1.0)); + let other = Global::new_mut(&mut ctx, Value::F32(2.0)); // Create an import object. // We add the two required globals in the `env` namespace. @@ -59,57 +60,57 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // Here we go. // // The Wasm module only imports some globals. We'll have to interact // with them either using the Global API or exported functions. - let get_some = instance + let get_some: TypedFunction<(), f32> = instance .exports .get_function("get_some")? - .native::<(), f32>()?; - let get_other = instance + .native(&mut ctx)?; + let get_other: TypedFunction<(), f32> = instance .exports .get_function("get_other")? - .native::<(), f32>()?; + .native(&mut ctx)?; - let some_result = get_some.call()?; - let other_result = get_other.call()?; + let some_result = get_some.call(&mut ctx)?; + let other_result = get_other.call(&mut ctx)?; println!("some value (via `get_some`): {:?}", some_result); - println!("some value (via Global API): {:?}", some.get()); + println!("some value (via Global API): {:?}", some.get(&mut ctx)); println!("other value (via `get_other`): {:?}", other_result); - println!("other value (via Global API): {:?}", other.get()); + println!("other value (via Global API): {:?}", other.get(&mut ctx)); - assert_eq!(some_result, some.get().f32().unwrap()); - assert_eq!(other_result, other.get().f32().unwrap()); + assert_eq!(some_result, some.get(&mut ctx).f32().unwrap()); + assert_eq!(other_result, other.get(&mut ctx).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(Value::F32(42.0)); + let result = some.set(&mut ctx, Value::F32(42.0)); assert_eq!( result.expect_err("Expected an error").message(), "Attempted to set an immutable global" ); - other.set(Value::F32(21.0))?; - let other_result = other.get(); + other.set(&mut ctx, Value::F32(21.0))?; + let other_result = other.get(&mut ctx); println!("other value after `set`: {:?}", other_result); assert_eq!(other_result, Value::F32(21.0)); println!("Altering global values through exported functions..."); // Changes made to global through exported functions will // be reflected on the host side. - let set_other = instance + let set_other: TypedFunction = instance .exports .get_function("set_other")? - .native::()?; - set_other.call(42.0)?; + .native(&mut ctx)?; + set_other.call(&mut ctx, 42.0)?; - println!("other value (via Global API): {:?}", other.get()); - assert_eq!(other.get(), Value::F32(42.0)); + println!("other value (via Global API): {:?}", other.get(&mut ctx)); + assert_eq!(other.get(&mut ctx), Value::F32(42.0)); Ok(()) } diff --git a/examples/instance.rs b/examples/instance.rs index 66404032e9b..5e8a9de09ac 100644 --- a/examples/instance.rs +++ b/examples/instance.rs @@ -14,7 +14,7 @@ //! //! Ready? -use wasmer::{imports, wat2wasm, Instance, Module, Store}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -40,6 +40,7 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -50,7 +51,7 @@ fn main() -> Result<(), Box> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // We now have an instance ready to be used. // @@ -60,13 +61,11 @@ 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 = instance - .exports - .get_function("add_one")? - .native::()?; + let add_one: TypedFunction = + instance.exports.get_function("add_one")?.native(&mut ctx)?; println!("Calling `add_one` function..."); - let result = add_one.call(1)?; + let result = add_one.call(&mut ctx, 1)?; println!("Results of `add_one`: {:?}", result); assert_eq!(result, 2); diff --git a/examples/memory.rs b/examples/memory.rs index 72b29c892f0..66fa88f8e77 100644 --- a/examples/memory.rs +++ b/examples/memory.rs @@ -15,7 +15,7 @@ //! Ready? use std::mem; -use wasmer::{imports, wat2wasm, Bytes, Instance, Module, Pages, Store, TypedFunction}; +use wasmer::{imports, wat2wasm, Bytes, Context, Instance, Module, Pages, Store, TypedFunction}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -58,6 +58,7 @@ fn main() -> anyhow::Result<()> { // 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -68,14 +69,17 @@ fn main() -> anyhow::Result<()> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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("mem_size")?; - let get_at: TypedFunction = instance.exports.get_typed_function("get_at")?; - let set_at: TypedFunction<(i32, i32), ()> = instance.exports.get_typed_function("set_at")?; + let mem_size: TypedFunction<(), i32> = + instance.exports.get_typed_function(&mut ctx, "mem_size")?; + let get_at: TypedFunction = + instance.exports.get_typed_function(&mut ctx, "get_at")?; + let set_at: TypedFunction<(i32, i32), ()> = + instance.exports.get_typed_function(&mut ctx, "set_at")?; let memory = instance.exports.get_memory("memory")?; // We now have an instance ready to be used. @@ -89,15 +93,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(), Pages::from(1)); - assert_eq!(memory.size().bytes(), Bytes::from(65536 as usize)); - assert_eq!(memory.data_size(), 65536); + 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); // 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()?; + let result = mem_size.call(&mut ctx)?; println!("Memory size: {:?}", result); - assert_eq!(Pages::from(result as u32), memory.size()); + assert_eq!(Pages::from(result as u32), memory.size(&mut ctx)); // Now that we know the size of our memory, it's time to see how wa // can change this. @@ -106,9 +110,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(2)?; - assert_eq!(memory.size(), Pages::from(3)); - assert_eq!(memory.data_size(), 65536 * 3); + memory.grow(&mut ctx, 2)?; + assert_eq!(memory.size(&mut ctx), Pages::from(3)); + assert_eq!(memory.data_size(&mut ctx), 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. @@ -118,9 +122,9 @@ fn main() -> anyhow::Result<()> { // addresses to write and read a value. let mem_addr = 0x2220; let val = 0xFEFEFFE; - set_at.call(mem_addr, val)?; + set_at.call(&mut ctx, mem_addr, val)?; - let result = get_at.call(mem_addr)?; + let result = get_at.call(&mut ctx, mem_addr)?; println!("Value at {:#x?}: {:?}", mem_addr, result); assert_eq!(result, val); @@ -129,9 +133,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(mem_addr, val)?; + set_at.call(&mut ctx, mem_addr, val)?; - let result = get_at.call(mem_addr)?; + let result = get_at.call(&mut ctx, mem_addr)?; println!("Value at {:#x?}: {:?}", mem_addr, result); assert_eq!(result, val); diff --git a/examples/metering.rs b/examples/metering.rs index 27d7248409f..613e2cab446 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, Instance, Module, Store}; +use wasmer::{imports, wat2wasm, Context, Instance, Module, Store, TypedFunction}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; use wasmer_middlewares::{ @@ -71,6 +71,7 @@ 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, ()); println!("Compiling module..."); // Let's compile the Wasm module. @@ -81,19 +82,17 @@ fn main() -> anyhow::Result<()> { println!("Instantiating module..."); // Let's instantiate the Wasm module. - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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 = instance - .exports - .get_function("add_one")? - .native::()?; + let add_one: TypedFunction = + instance.exports.get_function("add_one")?.native(&mut ctx)?; println!("Calling `add_one` function once..."); - add_one.call(1)?; + add_one.call(&mut ctx, 1)?; // As you can see here, after the first call we have 6 remaining points. // @@ -101,7 +100,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(&instance); + let remaining_points_after_first_call = get_remaining_points(&mut ctx, &instance); assert_eq!( remaining_points_after_first_call, MeteringPoints::Remaining(6) @@ -113,11 +112,11 @@ fn main() -> anyhow::Result<()> { ); println!("Calling `add_one` function twice..."); - add_one.call(1)?; + add_one.call(&mut ctx, 1)?; // We spent 4 more points with the second call. // We have 2 remaining points. - let remaining_points_after_second_call = get_remaining_points(&instance); + let remaining_points_after_second_call = get_remaining_points(&mut ctx, &instance); assert_eq!( remaining_points_after_second_call, MeteringPoints::Remaining(2) @@ -132,7 +131,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(1) { + match add_one.call(&mut ctx, 1) { Ok(result) => { bail!( "Expected failure while calling `add_one`, found: {}", @@ -143,7 +142,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(&instance); + let remaining_points = get_remaining_points(&mut ctx, &instance); match remaining_points { MeteringPoints::Remaining(..) => { @@ -157,9 +156,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(&instance, new_limit); + set_remaining_points(&mut ctx, &instance, new_limit); - let remaining_points = get_remaining_points(&instance); + let remaining_points = get_remaining_points(&mut ctx, &instance); assert_eq!(remaining_points, MeteringPoints::Remaining(new_limit)); println!("Remaining points: {:?}", remaining_points); diff --git a/examples/table.rs b/examples/table.rs index ac73da0a12c..70e365a5069 100644 --- a/examples/table.rs +++ b/examples/table.rs @@ -1,11 +1,12 @@ use wasmer::{ - imports, wat2wasm, Function, Instance, Module, Store, TableType, Type, TypedFunction, Value, + imports, wat2wasm, Context, ContextMut, Function, 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(arg1: i32, arg2: i32) -> i32 { +fn host_callback(_ctx: ContextMut<()>, arg1: i32, arg2: i32) -> i32 { arg1 + arg2 } @@ -52,20 +53,22 @@ 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, ()); // 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(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &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("call_callback")?; + let call_via_table: TypedFunction<(i32, i32, i32), i32> = instance + .exports + .get_typed_function(&mut ctx, "call_callback")?; // And then call it with table index 1 and arguments 2 and 7. - let result = call_via_table.call(1, 2, 7)?; + let result = call_via_table.call(&mut ctx, 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); @@ -73,10 +76,10 @@ 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(), 3); + assert_eq!(guest_table.size(&mut ctx), 3); assert_eq!( - guest_table.ty(), - &TableType { + guest_table.ty(&mut ctx), + TableType { ty: Type::FuncRef, minimum: 3, maximum: Some(6) @@ -86,31 +89,31 @@ fn main() -> anyhow::Result<()> { // == Setting elements in a table == // We first construct a `Function` over our host_callback. - let func = Function::new_native(&store, host_callback); + let func = Function::new_native(&mut ctx, host_callback); // And set table index 1 of that table to the host_callback `Function`. - guest_table.set(1, func.into())?; + guest_table.set(&mut ctx, 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(1, 2, 7)?; + let result = call_via_table.call(&mut ctx, 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(&store, host_callback); + let func = Function::new_native(&mut ctx, 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(3, func.into())?; + let previous_size = guest_table.grow(&mut ctx, 3, func.into())?; assert_eq!(previous_size, 3); - assert_eq!(guest_table.size(), 6); + assert_eq!(guest_table.size(&mut ctx), 6); assert_eq!( - guest_table.ty(), - &TableType { + guest_table.ty(&mut ctx), + TableType { ty: Type::FuncRef, minimum: 3, maximum: Some(6) @@ -118,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(table_index as _).unwrap() { - let result = f.call(&[Value::I32(1), Value::I32(9)])?; + 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)])?; assert_eq!(result[0], Value::I32(10)); } else { panic!("expected to find funcref in table!"); @@ -127,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(0, 2, 7)?; + let result = call_via_table.call(&mut ctx, 0, 2, 7)?; assert_eq!(result, 18); // Now overwrite index 0 with our host_callback. - let func = Function::new_native(&store, host_callback); - guest_table.set(0, func.into())?; + let func = Function::new_native(&mut ctx, host_callback); + guest_table.set(&mut ctx, 0, func.into())?; // And verify that it does what we expect. - let result = call_via_table.call(0, 2, 7)?; + let result = call_via_table.call(&mut ctx, 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(table_index as _).unwrap() { - let result = f.call(&[Value::I32(1), Value::I32(9)])?; + 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)])?; assert_eq!(result[0], Value::I32(10)); } else { panic!("expected to find funcref in table!"); } - let result = call_via_table.call(table_index, 1, 9)?; + let result = call_via_table.call(&mut ctx, table_index, 1, 9)?; assert_eq!(result, 10); } diff --git a/examples/tunables_limit_memory.rs b/examples/tunables_limit_memory.rs index 3e43cd9f7d5..9b4f4e1ebd7 100644 --- a/examples/tunables_limit_memory.rs +++ b/examples/tunables_limit_memory.rs @@ -1,11 +1,10 @@ use std::ptr::NonNull; -use std::sync::Arc; use wasmer::{ imports, vm::{self, MemoryError, MemoryStyle, TableStyle, VMMemoryDefinition, VMTableDefinition}, - wat2wasm, BaseTunables, Instance, Memory, MemoryType, Module, Pages, Store, TableType, Target, - Tunables, + wat2wasm, BaseTunables, Context, Instance, Memory, MemoryType, Module, Pages, Store, TableType, + Target, Tunables, }; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; @@ -86,7 +85,7 @@ impl Tunables for LimitingTunables { &self, ty: &MemoryType, style: &MemoryStyle, - ) -> Result, MemoryError> { + ) -> Result { let adjusted = self.adjust_memory(ty); self.validate_memory(&adjusted)?; self.base.create_host_memory(&adjusted, style) @@ -100,7 +99,7 @@ impl Tunables for LimitingTunables { ty: &MemoryType, style: &MemoryStyle, vm_definition_location: NonNull, - ) -> Result, MemoryError> { + ) -> Result { let adjusted = self.adjust_memory(ty); self.validate_memory(&adjusted)?; self.base @@ -110,11 +109,7 @@ impl Tunables for LimitingTunables { /// Create a table owned by the host given a [`TableType`] and a [`TableStyle`]. /// /// Delegated to base. - fn create_host_table( - &self, - ty: &TableType, - style: &TableStyle, - ) -> Result, String> { + fn create_host_table(&self, ty: &TableType, style: &TableStyle) -> Result { self.base.create_host_table(ty, style) } @@ -126,7 +121,7 @@ impl Tunables for LimitingTunables { ty: &TableType, style: &TableStyle, vm_definition_location: NonNull, - ) -> Result, String> { + ) -> Result { self.base.create_vm_table(ty, style, vm_definition_location) } } @@ -151,6 +146,7 @@ fn main() -> Result<(), Box> { // 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, ()); println!("Compiling module..."); let module = Module::new(&store, wasm_bytes)?; @@ -159,7 +155,7 @@ fn main() -> Result<(), Box> { let import_object = imports! {}; // Now at this point, our custom tunables are used - let instance = Instance::new(&module, &import_object)?; + let instance = Instance::new(&mut ctx, &module, &import_object)?; // Check what happened let mut memories: Vec = instance @@ -172,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().maximum.unwrap(), Pages(24)); + assert_eq!(first_memory.ty(&mut ctx).maximum.unwrap(), Pages(24)); Ok(()) } diff --git a/examples/wasi.rs b/examples/wasi.rs index 2b80cf7fc11..2eb77075e55 100644 --- a/examples/wasi.rs +++ b/examples/wasi.rs @@ -15,7 +15,7 @@ //! //! Ready? -use wasmer::{Instance, Module, Store}; +use wasmer::{AsContextMut, Context, Instance, Module, Store}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; use wasmer_wasi::WasiState; @@ -44,17 +44,24 @@ fn main() -> Result<(), Box> { // .args(&["world"]) // .env("KEY", "Value") .finalize()?; + // And now the context,using the newly created WasiEnv + let mut ctx = Context::new(&store, wasi_env.clone()); 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(&module)?; - let instance = Instance::new(&module, &import_object)?; + let import_object = wasi_env.import_object(&mut ctx.as_context_mut(), &module)?; + let instance = Instance::new(&mut ctx, &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()); println!("Call WASI `_start` function..."); // And we just call the `_start` function! let start = instance.exports.get_function("_start")?; - start.call(&[])?; + start.call(&mut ctx, &[])?; Ok(()) } diff --git a/examples/wasi_pipes.rs b/examples/wasi_pipes.rs index c4efec10a84..b5b8a750459 100644 --- a/examples/wasi_pipes.rs +++ b/examples/wasi_pipes.rs @@ -12,7 +12,7 @@ //! Ready? use std::io::{Read, Write}; -use wasmer::{Instance, Module, Store}; +use wasmer::{AsContextMut, Context, Instance, Module, Store}; use wasmer_compiler::Universal; use wasmer_compiler_cranelift::Cranelift; use wasmer_wasi::{Pipe, WasiState}; @@ -43,12 +43,18 @@ fn main() -> Result<(), Box> { .stdin(Box::new(input.clone())) .stdout(Box::new(output.clone())) .finalize()?; + let mut ctx = Context::new(&store, wasi_env.clone()); 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(&module)?; - let instance = Instance::new(&module, &import_object)?; + let import_object = wasi_env.import_object(&mut ctx.as_context_mut(), &module)?; + let instance = Instance::new(&mut ctx, &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()); let msg = "racecar go zoom"; println!("Writing \"{}\" to the WASI stdin...", msg); @@ -58,7 +64,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(&[])?; + start.call(&mut ctx, &[])?; println!("Reading from the WASI stdout...");