### Complete Production Setup Example Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/configuration.md A comprehensive example demonstrating a production-ready Wasmtime-rb setup. Includes optimized engine configuration, WASI setup with arguments, environment variables, and directory mapping, along with store limits and user context. ```ruby require "wasmtime" # Engine for production: optimized compilation engine = Wasmtime::Engine.new( debug_info: false, parallel_compilation: true, cranelift_opt_level: :speed ) # WASI for sandboxed execution wasi = Wasmtime::WasiConfig.new wasi.args = ["app", "--mode", "production"] wasi.env = {"LOG_LEVEL" => "info"} wasi.map_dir("/data", "/var/wasm/data", file_perms: :all, dir_perms: :all) wasi.inherit_network = true wasi.socket_addr_check = proc do |addr, use| allowed_servers.include?(addr) && use == :tcp_connect end # Store with limits and user context store = Wasmtime::Store.new( engine, {request_id: SecureRandom.uuid, user_id: current_user.id}, wasi_config: wasi, limits: { memory_size: 256 * 1024 * 1024, # 256MB max instances: 5, tables: 2 } ) # Load module and instantiate module_bytes = File.read("app.wasm") mod = Wasmtime::Module.new(engine, module_bytes) instance = Wasmtime::Instance.new(store, mod) # Run instance.invoke("_start") ``` -------------------------------- ### Complete WASI Configuration Example Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/wasi.md Demonstrates a comprehensive setup of `WasiConfig` including arguments, environment variables, I/O inheritance, directory mapping, network inheritance, and custom socket address checking. ```ruby require "wasmtime" engine = Wasmtime::Engine.new wasi_config = Wasmtime::WasiConfig.new wasi_config.args = ["myapp", "input.txt"] wasi_config.env = {"PATH" => "/usr/bin", "USER" => "alice"} wasi_config.stdin = :inherit wasi_config.stdout = :inherit wasi_config.stderr = :inherit wasi_config.map_dir("/", "/tmp/sandbox") wasi_config.inherit_network = true wasi_config.socket_addr_check = proc do |addr, use| # Allow TCP to localhost only use == :tcp_connect && (addr.start_with?("127.0.0.1") || addr.start_with?("::1")) end store = Wasmtime::Store.new(engine, wasi_config: wasi_config) # Load and run a WASI module mod = Wasmtime::Module.from_file(engine, "program.wasm") instance = Wasmtime::Instance.new(store, mod) # Some WASI modules expect _start to be called instance.invoke("_start") if instance.export("_start") ``` -------------------------------- ### Build WASI Network Example Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/spec/fixtures/wasi-network/README.md Builds the WASI network example for WASI preview 2 and copies it to the parent directory. This command is used to update the WASI network example. ```shell cargo build --target=wasm32-wasip2 --release && \ cp target/wasm32-wasip2/release/wasi-network.wasm \ ../wasi-network-p2.wasm ``` -------------------------------- ### Basic Wasmtime Setup Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/README.md Shows the basic setup for using Wasmtime in Ruby, including creating an Engine, Store, Module, and Instance. ```ruby engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine) mod = Wasmtime::Module.new(engine, "(module)") instance = Wasmtime::Instance.new(store, mod) ``` -------------------------------- ### Install Dependencies Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/CONTRIBUTING.md Run this command to install the necessary Ruby gems for development. ```bash bundle install ``` -------------------------------- ### Example Module Imports Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/types.md An example of the output from `Module#imports`, showing a list of import hash objects. ```ruby imports = mod.imports # => [ # {"module"=>"env", "name"=>"log", "type"=>{...}}, # {"module"=>"env", "name"=>"memory", "type"=>{...}} # ] ``` -------------------------------- ### WASI Directory Mapping Examples Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/configuration.md Demonstrates various ways to map host directories into the WebAssembly filesystem with different permission levels. ```ruby wasi = Wasmtime::WasiConfig.new # Grant full access wasi.map_dir("/", "/tmp/sandbox") # Read-only wasi.map_dir("/data", "/var/data", file_perms: :read, dir_perms: :read) # Write access but not directory mutation wasi.map_dir("/temp", "/tmp", file_perms: :write, dir_perms: :read) # All operations wasi.map_dir("/work", "/home/user", file_perms: :all, dir_perms: :all) ``` -------------------------------- ### Implement WASI Support Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Guides on setting up WASI support by creating a `Wasmtime::WasiConfig`, configuring it with arguments, environment variables, and directories, and then passing it to `Store.new`. ```ruby config = Wasmtime::WasiConfig.new config.arg("my_program") config.env("MY_VAR", "value") config.push_mkdir(".") store = Wasmtime::Store.new(engine, wasi_config: config) module = Wasmtime::Module.new(engine, wasm) instance = Wasmtime::Instance.new(store, module) ``` -------------------------------- ### Full Example: Instantiating a Component with WASI Support Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/component.md Demonstrates the complete process of setting up an engine, store with WASI configuration, a component linker, adding WASI command support, and finally instantiating a simple component. ```ruby engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine, wasi_config: Wasmtime::WasiConfig.new) linker = Wasmtime::Component::Linker.new(engine) # Add WASI support Wasmtime::WasiCommand.add_to_linker(linker) component = Wasmtime::Component::Component.new(engine, "(component)") instance = linker.instantiate(store, component) ``` -------------------------------- ### Example: Trap Message Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Demonstrates how to catch a Wasmtime::Trap and print its message. This example shows a common scenario where WebAssembly code executes an unreachable instruction. ```ruby engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine) mod = Wasmtime::Module.new(engine, "(module (func (export \"bad\") (unreachable)))") instance = Wasmtime::Instance.new(store, mod) begin instance.invoke("bad") rescue Wasmtime::Trap => e puts e.message # => "wasm trap: wasm `unreachable` instruction executed" end ``` -------------------------------- ### Install wasmtime Gem Manually Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/README.md Install the wasmtime gem directly using the gem command-line tool. ```sh gem install wasmtime ``` -------------------------------- ### Implement WASI support Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Guide on integrating WebAssembly System Interface (WASI) support into your wasmtime-rb applications. ```APIDOC ## Implement WASI support ### Description This section details how to configure and utilize the WebAssembly System Interface (WASI) for running Wasm modules that require system-level capabilities like file access, network, and command-line arguments. ### Steps 1. Create a `Wasmtime::WasiConfig` object. 2. Configure the WASI environment by setting arguments, environment variables, directories, and network access as needed. 3. Pass the configured `WasiConfig` to the `Store.new` method: `Store.new(engine, wasi_config: config)`. 4. Load the WASI-enabled module and instantiate it as usual. ### Key Components - `Wasmtime::WasiConfig.new` - `WasiConfig` configuration methods (e.g., `args=`, `env=`, `dir=`, `net=`). - `Store.new(wasi_config: ...)` ``` -------------------------------- ### Basic Wasmtime-rb Usage Example Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/README.md Demonstrates creating an engine, compiling a Wasm module from WAT, defining a Ruby function for Wasm import, and instantiating and invoking the module. ```ruby require "wasmtime" # Create an engine. Generally, you only need a single engine and can # re-use it throughout your program. engine = Wasmtime::Engine.new # Compile a Wasm module from either Wasm or WAT. The compiled module is # specific to the Engine's configuration. mod = Wasmtime::Module.new(engine, <<~WAT) (module (func $hello (import "" "hello")) (func (export "run") (call $hello)) ) WAT # Create a store. Store can keep state to be re-used in Funcs. store = Wasmtime::Store.new(engine, {count: 0}) # Define a Wasm function from Ruby code. func = Wasmtime::Func.new(store, [], []) do |caller| puts "Hello from Func!" caller.store_data[:count] += 1 puts "Ran #{caller.store_data[:count]} time(s)" end # Build the Wasm instance by providing its imports. instance = Wasmtime::Instance.new(store, mod, [func]) # Run the `run` export. instance.invoke("run") # Or: get the `run` export and call it. instance.export("run").to_func.call ``` -------------------------------- ### Memory-Limited Configuration Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/configuration.md Configure the Wasmtime engine with a specific maximum WebAssembly stack size, set to 512KB in this example. ```ruby engine = Wasmtime::Engine.new( max_wasm_stack: 512 * 1024 # 512KB stack ) ``` -------------------------------- ### Start Background Epoch Interval Timer Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/engine.md Starts a background timer that increments the engine's epoch at regular intervals. If a prior timer was running, it is stopped first. This is useful for preventing infinite loops in WebAssembly execution. ```ruby engine = Wasmtime::Engine.new(epoch_interruption: true) store = Wasmtime::Store.new(engine) # Increment epoch every 100ms in the background engine.start_epoch_interval(100) # Create a module with an infinite loop mod = Wasmtime::Module.new(engine, "(module (func (export \"infinite\") (block (loop (br 0)))))") instance = Wasmtime::Instance.new(store, mod) # This will trap after approximately 100ms due to epoch interruption begin instance.invoke("infinite") rescue Wasmtime::Trap => e puts "Interrupted: #{e.message}" end ``` -------------------------------- ### Pre-fork Server Engine Setup Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/engine.md Illustrates a pattern for pre-forking servers where parallel compilation is disabled before forking to prevent deadlocks. It's then re-enabled in child processes after forking. ```ruby # Many Ruby servers use pre-forking. Disable parallel compilation # before forking to avoid deadlocks, then enable it in child processes. prefork_engine = Wasmtime::Engine.new(parallel_compilation: false) wasm_module = Wasmtime::Module.new(prefork_engine, "(module)") fork do # Enable parallel compilation now that we've forked engine = Wasmtime::Engine.new(parallel_compilation: true) store = Wasmtime::Store.new(engine) instance = Wasmtime::Instance.new(store, wasm_module) end ``` -------------------------------- ### Example Error Message Format Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/errors.md Illustrates the typical structure of an error message, including the operation, reason, and context. ```text Could not build module: invalid instruction at offset 42 in function 0 ``` -------------------------------- ### Example: Trap Code Handling Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Illustrates how to use a case statement to handle different WebAssembly trap codes. This provides a structured way to respond to specific types of errors. ```ruby begin instance.invoke("bad_operation") rescue Wasmtime::Trap => e case e.code when :STACK_OVERFLOW puts "Stack overflow" when :MEMORY_OUT_OF_BOUNDS puts "Memory access out of bounds" when :UNREACHABLE_CODE_REACHED puts "Unreachable code executed" else puts "Unknown trap: #{e.code}" end end ``` -------------------------------- ### Wasmtime-rb Memory Example Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/memory.md Demonstrates creating a Wasm module with memory, instantiating it, and interacting with the memory from Ruby. Shows writing and reading integers and raw bytes, and calling Wasm functions that access memory. ```ruby engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine) # Module that exports memory mod = Wasmtime::Module.new(engine, <<~WAT) (module (memory (export "memory") 1) (func (export "store_number") (param i32) (i32.store (i32.const 0) (local.get 0))) (func (export "load_number") (result i32) (i32.load (i32.const 0)))) WAT instance = Wasmtime::Instance.new(store, mod) # Access memory from Ruby memory = instance.export("memory").to_memory memory.write_i32(0, 42) puts memory.read_i32(0) # => 42 # Call Wasm function to verify instance.invoke("store_number", 100) puts instance.invoke("load_number") # => 100 # Read as raw bytes memory.write(50, "Hello") text = memory.read_utf8(50, 5) puts text # => "Hello" ``` -------------------------------- ### Build Wasm Component Fixture Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/spec/fixtures/component-types/README.md Builds the Wasm component fixture using cargo-component. Ensure cargo-component is installed. ```bash ( cd spec/fixtures/component-types && \ cargo component build --release && \ cp target/wasm32-unknown-unknown/release/component_types.wasm ../ ) ``` -------------------------------- ### Lock Bundle to Supported Platforms Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/README.md Inform Bundler about the target platforms for precompiled gems to ensure correct installation. ```sh bundle lock --add-platform x86_64-linux # Standard Linux (e.g. Heroku, GitHub Actions, etc.) bundle lock --add-platform x86_64-linux-musl # MUSL Linux deployments (i.e. Alpine Linux) bundle lock --add-platform aarch64-linux # ARM64 Linux deployments (i.e. AWS Graviton2) bundle lock --add-platform x86_64-darwin # Intel MacOS (i.e. pre-M1) bundle lock --add-platform arm64-darwin # Apple Silicon MacOS (i.e. M1) ``` -------------------------------- ### Update WASI Deterministic Program Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/spec/fixtures/wasi-deterministic/README.md This command builds a WASI program in release mode, optimizes it using wasm-opt, and copies the compiled WASM files for WASI Preview 1 and Preview 2 to the parent directory. Ensure you have `wasm-opt` installed and the necessary Rust toolchains. ```shell cargo build --release && \ wasm-opt -O \ --enable-bulk-memory \ target/wasm32-wasip1/release/wasi-deterministic.wasm \ -o ../wasi-deterministic.wasm && \ cargo build --target=wasm32-wasip2 --release && \ cp target/wasm32-wasip2/release/wasi-deterministic.wasm \ ../wasi-deterministic-p2.wasm ``` -------------------------------- ### Configuring and Using WASI with Wasmtime-rb Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/README.md Illustrates how to set up WASI configuration, including command-line arguments, environment variables, and directory mappings, before loading and running a WASI-enabled WebAssembly module. ```ruby # Create WASI configuration wasi = Wasmtime::WasiConfig.new wasi.args = ["myapp", "arg1"] wasi.env = {"USER" => "alice"} wasi.map_dir("/", "/tmp/sandbox") # Create store with WASI store = Wasmtime::Store.new(engine, wasi_config: wasi) # Load and run a WASI module mod = Wasmtime::Module.from_file(engine, "program.wasm") instance = Wasmtime::Instance.new(store, mod) instance.invoke("_start") # WASI entry point ``` -------------------------------- ### Instantiation Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Methods for creating stores, instantiating modules, and setting up linkers for imports and exports. ```APIDOC ## Instantiation ### Description Covers the process of creating execution contexts (stores) and bringing WebAssembly modules to life as runnable instances, including the use of linkers for managing imports and exports. ### Methods - `Store.new(engine, ...)` — Create a new store for executing Wasm modules. - `Instance.new(store, module, ...)` — Instantiate a module within a store. - `Linker.new(engine)` — Create a new linker for managing imports and exports. - `Linker.instantiate(linker, module)` — Instantiate a module using a linker. - `Component::Linker.instantiate(linker, component)` — Instantiate a WebAssembly component using a component linker. ``` -------------------------------- ### Initialize Default and Custom Engines Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/engine.md Demonstrates creating a default engine and an engine with specific configuration options like enabling debug info, disabling parallel compilation, and enabling fuel consumption. ```ruby # Default engine engine = Wasmtime::Engine.new # Engine with custom configuration engine = Wasmtime::Engine.new( debug_info: true, parallel_compilation: false, # For pre-fork servers consume_fuel: true ) ``` -------------------------------- ### Get Global Value Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md The `#get` method retrieves the current value stored in a global variable. This can be called on both constant and mutable globals. ```ruby counter = Wasmtime::Global.var(store, :i32, 0) puts counter.get # => 0 ``` -------------------------------- ### Global#get Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Retrieves the current value of a global variable. ```APIDOC ## Global#get ### Description Gets the current value of the global. ### Method Signature ```ruby global.get ``` ### Returns - `Object` - The global's current value. ### Example ```ruby counter = Wasmtime::Global.var(store, :i32, 0) puts counter.get # => 0 ``` ``` -------------------------------- ### Create and run a simple module Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md This snippet outlines the basic steps to create an engine, compile a WebAssembly module, instantiate it, and invoke a function. ```APIDOC ## Create and run a simple module ### Description This sequence demonstrates the fundamental workflow for interacting with WebAssembly modules using wasmtime-rb, from engine creation to function invocation. ### Methods - `Wasmtime::Engine.new` - `Wasmtime::Module.new(engine, wasm)` - `Wasmtime::Store.new(engine)` - `Wasmtime::Instance.new(store, module)` - `instance.invoke(name, *args)` ### Usage Example ```ruby # 1. Create engine engine = Wasmtime::Engine.new # 2. Compile module (assuming 'wasm' is your Wasm binary data) module = Wasmtime::Module.new(engine, wasm) # 3. Create store store = Wasmtime::Store.new(engine) # 4. Instantiate instance = Wasmtime::Instance.new(store, module) # 5. Call function (assuming a function named 'my_function' exists) result = instance.invoke("my_function", arg1, arg2) ``` ``` -------------------------------- ### Table#get Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Retrieves the element at a specific index within the table. ```APIDOC ## Table#get ### Description Returns the element at the given index, or nil if out of bounds. ### Method `table.get(index)` ### Parameters #### Arguments - **index** (Integer) - Required - Element index ### Returns `Object | nil` ``` -------------------------------- ### Create and Instantiate a Component Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Create a WebAssembly component using `Component::Component.new` and instantiate it using `Component::Linker.instantiate`. ```ruby engine = Wasmtime::Engine.new component_bytes = "..." component = Wasmtime::Component::Component.new(engine, component_bytes) linker = Wasmtime::Component::Linker.new(engine) instance = linker.instantiate(component) ``` -------------------------------- ### Get Minimum Memory Size Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/memory.md Retrieves the minimum size of the Wasmtime memory in pages. ```ruby memory = Wasmtime::Memory.new(store, min_size: 2) puts memory.min_size # => 2 ``` -------------------------------- ### Instantiating a WebAssembly Module Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/README.md Demonstrates how to instantiate a compiled WebAssembly Module within a specific Store, optionally providing necessary imports. ```ruby instance = Wasmtime::Instance.new(store, module, imports) ``` -------------------------------- ### Get Table Size Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Retrieve the current number of elements in the table using `table.size`. ```ruby table.size ``` -------------------------------- ### Get Error Message Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Retrieve the general error message from a caught `Wasmtime::Error` exception. ```ruby begin # ... code that might error ... rescue Wasmtime::Error => e puts "Error: #{e.message}" end ``` -------------------------------- ### Wasmtime Instance Lifecycle Management Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/instance.md Demonstrates how instances are tied to their store. If the store is garbage collected, using the instance may lead to errors. ```ruby def create_instance engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine) # Scope-local store mod = Wasmtime::Module.new(engine, "(module (func (export \"run\")))") Wasmtime::Instance.new(store, mod) end instance = create_instance # store is now garbage collected begin instance.invoke("run") # May fail - store was collected rescue => e puts "Error: #{e.message}" end ``` -------------------------------- ### Get FuncType Result Types Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/func.md Returns result types for this function type as an Array of symbols. ```ruby func_type.results ``` -------------------------------- ### Troubleshooting: Missing WASI Configuration Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/errors.md Use this when the 'Store is missing WASI configuration'. Ensure WASI is configured by passing `wasi_config:` to `Store.new`. ```text Store is missing WASI configuration ``` -------------------------------- ### Get FuncType Parameter Types Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/func.md Returns parameter types for this function type as an Array of symbols. ```ruby func_type.params ``` -------------------------------- ### Configuring Wasmtime Engine Options Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/README.md Demonstrates how to create a Wasmtime engine with specific configuration options, such as enabling parallel compilation and debug information. ```ruby engine = Wasmtime::Engine.new( parallel_compilation: true, debug_info: true ) ``` -------------------------------- ### Get remaining fuel from a Wasmtime::Store Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/store.md Returns the current amount of fuel remaining in the store. ```ruby engine = Wasmtime::Engine.new(consume_fuel: true) store = Wasmtime::Store.new(engine) store.set_fuel(5000) remaining = store.get_fuel # => 5000 ``` -------------------------------- ### Basic WebAssembly Module Execution in Ruby Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/README.md Demonstrates how to compile a WebAssembly module from text format, instantiate it, and invoke an exported function using Wasmtime-rb. ```ruby require "wasmtime" # Create an engine engine = Wasmtime::Engine.new # Create a module from WebAssembly text format mod = Wasmtime::Module.new(engine, <<~WAT) (module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)) WAT # Create a store store = Wasmtime::Store.new(engine) # Instantiate the module instance = Wasmtime::Instance.new(store, mod) # Call an exported function result = instance.invoke("add", 5, 3) puts result # => 8 ``` -------------------------------- ### Basic Store Configuration Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/configuration.md Configure a Wasmtime::Store with optional WASI configurations and resource limits. ```ruby store = Wasmtime::Store.new( engine, user_data, # Optional: arbitrary user data wasi_config: config, # Optional: WASI configuration wasi_p1_config: config, # Optional: WASI P1 configuration limits: { # Optional: resource limits memory_size: 1024 * 1024, instances: 10 } ) ``` -------------------------------- ### Instance Lifecycle Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/instance.md Understanding how instances are managed and their relationship with stores. ```APIDOC ## Instance lifecycle ### Description Instances hold references to their store and module. When the store is garbage collected, all instances from that store are invalidated. Attempting to use a store or instance after its store has been garbage collected will raise an error. ### Example ```ruby def create_instance engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine) # Scope-local store mod = Wasmtime::Module.new(engine, "(module (func (export \"run\")))") Wasmtime::Instance.new(store, mod) end instance = create_instance # store is now garbage collected begin instance.invoke("run") # May fail - store was collected rescue => e puts "Error: #{e.message}" end ``` ``` -------------------------------- ### Configure Resource Limits (Memory and Fuel) Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/README.md Illustrates setting resource limits for Wasmtime stores, including memory size and fuel consumption. Fuel consumption requires enabling it on the engine. ```ruby # Memory limit store = Wasmtime::Store.new(engine, limits: {memory_size: 1024 * 1024}) # Fuel limit engine = Wasmtime::Engine.new(consume_fuel: true) store.set_fuel(10000) ``` -------------------------------- ### Component.new Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/component.md Creates a new Wasmtime::Component::Component by compiling WAT or Wasm component binary data provided as a string. ```APIDOC ## Component.new ### Description Creates a new component by compiling WAT or Wasm component binary. ### Method `Wasmtime::Component::Component.new(engine, wat_or_wasm)` ### Parameters #### Path Parameters - **engine** (Wasmtime::Engine) - Required - The engine to compile with - **wat_or_wasm** (String) - Required - WAT or Wasm component binary ### Returns `Wasmtime::Component::Component` ### Example ```ruby engine = Wasmtime::Engine.new component = Wasmtime::Component::Component.new(engine, "(component)") ``` ``` -------------------------------- ### Get Single Instance Export Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Retrieve a specific exported item from a Wasm instance by its name using `instance.export`. ```ruby memory_export = instance.export("memory") func_export = instance.export("my_function") ``` -------------------------------- ### Create and Run a Simple Wasm Module Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Steps to create a Wasmtime engine, compile a module, create a store, instantiate the module, and invoke an exported function. Ensure the Wasm binary is available. ```ruby engine = Wasmtime::Engine.new wasm = "..." module = Wasmtime::Module.new(engine, wasm) store = Wasmtime::Store.new(engine) instance = Wasmtime::Instance.new(store, module) instance.invoke("my_function", arg1, arg2) ``` -------------------------------- ### Stop Background Epoch Interval Timer Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/engine.md Stops a previously started timer from `start_epoch_interval`. Does nothing if no timer is running. ```ruby engine.stop_epoch_interval ``` -------------------------------- ### Create and Configure WASI Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/configuration.md Initializes WASI configuration, sets arguments, environment variables, standard I/O streams, maps directories, and enables network access. This configuration is then used to create a Wasmtime store. ```ruby wasi = Wasmtime::WasiConfig.new wasi.args = ["program_name", "arg1", "arg2"] wasi.env = {"HOME" => "/home/user", "PATH" => "/usr/bin"} wasi.stdin = :inherit # or "/path/to/file" or "string data" wasi.stdout = :inherit # or "/path/to/file" wasi.stderr = :inherit # or "/path/to/file" wasi.map_dir("/data", "/var/data") wasi.inherit_network = true wasi.allow_tcp = true wasi.allow_udp = true wasi.allow_ip_name_lookup = true store = Wasmtime::Store.new(engine, wasi_config: wasi) ``` -------------------------------- ### Wasmtime::Global Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Represents a global variable, which can be either constant or mutable. It allows creating, getting, and setting global values. ```APIDOC ## Class Wasmtime::Global ### Description Global variable (constant or mutable). ### Methods - `const(store, type, default)` — Create constant global - `var(store, type, default)` — Create mutable global - `get` — Get current value - `set(value)` — Set value (mutable only) - `const?` — Is constant? - `var?` — Is mutable? - `type` — Get value type ### Related `Wasmtime::GlobalType` ``` -------------------------------- ### Get Maximum Memory Size Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/memory.md Retrieves the maximum size of the Wasmtime memory in pages. Returns nil if the memory is unlimited. ```ruby unlimited = Wasmtime::Memory.new(store, min_size: 1) puts unlimited.max_size # => nil limited = Wasmtime::Memory.new(store, min_size: 1, max_size: 100) puts limited.max_size # => 100 ``` -------------------------------- ### Creating a Wasmtime Store with User Data Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/README.md Explains how to create a Wasmtime Store, associating it with an engine and optionally providing user-defined data that can be accessed from host functions. ```ruby store = Wasmtime::Store.new(engine, user_data) ``` -------------------------------- ### Get Element from Table Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Access an element at a specific index using `table.get(index)`. Returns `nil` if the index is out of bounds. ```ruby table.get(index) ``` -------------------------------- ### Create Component from WAT or Wasm Binary Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/component.md Use this method to create a component by compiling either WebAssembly Text Format (WAT) or a Wasm component binary. Requires an initialized Wasmtime::Engine. ```ruby engine = Wasmtime::Engine.new component = Wasmtime::Component::Component.new(engine, "(component)") ``` -------------------------------- ### Caller Lifetime Example Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/caller.md Demonstrates that the Caller object is only valid during function execution. Attempting to use it after the function returns raises an error. ```ruby saved_caller = nil func = Wasmtime::Func.new(store, [], []) do |caller| saved_caller = caller end mod = Wasmtime::Module.new(engine, "(module (func (export \"test\")))") instance = Wasmtime::Instance.new(store, mod, [func]) instance.invoke("test") # This will raise an error - caller has expired begin saved_caller.store_data rescue Wasmtime::Error => e puts "Error: #{e.message}" # "Caller outlived its Func execution" end ``` -------------------------------- ### Create Component from File Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/component.md Loads and compiles a component from a specified file path. Supports both .wasm and .wat component file formats. An engine is required for compilation. ```ruby engine = Wasmtime::Engine.new component = Wasmtime::Component::Component.from_file(engine, "components/app.wasm") ``` -------------------------------- ### Generate Changelog Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/CONTRIBUTING.md Use this script to automatically generate the project's changelog. Ensure you have the 'github_changelog_generator' gem installed and are authenticated with 'gh'. ```bash ./scripts/generate-changelog.sh ``` -------------------------------- ### Get Trap Message Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Retrieves a string describing the WebAssembly trap. This is useful for logging or displaying detailed error information to the user. ```ruby trap.message ``` -------------------------------- ### Get Global Type Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md The `#type` method returns the WebAssembly type of the global variable as a symbol (e.g., `:i32`, `:f64`, `:externref`). ```ruby global.type ``` -------------------------------- ### Compile Module from File Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Load and compile a WebAssembly module directly from a file path using `Wasmtime::Module.from_file`. ```ruby engine = Wasmtime::Engine.new module = Wasmtime::Module.from_file(engine, "path/to/module.wasm") ``` -------------------------------- ### Module.new Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/module.md Creates a new Wasmtime::Module by compiling WebAssembly Text format (WAT) or binary (Wasm). ```APIDOC ## Module.new ### Description Creates a new module by compiling WAT (WebAssembly Text format) or Wasm binary. ### Method `Wasmtime::Module.new(engine, wat_or_wasm)` ### Parameters #### Path Parameters - **engine** (Wasmtime::Engine) - Required - The engine to compile with - **wat_or_wasm** (String) - Required - WAT source code or raw Wasm binary ### Request Example ```ruby engine = Wasmtime::Engine.new # Create from WAT mod = Wasmtime::Module.new(engine, <<~WAT) (module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)) WAT # Create from binary wasm_bytes = File.read("program.wasm") mod = Wasmtime::Module.new(engine, wasm_bytes) ``` ### Returns `Wasmtime::Module` ``` -------------------------------- ### Get Store Data with Caller#store_data Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/caller.md Retrieves the user data associated with the store. This is the data object originally passed to `Store.new`. ```ruby caller.store_data ``` ```ruby engine = Wasmtime::Engine.new store_data = {request_id: 123, user_id: 456} store = Wasmtime::Store.new(engine, store_data) func = Wasmtime::Func.new(store, [], [:i32]) do |caller| data = caller.store_data puts "Request: #{data[:request_id]}, User: #{data[:user_id]}" data[:user_id] end mod = Wasmtime::Module.new(engine, <<~WAT) (module (func $get_user (import "" "get_user") (result i32)) (func (export "main") (result i32) (call $get_user))) WAT instance = Wasmtime::Instance.new(store, mod, [func]) user_id = instance.invoke("main") puts user_id # => 456 ``` -------------------------------- ### Creating and Calling Host Functions in Ruby Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/README.md Illustrates how to define a host function in Ruby that can be called from WebAssembly, and how to retrieve and call an exported Wasm function from Ruby. ```ruby # Host function func = Wasmtime::Func.new(store, [:i32], []) { |caller, x| x * 2 } # Wasm function (from instance) func = instance.export("add").to_func result = func.call(5, 3) ``` -------------------------------- ### Get Function Result Types with Func#results Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/func.md Returns an Array of symbols representing the result types of a function. This is useful for introspection. ```ruby func.results ``` ```ruby func = Wasmtime::Func.new(store, [:i32], [:i32, :i32]) do |caller, a| [a, a * 2] end puts func.results # => [:i32, :i32] ``` -------------------------------- ### Get Function Parameter Types with Func#params Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/func.md Returns an Array of symbols representing the parameter types of a function. This is useful for introspection. ```ruby func.params ``` ```ruby func = Wasmtime::Func.new(store, [:i32, :i64, :f32], [:i32]) do |caller, a, b, c| a end puts func.params # => [:i32, :i64, :f32] ``` -------------------------------- ### WASI Preview 1 Configuration (Deprecated) Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/wasi.md Configure WASI Preview 1 modules using `wasi_p1_config` for compatibility with older WASI versions. ```ruby wasi_p1_config = Wasmtime::WasiConfig.new wasi_p1_config.args = ["program"] store = Wasmtime::Store.new(engine, wasi_p1_config: wasi_p1_config) ``` -------------------------------- ### Get all exports from an instance Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/instance.md Retrieves all exports from an instance as a hash. Keys are export names, and values are the corresponding Wasmtime::Extern objects. ```ruby instance.exports ``` ```ruby engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine) mod = Wasmtime::Module.new(engine, <<~WAT) (module (memory (export \"memory\") 1) (func (export \"get_number\") (result i32) (i32.const 42)) (global (export \"counter\") (mut i32) (i32.const 0))) WAT instance = Wasmtime::Instance.new(store, mod) exports = instance.exports puts exports.keys # => ["memory", "get_number", "counter"] # Access individual exports memory = exports["memory"] func = exports["get_number"] global = exports["counter"] ``` -------------------------------- ### Memory#read Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/memory.md Reads a specified number of bytes from memory starting at a given offset. The data is returned as a binary (ASCII-8BIT) string. ```APIDOC ## Memory#read ### Description Reads bytes from memory at the given offset. Returns a binary (ASCII-8BIT) string. ### Method `memory.read(offset, size)` ### Parameters #### Path Parameters - **offset** (Integer) - Required - Starting byte offset - **size** (Integer) - Required - Number of bytes to read ### Response #### Success Response - **String** - Binary string containing the read bytes ### Raises - `Wasmtime::Error` if offset/size is out of bounds ### Example ```ruby memory = instance.export("memory").to_memory # Read 4 bytes from offset 0 data = memory.read(0, 4) puts data.bytes # => [10, 20, 30, 40] ``` ``` -------------------------------- ### Component.from_file Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/component.md Creates a Wasmtime::Component::Component by loading and compiling a component from a specified file path. ```APIDOC ## Component.from_file ### Description Creates a component by loading and compiling a file. ### Method `Wasmtime::Component::Component.from_file(engine, path)` ### Parameters #### Path Parameters - **engine** (Wasmtime::Engine) - Required - The engine to compile with - **path** (String) - Required - Path to .wasm or .wat component file ### Returns `Wasmtime::Component::Component` ### Example ```ruby engine = Wasmtime::Engine.new component = Wasmtime::Component::Component.from_file(engine, "components/app.wasm") ``` ``` -------------------------------- ### Wasmtime::Component::Linker#instantiate Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/component.md Instantiates a WebAssembly component, linking its imports with the provided store and linker configuration. ```APIDOC ## Wasmtime::Component::Linker#instantiate ### Description Instantiates a component with linked imports. ### Method `linker.instantiate(store, component)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **store** (Wasmtime::Store) - Required - Store for the instance - **component** (Wasmtime::Component::Component) - Required - Component to instantiate ### Returns `Wasmtime::Component::Instance` ``` -------------------------------- ### Engine#stop_epoch_interval Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/engine.md Stops a previously started timer from `start_epoch_interval`. This method is only available when the Tokio feature is enabled. It does nothing if no timer is running. ```APIDOC ## Engine#stop_epoch_interval (Tokio feature only) ### Description Stops a previously started timer from `start_epoch_interval`. Does nothing if no timer is running. ### Returns `nil` ``` -------------------------------- ### Wasmtime::Instance.new Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/instance.md Creates a new WebAssembly instance by instantiating a module with provided imports. ```APIDOC ## Wasmtime::Instance.new ### Description Creates a new WebAssembly instance by instantiating a module with provided imports. ### Method `Wasmtime::Instance.new(store, module, imports = [])` ### Parameters #### Path Parameters - **store** (Wasmtime::Store) - Required - The store in which to instantiate - **module** (Wasmtime::Module) - Required - The module to instantiate - **imports** (Array) - Optional - Import items in declaration order ### Returns `Wasmtime::Instance` ### Example ```ruby engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine) # Module with no imports simple_mod = Wasmtime::Module.new(engine, "(module (func (export \"run\")))") instance = Wasmtime::Instance.new(store, simple_mod) # Module with imports mod_with_imports = Wasmtime::Module.new(engine, <<~WAT) (module (func $log (import "" "log") (param i32)) (func (export "run") (call $log (i32.const 42)))) WAT log_func = Wasmtime::Func.new(store, [:i32], []) do |caller, value| puts "Log: #{value}" end instance = Wasmtime::Instance.new(store, mod_with_imports, [log_func]) instance.invoke("run") ``` ``` -------------------------------- ### Get Trap Code and Message Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Extract the specific trap code (e.g., `:OUT_OF_FUEL`) and a descriptive message from a caught `Wasmtime::Trap` exception. ```ruby begin # ... code that might trap ... rescue Wasmtime::Trap => e puts "Trap Code: #{e.code}" puts "Trap Message: #{e.message}" end ``` -------------------------------- ### Compile and Test Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/CONTRIBUTING.md Execute this command to compile the gem, run all tests, and perform a Ruby linting check. ```bash bundle exec rake ``` -------------------------------- ### Get a single export by name Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/instance.md Retrieves a specific export from an instance by its name. Returns the Wasmtime::Extern object or nil if the export is not found. ```ruby instance.export(name) ``` ```ruby instance = # ... create instance ... # Get function export add_func = instance.export("add") result = add_func.to_func.call(5, 3) if add_func # Get memory export memory = instance.export("memory") if memory data = memory.to_memory.read(0, 10) end # Handle missing exports unless instance.export("does_not_exist") puts "Export not found" end ``` -------------------------------- ### Configuration Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/INDEX.md Options for configuring the Wasmtime engine, store, and WASI environment. ```APIDOC ## Configuration ### Description Details the various configuration options available for customizing the behavior of the Wasmtime engine, stores, and the WASI system interface. ### Configuration Options - `Engine.new(config)` — Configure engine-level settings. - `Store.new(engine, data, limits: ...)` — Configure store-specific data and limits. - `WasiConfig.new` — Create and configure WASI settings (arguments, environment, etc.). ``` -------------------------------- ### Lookup Defined Item - Linker#get Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/linker.md Looks up a previously defined item in the linker. This is useful for retrieving imported functions or other externals that have been registered with the linker. ```ruby linker.func_new("env", "log", [:i32], []) { |c, v| puts v } extern = linker.get(store, "env", "log") func = extern.to_func func.call(42) ``` -------------------------------- ### Troubleshooting: Function Not Found Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/errors.md Use this when encountering 'function "X" not found'. Ensure the export name in the module source is correct. ```text function "X" not found ``` -------------------------------- ### Get Module Imports Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/module.md Retrieves information about all imports required by the module. Each import is represented as a hash containing its module name, item name, and type. ```ruby engine = Wasmtime::Engine.new mod = Wasmtime::Module.new(engine, <<~WAT) (module (func $log (import "env" "log") (param i32)) (memory (import "env" "memory") 1) (func (export "main") (call $log (i32.const 42)))) WAT imports = mod.imports # => [ # {"module"=>"env", "name"=>"log", "type"=>{...func type...}}, # {"module"=>"env", "name"=>"memory", "type"=>{...memory type...}} # ] imports.each do |import| puts "#{import['module']}.#{import['name']}: #{import['type']}" end ``` -------------------------------- ### Get Wasm Backtrace Message Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Retrieves a textual representation of the WebAssembly backtrace, if available. This is helpful for debugging complex execution flows within WebAssembly modules. ```ruby trap.wasm_backtrace_message ``` -------------------------------- ### Instance#invoke Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/instance.md Retrieves and calls a WebAssembly function export by name, passing the given arguments. ```APIDOC ## Instance#invoke ### Description Retrieves and calls a WebAssembly function export by name, passing the given arguments. ### Method `instance.invoke(name, *args)` ### Parameters #### Path Parameters - **name** (String) - Required - Name of the exported function - **args** (Object) - Optional - Arguments to pass to the function ### Returns Depends on function signature: - 0 results: `nil` - 1 result: Single value - 2+ results: `Array` of values ### Raises `Wasmtime::Error` if the function is not found or execution fails ### Example ```ruby engine = Wasmtime::Engine.new store = Wasmtime::Store.new(engine) mod = Wasmtime::Module.new(engine, <<~WAT) (module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add) (func (export "swap") (param i32 i32) (result i32 i32) local.get 1 local.get 0)) WAT instance = Wasmtime::Instance.new(store, mod) # Single result sum = instance.invoke("add", 5, 3) puts sum # => 8 # Multiple results a, b = instance.invoke("swap", 10, 20) puts "#{a}, #{b}" # => 20, 10 ``` ``` -------------------------------- ### Get Trap Code Source: https://github.com/bytecodealliance/wasmtime-rb/blob/main/_autodocs/api-reference/global_table_trap.md Retrieves the trap code as a symbol. This allows for programmatic handling of different trap types. Returns nil if the trap did not originate from WebAssembly. ```ruby trap.code ```