### Hello World Component Example Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/bindgen_examples/mod.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates a basic 'hello world' component setup. It shows how to add a trait to the linker and instantiate a component, then call a function from the generated bindings. ```rust use wasmtime::component::*; use wasmtime::{Engine, Store}; #[doc = include_str!("./_0_hello_world.rs")] struct MyState { name: String, } fn main() -> wasmtime::Result<()> { let engine = Engine::default(); let component = Component::from_file(&engine, "./your-component.wasm")?; // The `add_to_linker` method is generated by the `bindgen!` macro. // It takes a mutable reference to a `Linker`, and a closure which // will be called to create the host state for the component. // // The second type parameter of `add_to_linker` is chosen here // as the built-in `HasSelf` type in Wasmtime. This effectively says // that our function isn't actually projecting, it's returning the // input, so `HasSelf<_>` is a convenience to avoid writing a custom // `HasData` implementation. let mut linker = Linker::new(&engine); HelloWorld::add_to_linker::<_, HasSelf<_>>(&mut linker, |state| state)?; // As with the core wasm API of Wasmtime instantiation occurs within a // `Store`. The bindings structure contains an `instantiate` method which // takes the store, component, and linker. This returns the `bindings` // structure which is an instance of `HelloWorld` and supports typed access // to the exports of the component. let mut store = Store::new( &engine, MyState { name: "me".to_string(), }, ); let bindings = HelloWorld::instantiate(&mut store, &component, &linker)?; // Here our `greet` function doesn't take any parameters for the component, // but in the Wasmtime embedding API the first argument is always a `Store`. bindings.call_greet(&mut store)?; Ok(()) } ``` -------------------------------- ### Get Module Imports Example (No Imports) Source: https://docs.rs/wasmtime/latest/wasmtime/struct.Module.html?search=u32+-%3E+bool Shows how to get the list of imports for a Wasmtime module. This example demonstrates a module with no imports, resulting in an empty list. ```rust let module = Module::new(&engine, "(module)")?; assert_eq!(module.imports().len(), 0); ``` -------------------------------- ### Hello World Component Example Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/bindgen_examples/mod.rs.html Demonstrates loading and instantiating a WebAssembly component that exports a function and imports a host function. It shows how to set up the Wasmtime engine, store, component, and linker, and how to satisfy imports using traits. ```rust use wasmtime::component::* use wasmtime::{Engine, Store}; struct MyState { name: String, } impl HelloWorldImports for MyState { fn name(&mut self) -> String { self.name.clone() } } fn main() -> wasmtime::Result<()> { // Compile the `Component` that is being run for the application. let engine = Engine::default(); let component = Component::from_file(&engine, "./your-component.wasm")?; // Instantiation of bindings always happens through a `Linker`. // Configuration of the linker is done through a generated `add_to_linker` // method on the bindings structure. // // Note that the function provided here is a projection from `T` in // `Store` to `&mut U` where `U` implements the `HelloWorldImports` ``` -------------------------------- ### Get Memory as Non-Null Pointer Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/mmap.rs.html?search=std%3A%3Avec Returns a NonNull pointer to the start of the allocated memory. This guarantees the pointer is not null. ```rust /// Return the allocated memory as a mutable pointer to u8. #[inline] pub fn as_non_null(&self) -> NonNull { self.sys.as_send_sync_ptr().as_non_null() } ``` -------------------------------- ### Get Offset from MmapOffset Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/mmap.rs.html?search= Returns the host-page-aligned offset within the mmap. This is the specific byte offset from the start of the mmap. ```rust /// Returns the host-page-aligned offset within the mmap. #[inline] pub fn offset(&self) -> HostAlignedByteCount { self.offset } ``` -------------------------------- ### Creating a Store with Default Configuration Source: https://docs.rs/wasmtime/latest/wasmtime/struct.Store.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a new `Store` with default configuration settings, which includes a new `Engine` with default configurations. ```rust let mut store = Store::default(); ``` -------------------------------- ### Hello World Component Example Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/bindgen_examples/mod.rs.html?search=u32+-%3E+bool Demonstrates loading a component with a single host function import and calling an exported function. Imports are satisfied via traits. ```rust use wasmtime::component::*; use wasmtime::{Engine, Store}; struct MyState { name: String, } // Imports into the world, like the `name` import for this world, are // satisfied through traits. impl HelloWorldImports for MyState { fn name(&mut self) -> String { self.name.clone() } } fn main() -> wasmtime::Result<()> { // Compile the `Component` that is being run for the application. let engine = Engine::default(); let component = Component::from_file(&engine, "./your-component.wasm")?; // Instantiation of bindings always happens through a `Linker`. // Configuration of the linker is done through a generated `add_to_linker` // method on the bindings structure. // // Note that the function provided here is a projection from `T` in // `Store` to `&mut U` where `U` implements the `HelloWorldImports` ``` -------------------------------- ### Get Module Exports (With Exports) Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/module.rs.html?search=std%3A%3Avec Retrieves and inspects exports for a WebAssembly module. This example shows how to check for the presence of exports. ```rust # use wasmtime::* # fn main() -> Result<()> { # let engine = Engine::default(); # let wat = r#"( # module # (func (export "bar")) # ) # "#; # let module = Module::new(&engine, wat)?; # // This is a placeholder, actual export inspection would involve iterating module.exports() # assert!(module.exports().next().is_some()); # Ok(()) # } ``` -------------------------------- ### Get Function Start Source Location Source: https://docs.rs/wasmtime/latest/wasmtime/struct.CompiledModule.html Returns the original binary offset in the file where the function at the given index was defined. ```rust pub fn func_start_srcloc(&self, key: FuncKey) -> FilePos ``` -------------------------------- ### HelloWorld Instantiation Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_2_world_exports/struct.HelloWorld.html?search=u32+-%3E+bool Demonstrates how to instantiate the HelloWorld struct using different approaches. ```APIDOC ## HelloWorld Auto-generated bindings for an instance a component which implements the world `hello-world`. ### Instantiation Methods 1. **`HelloWorld::instantiate`**: Creates an instance using a `Store`, `Component`, and `Linker`. 2. **`HelloWorldPre::instantiate`**: First creates a `HelloWorldPre` with a `Component` for ahead-of-time string lookups, then instantiates it. 3. **`HelloWorld::new`**: Creates an instance if you have already instantiated the component yourself using an `Instance`. These methods balance the work performed at different stages. ``` -------------------------------- ### Get Stack Range Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/stack_switching/stack/unix.rs.html?search=u32+-%3E+bool Calculates and returns the memory range (start and end addresses) occupied by the stack's data. ```rust pub fn range(&self) -> Option> { let base = unsafe { self.top.sub(self.len).addr() }; Some(base..base + self.len) } ``` -------------------------------- ### Example: Creating and Instantiating with a Table Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/externals/table.rs.html?search= Illustrates the creation of a `Table` and its subsequent use when instantiating a Wasm module. This example shows setting up a function table and importing it into a module. ```rust # use wasmtime::* # fn main() -> Result<()> { let engine = Engine::default(); let mut store = Store::new(&engine, ()); let ty = TableType::new(RefType::FUNCREF, 2, None); let table = Table::new(&mut store, ty, Ref::Func(None))?; let module = Module::new( &engine, "(module (table (import \"\" \"") 2 funcref) (func $f (result i32) i32.const 10) (elem (i32.const 0) $f) )" )?; let instance = Instance::new(&mut store, &module, &[table.into()])?; // ... Ok(()) # } ``` -------------------------------- ### Get Memory as Mutable Pointer Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/mmap.rs.html?search=std%3A%3Avec Returns a mutable pointer to the start of the allocated memory. Use this for direct memory manipulation. ```rust /// Return the allocated memory as a mutable pointer to u8. #[inline] pub fn as_mut_ptr(&self) -> *mut u8 { self.sys.as_send_sync_ptr().as_ptr() } ``` -------------------------------- ### HelloWorldPre::new Source: https://docs.rs/wasmtime/latest/src/wasmtime/opt/rustwide/target/debug/build/wasmtime-internal-component-macro-b79c1cccc3b964c2/out/hello-world2.rs.html?search=u32+-%3E+bool Creates a new HelloWorldPre bindings. This can be used to instantiate a component into a store. It may fail if the component does not have the required exports. ```APIDOC ## HelloWorldPre::new ### Description Creates a new copy of `HelloWorldPre` bindings which can then be used to instantiate into a particular store. This method may fail if the component behind `instance_pre` does not have the required exports. ### Method `pub fn new(instance_pre: crate::component::InstancePre<_T>) -> crate::Result` ### Parameters * `instance_pre` (`crate::component::InstancePre<_T>`): The pre-instantiated instance to create bindings from. ``` -------------------------------- ### Hello World Component Example Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/bindgen_examples/mod.rs.html Demonstrates a basic 'hello world' component interaction, including adding a function to the linker, instantiating a component, and calling an exported function. ```rust use wasmtime::component::*; use wasmtime::{Engine, Store}; #[doc = include_str!("./_0_hello_world.rs")] struct MyState { name: String, } impl HelloWorld for MyState { fn greet(&mut self) -> String { format!("Hello, {}!", self.name) } } fn main() -> wasmtime::Result<()> { let engine = Engine::default(); let component = Component::from_file(&engine, "./your-component.wasm")?; // The `add_to_linker` method is generated by the `componentize` macro. // It takes a mutable reference to a `Linker`, and a closure which // will be used to extract the host state from the `Store`. // // In this case the `T`, `MyState`, is stored directly in the // structure so no projection is necessary here. // // Note that the second type parameter of `add_to_linker` is chosen here // as the built-in `HasSelf` type in Wasmtime. This effectively says // that our function isn't actually projecting, it's returning the // input, so `HasSelf<_>` is a convenience to avoid writing a custom // `HasData` implementation. let mut linker = Linker::new(&engine); HelloWorld::add_to_linker::<_, HasSelf<_>>(&mut linker, |state| state)?; // As with the core wasm API of Wasmtime instantiation occurs within a // `Store`. The bindings structure contains an `instantiate` method which // takes the store, component, and linker. This returns the `bindings` // structure which is an instance of `HelloWorld` and supports typed access // to the exports of the component. let mut store = Store::new( &engine, MyState { name: "me".to_string(), }, ); let bindings = HelloWorld::instantiate(&mut store, &component, &linker)?; // Here our `greet` function doesn't take any parameters for the component, // but in the Wasmtime embedding API the first argument is always a `Store`. bindings.call_greet(&mut store)?; Ok(()) } ``` -------------------------------- ### get Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/func/options.rs.html?search= Returns a fixed mutable slice of memory N bytes large starting at offset N, panicking on out-of-bounds. ```APIDOC ## get ### Description Retrieves a mutable slice of a fixed size `N` from memory, starting at a specified `offset`. This method panics if the requested slice goes out of bounds. ### Method Getter ### Endpoint N/A (Method within a struct) ### Parameters - **N** (const usize) - Description: The fixed size of the slice to retrieve. - **offset** (usize) - Description: The starting offset in memory for the slice. ### Panics - Panics if memory has not been configured for this lowering. - Panics on out-of-bounds access. ### Response #### Success Response - **&mut [u8; N]**: A mutable reference to a byte array of size `N`. ### Response Example ```json { "example": "Mutable byte array of size N" } ``` ``` -------------------------------- ### Get Text Segment Range Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/code.rs.html?search=u32+-%3E+bool Provides the start and end range of the text segment (executable code) as `EngineCodePC` pointers. ```rust pub fn text_range(&self) -> Range { let raw = self.original_code.raw_addr_range(); EngineCodePC(raw.start)..EngineCodePC(raw.end) } ``` -------------------------------- ### Example of using Instance::new_async Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/instance.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the basic usage of `Instance::new_async` with a simple module and an empty import list within an asynchronous context. Ensure your store's data is `Send` for compatibility with asynchronous runtimes. ```rust use wasmtime::{Result, Store, Engine, Module, Instance}; #[tokio::main] async fn main() -> Result<()> { let engine = Engine::default(); // For this example, a module with no imports is being used hence // the empty array to `Instance::new_async`. let module = Module::new(&engine, "(module)")?; let mut store = Store::new(&engine, ()); let instance = Instance::new_async(&mut store, &module, &[]).await?; // ... use `instance` and exports and such ... Ok(()) } ``` -------------------------------- ### HelloWorldPre::instantiate_async Source: https://docs.rs/wasmtime/latest/src/wasmtime/opt/rustwide/target/debug/build/wasmtime-internal-component-macro-b79c1cccc3b964c2/out/hello-world2.rs.html?search=u32+-%3E+bool Asynchronously instantiates a new instance of HelloWorld within the provided store using the pre-instantiated HelloWorldPre bindings. ```APIDOC ## HelloWorldPre::instantiate_async ### Description Same as [`Self::instantiate`], except with `async`. ### Method `pub async fn instantiate_async(&self, mut store: impl crate::AsContextMut) -> crate::Result` ### Parameters * `store` (`impl crate::AsContextMut`): A mutable reference to the store context. ``` -------------------------------- ### Get Wasmtime Continuation Start Address Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/stack_switching/stack/unix/x86_64.rs.html Retrieves the memory address of the `wasmtime_continuation_start` function. This is used as the base entry point for all fibers. ```rust use core::arch::naked_asm; #[inline(never)] // FIXME(rust-lang/rust#148307) pub fn wasmtime_continuation_start_address() -> *const () { wasmtime_continuation_start as *const () } ``` -------------------------------- ### Get Wasmtime Continuation Start Address Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/stack_switching/stack/unix/x86_64.rs.html?search= Returns the memory address of the `wasmtime_continuation_start` function. This is used as the base entry point for all fibers. ```rust pub fn wasmtime_continuation_start_address() -> *const () { wasmtime_continuation_start as *const () } ``` -------------------------------- ### HelloWorld Demo Method Source: https://docs.rs/wasmtime/latest/src/wasmtime/opt/rustwide/target/debug/build/wasmtime-internal-component-macro-b79c1cccc3b964c2/out/hello-world2.rs.html Returns a reference to the guest exports for the 'demo' interface. ```rust pub fn demo(&self) -> &exports::demo::Guest { &self.interface0 } ``` -------------------------------- ### instantiate Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_2_world_exports/struct.HelloWorld.html?search=std%3A%3Avec Convenience wrapper around `HelloWorldPre::new` and `HelloWorldPre::instantiate`. This method creates a `HelloWorld` instance using a `Store`, `Component`, and `Linker`. ```APIDOC ## instantiate ### Description Convenience wrapper around `HelloWorldPre::new` and `HelloWorldPre::instantiate`. ### Method `pub fn instantiate<_T>( store: impl AsContextMut, component: &Component, linker: &Linker<_T>, ) -> Result` ### Parameters * `store`: A mutable reference to the store context. * `component`: A reference to the component to instantiate. * `linker`: A reference to the linker used for instantiation. ``` -------------------------------- ### Get Offset Value Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/mmap.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the host-page-aligned offset value within the Mmap. This represents the byte count from the start of the Mmap to this offset. ```rust /// Returns the host-page-aligned offset within the mmap. #[inline] pub fn offset(&self) -> HostAlignedByteCount { self.offset } ``` -------------------------------- ### Get Text Range Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/code.rs.html Provides the address range (start and end) of the engine code's text segment, represented by `EngineCodePC`. ```rust pub fn text_range(&self) -> Range { let raw = self.original_code.raw_addr_range(); EngineCodePC(raw.start)..EngineCodePC(raw.end) } ``` -------------------------------- ### HelloWorldPre::instantiate Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_0_hello_world/struct.HelloWorldPre.html?search= Instantiates a new HelloWorld component instance within the given store. ```APIDOC ## pub fn instantiate(&self, store: impl AsContextMut) -> Result ### Description Instantiates a new instance of `HelloWorld` within the `store` provided. This function will use `self` as the pre-instantiated instance to perform instantiation. Afterwards the preloaded indices in `self` are used to lookup all exports on the resulting instance. ### Parameters * `store`: A mutable reference to a store that implements `AsContextMut`. ### Returns A `Result` containing the `HelloWorld` instance if successful, or an error if instantiation fails. ``` -------------------------------- ### Running VTune Profiler with Wasmtime Source: https://docs.rs/wasmtime/latest/src/wasmtime/profiling_agent/vtune.rs.html Example command to run Wasmtime with VTune profiling enabled. Ensure VTune is installed and configured. ```bash vtune -run-pass-thru=--no-altstack -v -collect hotspots target/debug/wasmtime --profile=vtune test.wasm ``` -------------------------------- ### HelloWorldPre::instantiate_async Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_0_hello_world/struct.HelloWorldPre.html?search=u32+-%3E+bool Asynchronously instantiates a new instance of HelloWorld within the provided store using the pre-instantiated bindings. ```APIDOC ## HelloWorldPre::instantiate_async ### Description Same as `Self::instantiate`, except with `async`. ### Method `pub async fn instantiate_async(&self, store: impl AsContextMut) -> Result` ### Parameters #### Path Parameters - **store** (impl AsContextMut) - Required - The store context to instantiate the component within. ``` -------------------------------- ### Example: Logging String from Wasm Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/func.rs.html?search=u32+-%3E+bool Demonstrates how to use `get_module_export` within a Wasmtime host function to access memory exported by a Wasm module and log a string. This example shows the setup for a Wasm module with imports and exports, and how to instantiate it with a host function. ```rust use std::str; # use wasmtime::*; # fn main() -> Result<()> { # let mut store = Store::default(); let module = Module::new( store.engine(), r#"( (module (import "" "" (func $log_str (param i32 i32))) (func (export "foo") i32.const 4 ;; ptr i32.const 13 ;; len call $log_str) (memory (export "memory") 1) (data (i32.const 4) "Hello, world!")) "#, )?; let Some(module_export) = module.get_export_index("memory") else { bail!("failed to find `memory` export in module"); }; let log_str = Func::wrap(&mut store, move |mut caller: Caller<'_, ()>, ptr: i32, len: i32| { let mem = match caller.get_module_export(&module_export) { Some(Extern::Memory(mem)) => mem, _ => bail!("failed to find host memory"), }; let data = mem.data(&caller) .get(ptr as u32 as usize..) .and_then(|arr| arr.get(..len as u32 as usize)); let string = match data { Some(data) => match str::from_utf8(data) { Ok(s) => s, Err(_) => bail!("invalid utf-8"), }, None => bail!("pointer/length out of bounds"), }; assert_eq!(string, "Hello, world!"); println!("{}", string); Ok(()) }); let instance = Instance::new(&mut store, &module, &[log_str.into()])?; let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?; foo.call(&mut store, ())?; # Ok(()) # } ``` -------------------------------- ### HelloWorldPre::instantiate Source: https://docs.rs/wasmtime/latest/src/wasmtime/opt/rustwide/target/debug/build/wasmtime-internal-component-macro-b79c1cccc3b964c2/out/hello-world2.rs.html?search=u32+-%3E+bool Instantiates a new instance of HelloWorld within the provided store using the pre-instantiated HelloWorldPre bindings. ```APIDOC ## HelloWorldPre::instantiate ### Description Instantiates a new instance of [`HelloWorld`] within the `store` provided. This function will use `self` as the pre-instantiated instance to perform instantiation. Afterwards the preloaded indices in `self` are used to lookup all exports on the resulting instance. ### Method `pub fn instantiate(&self, mut store: impl crate::AsContextMut) -> crate::Result` ### Parameters * `store` (`impl crate::AsContextMut`): A mutable reference to the store context. ``` -------------------------------- ### Example: Calculating Resources for a Component Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/component.rs.html?search=u32+-%3E+bool Demonstrates how to calculate the required resources for a component that instantiates a core module multiple times. This example shows how to check the number of memories and maximum initial memory size. ```rust use wasmtime::{Config, Engine, component::Component}; let mut config = Config::new(); config.wasm_multi_memory(true); config.wasm_component_model(true); let engine = Engine::new(&config)?; let component = Component::new(&engine, &r#"( component ;; Define a core module that uses two memories. (core module $m (memory 1) (memory 6) ) ;; Instantiate that core module three times. (core instance $i1 (instantiate (module $m))) (core instance $i2 (instantiate (module $m))) (core instance $i3 (instantiate (module $m))) )"#)?; let resources = component.resources_required() .expect("this component does not import any core modules or instances"); // Instantiating the component will require allocating two memories per // core instance, and there are three instances, so six total memories. assert_eq!(resources.num_memories, 6); assert_eq!(resources.max_initial_memory_size, Some(6)); // The component doesn't need any tables. assert_eq!(resources.num_tables, 0); assert_eq!(resources.max_initial_table_size, None); ``` -------------------------------- ### Create Engine with Default Configuration Source: https://docs.rs/wasmtime/latest/src/wasmtime/engine.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new Wasmtime Engine using the default configuration settings. This is a convenient way to get started. ```rust impl Default for Engine { fn default() -> Engine { Engine::new(&Config::default()).unwrap() } } ``` -------------------------------- ### Get Module Imports (With Imports) Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/module.rs.html?search=std%3A%3Avec Retrieves and inspects imports for a WebAssembly module. This example shows how to check the number of imports and details of a specific import. ```rust # use wasmtime::* # fn main() -> Result<()> { # let engine = Engine::default(); let wat = r#"( module (import "host" "foo" (func)) ) "#; let module = Module::new(&engine, wat)?; assert_eq!(module.imports().len(), 1); let import = module.imports().next().unwrap(); assert_eq!(import.module(), "host"); assert_eq!(import.name(), "foo"); match import.ty() { ExternType::Func(_) => { /* ... */ } // Placeholder for actual type check _ => panic!("unexpected import type!"), } # Ok(()) # } ``` -------------------------------- ### Example: Asynchronous Instance Creation Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/instance.rs.html Demonstrates creating an instance using `Instance::new_async` within a Tokio runtime. Assumes a module with no imports. ```rust use wasmtime::{Result, Store, Engine, Module, Instance}; #[tokio::main] async fn main() -> Result<()> { let engine = Engine::default(); // For this example, a module with no imports is being used hence // the empty array to `Instance::new_async`. let module = Module::new(&engine, "(module)")?; let mut store = Store::new(&engine, ()); let instance = Instance::new_async(&mut store, &module, &[]).await?; // ... use `instance` and exports and such ... Ok(()) } ``` -------------------------------- ### Get Memory Base Address Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/memory/mmap.rs.html Retrieves the base address of the memory, adjusted by the pre-guard size. This is useful for obtaining the starting point of accessible memory. ```rust fn base(&self) -> MemoryBase { MemoryBase::Mmap( self.mmap .offset(self.pre_guard_size) .expect("pre_guard_size is in bounds"), ) } ``` -------------------------------- ### HelloWorldPre::new Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_0_hello_world/struct.HelloWorldPre.html?search= Creates a new HelloWorldPre bindings from an InstancePre. This can fail if the component does not have the required exports. ```APIDOC ## pub fn new(instance_pre: InstancePre) -> Result ### Description Creates a new copy of `HelloWorldPre` bindings which can then be used to instantiate into a particular store. This method may fail if the component behind `instance_pre` does not have the required exports. ### Parameters * `instance_pre`: An `InstancePre` object representing a pre-instantiated component. ``` -------------------------------- ### HelloWorldPre::new Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_2_world_exports/struct.HelloWorldPre.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new HelloWorldPre bindings from a pre-instantiated instance. This can be used to instantiate a component within a store, provided the component has the necessary exports. ```APIDOC ## HelloWorldPre::new ### Description Creates a new copy of `HelloWorldPre` bindings which can then be used to instantiate into a particular store. ### Method `pub fn new(instance_pre: InstancePre<_T>) -> Result` ### Parameters #### Path Parameters - `instance_pre` (InstancePre<_T>) - Required - The pre-instantiated instance to create bindings from. ### Response #### Success Response - `Self` (HelloWorldPre) - A new instance of HelloWorldPre bindings. #### Error Response - `Result` - May fail if the component behind `instance_pre` does not have the required exports. ``` -------------------------------- ### Start Asynchronous Caller Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/concurrent.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initiates a call when the caller is using the asynchronous ABI. This function is part of the setup for asynchronous operations within the component model. ```rust unsafe fn async_start( &mut self, instance: Instance, callback: *mut VMFuncRef, ``` -------------------------------- ### Engine::default Source: https://docs.rs/wasmtime/latest/src/wasmtime/engine.rs.html?search= Creates a new Wasmtime Engine with default configuration settings. This is a convenient way to get started without specifying individual configuration options. ```APIDOC ## Engine::default ### Description Creates a new [`Engine`] with default configuration settings. Consult the documentation of [`Config`] for default settings. ### Method `Engine::default() -> Engine` ### Parameters None ### Request Example ```rust let engine = wasmtime::Engine::default(); ``` ### Response #### Success Response (Engine) - Returns a new `Engine` instance with default configurations. #### Response Example ```rust // Success is implicit as this method does not return a Result ``` ``` -------------------------------- ### HelloWorldPre::instantiate Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_0_hello_world/struct.HelloWorldPre.html?search=u32+-%3E+bool Instantiates a new instance of HelloWorld within the provided store using the pre-instantiated bindings. ```APIDOC ## HelloWorldPre::instantiate ### Description Instantiates a new instance of `HelloWorld` within the `store` provided. This function will use `self` as the pre-instantiated instance to perform instantiation. Afterwards the preloaded indices in `self` are used to lookup all exports on the resulting instance. ### Method `pub fn instantiate(&self, store: impl AsContextMut) -> Result` ### Parameters #### Path Parameters - **store** (impl AsContextMut) - Required - The store context to instantiate the component within. ``` -------------------------------- ### Fetch StoreCode Base by EngineCode Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/module/registry.rs.html Gets the base `StoreCodePC` for a given `EngineCode`. This is determined by looking up the starting address of the `EngineCode`'s text range in the `store_code` map. ```rust pub fn store_code_base(&self, engine_code: &EngineCode) -> Option { self.store_code.get(engine_code.text_range().start).cloned() } ``` -------------------------------- ### HelloWorldPre::new Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_2_world_exports/struct.HelloWorldPre.html?search=std%3A%3Avec Creates a new HelloWorldPre bindings instance from a pre-instantiated component. This can fail if the component lacks the required exports. ```APIDOC ## `HelloWorldPre::new` ### Description Creates a new copy of `HelloWorldPre` bindings which can then be used to instantiate into a particular store. This method may fail if the component behind `instance_pre` does not have the required exports. ### Signature `pub fn new(instance_pre: InstancePre<_T>) -> Result` ### Parameters * `instance_pre` (`InstancePre<_T>`): A pre-instantiated instance of a component. ### Returns * `Result`: A `Result` containing the `HelloWorldPre` instance on success, or an error if the component exports are insufficient. ``` -------------------------------- ### Get Allocated Bytes in Copying GC Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/gc/enabled/copying.rs.html?search= Returns the total number of bytes currently allocated in the copying heap. This is calculated based on the bump pointer and the start of the active space. ```rust fn allocated_bytes(&self) -> usize { usize::try_from(self.bump_ptr() - self.active_space_start).unwrap() } ``` -------------------------------- ### Instantiate HelloWorld with Store, Component, and Linker Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_0_hello_world/struct.HelloWorld.html Convenience wrapper for instantiating a component and creating a HelloWorld instance. This is the most straightforward method when a Store, Component, and Linker are available. ```rust pub fn instantiate<_T>( store: impl AsContextMut, component: &Component, linker: &Linker<_T>, ) -> Result ``` -------------------------------- ### func_loc Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/instantiate.rs.html?search=std%3A%3Avec Gets the location information (start offset and length) for a given function key within the runtime's code section. This is a helper function for retrieving function metadata. ```APIDOC ## func_loc ### Description Gets the location information (start offset and length) for a given function key within the runtime's code section. This is a helper function for retrieving function metadata. ### Method `&self` (method on `Runtime` struct) ### Parameters #### Path Parameters - **key** (`FuncKey`) - Description: The key identifying the function for which to retrieve location information. ### Returns A reference to `FunctionLoc` containing the start and length of the function in the text section. ``` -------------------------------- ### instantiate_async Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/instance.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new instance, running the start function asynchronously instead of inline. ```APIDOC ## instantiate_async ### Description Creates a new instance, running the start function asynchronously instead of inline. For more information about asynchronous instantiation see the documentation on [`Instance::new_async`]. ### Method `#[cfg(feature = "async")] pub async fn instantiate_async(&self, mut store: impl AsContextMut) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Panics Panics if any import closed over by this [`InstancePre`] isn't owned by `store`, or if `store` does not have async support enabled. ### Errors This function will return an [`OutOfMemory`][crate::OutOfMemory] error when memory allocation fails. See the `OutOfMemory` type's documentation for details on Wasmtime's out-of-memory handling. ### Returns - `Result`: A `Result` containing the instantiated `Instance` on success, or an error on failure. ``` -------------------------------- ### Create a new Table Source: https://docs.rs/wasmtime/latest/wasmtime/struct.Table.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates creating a new WebAssembly table with a specified type and initial value. This example shows setting up an engine, store, table type, and then initializing the table. ```rust let engine = Engine::default(); let mut store = Store::new(&engine, ()); let ty = TableType::new(RefType::FUNCREF, 2, None); let table = Table::new(&mut store, ty, Ref::Func(None))?; let module = Module::new( &engine, "(module\n (table (import \"\" \"\") 2 funcref)\n (func $f (result i32)\n i32.const 10)\n (elem (i32.const 0) $f)\n )" )?; let instance = Instance::new(&mut store, &module, &[table.into()])?; // ... ``` -------------------------------- ### Get Module Imports Example (With Imports) Source: https://docs.rs/wasmtime/latest/wasmtime/struct.Module.html?search=u32+-%3E+bool Demonstrates retrieving import details for a Wasmtime module that has defined imports. It checks the count, module name, import name, and type of the import. ```rust let wat = r#"( module (import "host" "foo" (func)) )"#; let module = Module::new(&engine, wat)?; assert_eq!(module.imports().len(), 1); let import = module.imports().next().unwrap(); assert_eq!(import.module(), "host"); assert_eq!(import.name(), "foo"); match import.ty() { ExternType::Func(_) => { /* ... */ } _ => panic!("unexpected import type!"), } ``` -------------------------------- ### HelloWorldPre::instantiate_async Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_0_hello_world/struct.HelloWorldPre.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Asynchronously instantiates a new instance of HelloWorld within the provided store, using the pre-instantiated instance. It then uses the preloaded indices to look up all exports on the resulting instance. ```APIDOC ## HelloWorldPre::instantiate_async ### Description Same as `Self::instantiate`, except with `async`. ### Method `pub async fn instantiate_async(&self, store: impl AsContextMut) -> Result` ### Parameters #### Path Parameters - **store** (impl AsContextMut) - Required - The store to instantiate the HelloWorld instance within. ### Response #### Success Response - **HelloWorld** (HelloWorld) - The newly instantiated HelloWorld instance. - **Result** (Result) - Ok if successful, Err otherwise. ``` -------------------------------- ### InstancePre::instantiate_async Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/instance.rs.html?search=u32+-%3E+bool Creates a new instance, running the start function asynchronously instead of inline. This is used for asynchronous instantiation. ```APIDOC ## InstancePre::instantiate_async ### Description Creates a new instance, running the start function asynchronously instead of inline. For more information about asynchronous instantiation see the documentation on [`Instance::new_async`]. ### Method POST ### Endpoint `/instantiate_async` ### Parameters #### Query Parameters - **store** (impl AsContextMut) - Required - The store to instantiate the instance within. ### Panics Panics if any import closed over by this [`InstancePre`] isn't owned by `store`, or if `store` does not have async support enabled. ### Errors - **OutOfMemory** - Returned when memory allocation fails. ### Returns - **Instance** - The newly created `Instance`. ``` -------------------------------- ### Initiating and Running a Concurrent Function Call Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/concurrent/func.rs.html?search= This example demonstrates how to get a function from an instance and then execute it concurrently using `store.run_concurrent`. It shows the typical workflow for calling a Wasm function asynchronously. ```rust /// # let mut linker = Linker::new(&engine); /// # let component = Component::new(&engine, "")?; /// # let instance = linker.instantiate_async(&mut store, &component).await?; /// let my_func = instance.get_func(&mut store, "my_func").unwrap(); /// store.run_concurrent(async |accessor| -> wasmtime::Result<_> { /// my_func.call_concurrent(accessor, &[], &mut Vec::new()).await?; /// Ok(()) /// }).await??; /// # Ok(()) /// # } /// pub async fn call_concurrent( /// self, /// accessor: impl AsAccessor, /// params: &[Val], /// results: &mut [Val], /// ) -> Result<()> { /// let accessor = accessor.as_accessor(); /// let call = accessor.with(|store| self.start_call_concurrent(store, params, results))?; /// self.finish_call_concurrent(accessor, call).await /// } ``` -------------------------------- ### Instance Creation and Resource Metrics Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/vm/instance/allocator/pooling/metrics.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create an instance and observe changes in pooling allocator metrics for memories, tables, and instances. It also shows how metrics change after dropping the store and re-instantiating. ```rust let mut store = Store::new(&engine, ()); let i = crate::Instance::new(&mut store, &m1, &[])?; assert_eq!(metrics.memories(), 1); assert_eq!(metrics.tables(), 1); assert_eq!(metrics.core_instances(), 1); assert_eq!(metrics.component_instances(), 0); assert_eq!(metrics.unused_warm_memories(), 0); assert_eq!(metrics.unused_warm_tables(), 0); assert_eq!(metrics.unused_memory_bytes_resident(), 0); assert_eq!(metrics.unused_table_bytes_resident(), 0); let m = i.get_memory(&mut store, "m").unwrap(); m.data_mut(&mut store)[0] = 1; m.grow(&mut store, 1)?; drop(store); assert_eq!(metrics.memories(), 0); assert_eq!(metrics.tables(), 0); assert_eq!(metrics.core_instances(), 0); assert_eq!(metrics.unused_warm_memories(), 1); assert_eq!(metrics.unused_warm_tables(), 1); if PoolingAllocationConfig::is_pagemap_scan_available() { assert_eq!(metrics.unused_memory_bytes_resident(), host_page_size); assert_eq!(metrics.unused_table_bytes_resident(), host_page_size); } else { assert_eq!(metrics.unused_memory_bytes_resident(), 65536); assert_eq!(metrics.unused_table_bytes_resident(), host_page_size); } ``` -------------------------------- ### Get Function Offset Source: https://docs.rs/wasmtime/latest/wasmtime/struct.FrameInfo.html?search= Returns the optional offset from the start of the function within the WebAssembly module to this frame's program counter. This also requires mapping information to be generated during compilation. ```rust pub fn func_offset(&self) -> Option ``` -------------------------------- ### Getting Wasm Bytecode for a Module Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/code_memory.rs.html Extracts the Wasm bytecode for a given core module. It uses `wasm_bytecode_end_for_module` to determine the start and end points of the bytecode within the larger Wasm artifact. ```rust pub(crate) fn wasm_bytecode_for_module(&self, index: StaticModuleIndex) -> Option<&[u8]> { let start = if index.as_u32() == 0 { 0 } else { self.wasm_bytecode_end_for_module(StaticModuleIndex::from_u32(index.as_u32() - 1))? }; let end = self.wasm_bytecode_end_for_module(index)?; Some(&self.wasm_bytecode()[start..end]) } ``` -------------------------------- ### HelloWorld::new Source: https://docs.rs/wasmtime/latest/wasmtime/component/bindgen_examples/_0_hello_world/struct.HelloWorld.html?search=u32+-%3E+bool Creates a HelloWorld instance directly from an existing Instance. This is useful if you have already instantiated the component. ```APIDOC ## HelloWorld::new ### Description Convenience wrapper around `HelloWorldIndices::new` and `HelloWorldIndices::load`. ### Method `new` ### Parameters - `store`: `impl AsContextMut` - The store context. - `instance`: `&Instance` - The already instantiated component instance. ### Returns - `Result` - A `Result` containing the HelloWorld instance or an error. ``` -------------------------------- ### Example: Creating and Manipulating a Struct Instance Source: https://docs.rs/wasmtime/latest/wasmtime/struct.StructRef.html?search= Demonstrates how to configure Wasmtime for GC, define a struct type, allocate a struct instance, and interact with its fields. Ensure `wasm_function_references` and `wasm_gc` are enabled. ```rust use wasmtime::*; let mut config = Config::new(); config.wasm_function_references(true); config.wasm_gc(true); let engine = Engine::new(&config)?; let mut store = Store::new(&engine, ()); // Define a struct type. let struct_ty = StructType::new( store.engine(), [FieldType::new(Mutability::Var, StorageType::I8)], )?; // Create an allocator for the struct type. let allocator = StructRefPre::new(&mut store, struct_ty); { let mut scope = RootScope::new(&mut store); // Allocate an instance of the struct type. let my_struct = StructRef::new(&mut scope, &allocator, &[Val::I32(42)])?; // That instance's field should have the expected value. let val = my_struct.field(&mut scope, 0)?.unwrap_i32(); assert_eq!(val, 42); // And we can update the field's value because it is a mutable field. my_struct.set_field(&mut scope, 0, Val::I32(36))?; let new_val = my_struct.field(&mut scope, 0)?.unwrap_i32(); assert_eq!(new_val, 36); } ``` -------------------------------- ### Example of calling a concurrent function Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/concurrent/func.rs.html?search=std%3A%3Avec Demonstrates how to get a function from an instance and call it concurrently within a store's asynchronous context. This is useful for interacting with WebAssembly functions that are designed for concurrent execution. ```rust let mut store = store.as_context_mut(); let my_func = instance.get_func(&mut store, "my_func").unwrap(); store.run_concurrent(async |accessor| -> wasmtime::Result<_> { my_func.call_concurrent(accessor, &[], &mut Vec::new()).await?; Ok(()) }).await??; ``` -------------------------------- ### HelloWorld::new Source: https://docs.rs/wasmtime/latest/src/wasmtime/opt/rustwide/target/debug/build/wasmtime-internal-component-macro-b79c1cccc3b964c2/out/hello-world0.rs.html A convenience wrapper for creating a HelloWorld instance directly from a store and an instance. It uses HelloWorldIndices internally. ```APIDOC ## HelloWorld::new ### Description A convenience wrapper for creating a HelloWorld instance directly from a store and an instance. It uses HelloWorldIndices internally. ### Method `pub fn new(mut store: impl crate::AsContextMut, instance: &crate::component::Instance) -> crate::Result` ### Parameters * `store` (*impl crate::AsContextMut*): A mutable reference to the Wasmtime store. * `instance` (*&crate::component::Instance*): A reference to the Wasmtime instance. ### Returns * `crate::Result`: A Result containing the HelloWorld instance on success, or an error if creation fails. ``` -------------------------------- ### Get Function Range by Key Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/instantiate.rs.html Retrieves the byte range (start and end offsets) for a given function key within the text section. This function is a helper for other methods that need to access function code. ```rust pub fn function_range(&self, key: FuncKey) -> Range { let loc = self.func_loc(key); let start = usize::try_from(loc.start).unwrap(); let end = usize::try_from(loc.start + loc.length).unwrap(); start..end } ``` -------------------------------- ### Getting Fixed-Size Mutable Memory Slice Source: https://docs.rs/wasmtime/latest/src/wasmtime/runtime/component/func/options.rs.html?search=std%3A%3Avec Returns a fixed mutable slice of `N` bytes starting at `offset`. Assumes `offset` has been bounds-checked by the caller. Panics if memory was not configured during canonical options specification. ```rust pub fn get(&mut self, offset: usize) -> &mut [u8; N] { // FIXME: this bounds check shouldn't actually be necessary, all // callers of `ComponentType::store` have already performed a bounds // check so we're guaranteed that `offset..offset+N` is in-bounds. That // being said we at least should do bounds checks in debug mode and // it's not clear to me how to easily structure this so that it's // "statically obvious" the bounds check isn't necessary. // // For now I figure we can leave in this bounds check and if it becomes // an issue we can optimize further later, probably with judicious use // of `unsafe`. self.as_slice_mut()[offset..].first_chunk_mut().unwrap() } ```