### Install Dependencies with npm Source: https://github.com/bytecodealliance/wasm-tools/blob/main/playground/README.md Installs project dependencies using npm. Ensure Node.js and npm are installed. ```sh npm ci ``` -------------------------------- ### Install `cargo-fuzz` Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Install the `cargo-fuzz` tool, which is required for building and running fuzzers. ```bash $ cargo install cargo-fuzz ``` -------------------------------- ### Example WebAssembly Text Module Source: https://github.com/bytecodealliance/wasm-tools/blob/main/playground/pages/parse.html This is an example of a WebAssembly text module that can be parsed into binary format. It includes imports, memory, types, start function, table, and exports. ```wast (module (import "foo" "bar" (func (param f32))) (memory (data "hi")) (type (func (param i32) (result i32))) (start 1) (table 0 1 funcref) (func) (func (type 1) i32.const 42 drop) (export "e" (func 1))) ``` -------------------------------- ### Install wasm-tools CLI Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Install the wasm-tools CLI using Cargo. Ensure Rust is installed first. ```bash $ cargo install --locked wasm-tools ``` ```bash $ cargo binstall wasm-tools ``` -------------------------------- ### Install wasm-tools CLI Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-smith/README.md Install the wasm-tools command-line interface using cargo. ```shell cargo install wasm-tools ``` -------------------------------- ### Package and Install WAVE VS Code Extension Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/contrib/vscode/README.md Instructions for packaging the extension using `vsce` and installing it into VS Code. ```bash npx vsce package code --install-extension wasm-wave-0.0.1.vsix ``` -------------------------------- ### Install `rust-bindgen` CLI Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-dylib/ffi/README.md Install the `bindgen-cli` tool to regenerate FFI bindings. Ensure you have a recent version. ```bash cargo install bindgen-cli ``` -------------------------------- ### Configure Instantiations in wasm-compose Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-compose/CONFIG.md Example demonstrating the configuration of instantiations for wasm-compose. This includes setting up arguments for instantiations and specifying dependencies for instantiations. ```yaml instantiations: root: arguments: a: b b: arguments: c: instance: d export: e d: dependency: f ``` -------------------------------- ### Serve Project Files with http-server Source: https://github.com/bytecodealliance/wasm-tools/blob/main/playground/README.md Starts a local web server to preview changes. The worker script will not load from a file:// URL, so a web server is required. ```sh npx http-server dist ``` -------------------------------- ### Install wasm-tools CLI Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-shrink/README.md Install the wasm-tools command-line interface, which includes wasm-shrink, using Cargo. ```bash $ cargo install wasm-tools ``` -------------------------------- ### Verify wasm-tools Installation Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Confirm the installation of the wasm-tools CLI by checking its version. ```bash $ wasm-tools --version ``` -------------------------------- ### Specify Dependencies in wasm-compose Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-compose/CONFIG.md Example of how to specify dependencies in the wasm-compose configuration file. It shows how to define dependencies by their path and how to import them with a specific name. ```yaml dependencies: a: a.wasm b: path: b.wasm import: b ``` -------------------------------- ### Install wasm-metadata Crate Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-metadata/README.md Add the wasm-metadata crate to your Cargo project to begin using its functionality. ```sh cargo add wasm-metadata ``` -------------------------------- ### Example WIT World Definition Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md This is an example of a WIT world definition that will be encoded into a custom section. ```wit package a:b; world foo { import host: func(); export guest: func(); } ``` -------------------------------- ### LibFuzzer Integration Example Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-mutate/README.md Integrate wasm-mutate with libFuzzer for fuzzing Wasm compilers and runtimes. This example shows how to use fuzz_target and fuzz_mutator. ```rust #![no_main] use libfuzzer_sys::{fuzz_mutator, fuzz_target}; use std::io::{BufRead, Read, Write}; use wasmparser::WasmFeatures; fuzz_target!(|bytes: &[u8]| { // Initialize the Wasm for example }); fuzz_mutator!(|data: &mut [u8], size: usize, max_size: usize, seed: u32| { // Generate a random Wasm module with `wasm-smith` as well as a RNG seed for let wasm = &data[..size]; let features = WasmFeatures::default(); let mut validator = wasmparser::Validator::new(); validator.wasm_features(features); let validation_result = validator.validate_all(&wasm); // Mutate the data if its a valid Wasm file, otherwise, create a random one let wasm = if validation_result.is_ok() { wasm.to_vec() } else { let (w, _) = match wasm_tools_fuzz::generate_valid_module_from_seed(seed, |config, u| { config.exceptions_enabled = false; config.simd_enabled = false; config.reference_types_enabled = false; config.memory64_enabled = false; config.max_memories = 1; Ok(()) }) { Ok(m) => m, Err(_) => { return size; } }; w }; let mutated_wasm = wasm_mutate::WasmMutate::default() .seed(seed.into()) .fuel(1000) .preserve_semantics(true) .run(&wasm); let mutated_wasm = match mutated_wasm { Ok(w) => w, Err(_) => wasm, }; // The mutated Wasm should still be valid, since the input Wasm was valid. let newsize = mutated_wasm.len(); data[..newsize].copy_from_slice(&mutated_wasm[..newsize]); newsize }); ``` -------------------------------- ### Non-Deduplicatable WIT Imports by Semver Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md This WIT code shows an example where imports with different semver versions are not deduplicated because they are not semver compatible. This highlights the constraints of the semver deduplication process. ```wit world { import wasi:cli/environment@0.2.0; import wasi:cli/environment@0.3.0; } ``` -------------------------------- ### Encode a WebAssembly Module in Rust Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-encoder/README.md Demonstrates how to construct and encode a simple WebAssembly module with type, function, export, and code sections using the wasm-encoder crate. This example includes a function that adds two i32 arguments. ```rust use wasm_encoder:: { CodeSection, ExportKind, ExportSection, Function, FunctionSection, Module, TypeSection, ValType, }; let mut module = Module::new(); // Encode the type section. let mut types = TypeSection::new(); let params = vec![ValType::I32, ValType::I32]; let results = vec![ValType::I32]; types.ty().function(params, results); module.section(&types); // Encode the function section. let mut functions = FunctionSection::new(); let type_index = 0; functions.function(type_index); module.section(&functions); // Encode the export section. let mut exports = ExportSection::new(); exports.export("f", ExportKind::Func, 0); module.section(&exports); // Encode the code section. let mut codes = CodeSection::new(); let locals = vec![]; let mut f = Function::new(locals); f.instructions() .local_get(0) .local_get(1) .i32_add() .end(); codes.function(&f); module.section(&codes); // Extract the encoded Wasm bytes for this module. let wasm_bytes = module.finish(); // We generated a valid Wasm module! assert!(wasmparser::validate(&wasm_bytes).is_ok()); ``` -------------------------------- ### Wasm Encoding of WIT World Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md This shows the wasm-encoded representation of the example WIT world, typically embedded in a custom section. ```wasm (component (type (;0;) (component (type (;0;) (component (type (;0;) (func)) (import "host" (func (;0;) (type 0))) (export (;1;) "guest" (func (type 0))) ) ) (export (;0;) "a:b/foo" (component (type 0))) ) ) (export (;1;) "foo" (type 0)) (@custom "package-docs" "\00{}") (@producers (processed-by "wit-component" "0.218.0") ) ) ``` -------------------------------- ### Embed wasm-shrink as a library Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-shrink/README.md Use the WasmShrink builder in Rust to programmatically configure and run a shrinking task. This example shows setting the number of attempts and providing a predicate function. ```rust use wasm_shrink::WasmShrink; // Get the Wasm you want to shrink from somewhere. let my_input_wasm: Vec = todo!(); // Configure the shrinking task. let shrink = WasmShrink::default() // Give up on shrinking after 999 failed attempts to shrink a given // Wasm test case any further. .attempts(999); // Run the configured shrinking task. let info = shrink.run( my_input_wasm, // Predicate. &mut |wasm| { let is_interesting: bool = todo!( "check for whether the given Wasm is interesting" ); Ok(is_interesting) }, // Callback called each time we find a new smallest interesting // Wasm. &mut |new_smallest| { // Optionally do something with the new smallest Wasm. Ok(()) }, )?; // Get the shrunken Wasm and other information about the completed shrink // task from the returned `ShrinkInfo`. let shrunken_wasm = info.output; ``` -------------------------------- ### Encode Function Arguments with Optional None Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Demonstrates omitting trailing 'none' optional arguments in function calls. All provided examples are equivalent. ```clike // f: func(a: option, b: option, c: option) // all equivalent: f(some(1)) f(some(1), none) f(some(1), none, none) ``` -------------------------------- ### Example Predicate Script for wasm-shrink Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-shrink/README.md A bash script that checks if a Wasm file is 'interesting' by running it with wasmtime and grepping for a specific panic message. The script exits with status 0 if the message is found, indicating an interesting Wasm file. ```bash #!/usr/bin/env bash # Exit the script if any subcommand fails. set -e # The Wasm file is given as the first and only argument to the script. WASM=$1 # Run the Wasm in Wasmtime and `grep` for our target bug's panic # message. wasmtime run $WASM 2>&1 | grep --quiet 'assertion failed: invalid stack map' ``` -------------------------------- ### Build Project with npm Source: https://github.com/bytecodealliance/wasm-tools/blob/main/playground/README.md Builds the project using npm. This command is necessary after making changes to WIT files or component implementations. ```sh npm run build ``` -------------------------------- ### Build Wasm Tools from Source (Release) Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Use this command for an optimized build of the project from source. ```bash $ cargo build --release ``` -------------------------------- ### Build Wasm Tools from Source (Debug) Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Execute this command at the root of the repository to create a debug build. The resulting binary will be located at `./target/debug/wasm-tools`. ```bash $ cargo build ``` -------------------------------- ### View wasm-tools shrink help Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-shrink/README.md Display all available options and usage information for the wasm-tools shrink command. ```bash $ wasm-tools shrink --help ``` -------------------------------- ### Print WebAssembly Module Text Format Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Convert a binary WebAssembly module to its text format and print to stdout, or specify an output file. ```bash # Print the text format of a module to stdout $ wasm-tools print foo.wasm # Convert a binary module to text $ wasm-tools print foo.wasm -o foo.wat ``` -------------------------------- ### Parse WebAssembly Text Format to Binary Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Convert a WebAssembly text format file to a binary module and save to a specified output file. ```bash # Convert a text module to binary $ wasm-tools parse foo.wat -o foo.wasm ``` -------------------------------- ### Create Component from WIT Definition Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md Generates a component binary from a `*.wit` interface definition. The `--wasm` flag indicates the output should be a WASM binary. ```sh cat demo.wit package my:demo; interface host { hello: func(); } world demo { import host; } $ wasm-tools component wit demo.wit -o demo.wasm --wasm ``` -------------------------------- ### Generate Dynamic Library from WIT World Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-dylib/README.md Use the `wasm-tools wit-dylib` command to generate a dynamic library from a WIT file. This command takes the WIT file path and an output file path as arguments. ```bash wasm-tools wit-dylib ./wit -o world.so ``` -------------------------------- ### Link Interpreter and World Libraries Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-dylib/README.md Link the generated dynamic library with an interpreter library and necessary system libraries to create a WebAssembly component. This command requires specifying the interpreter library, the world library, and potentially adaptation modules. ```bash wasm-tools component link interpreter.so world.so -o component.wasm --adapt wasi_snapshot_preview1.reactor.wasm ``` -------------------------------- ### Inspect Component WIT Interface Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Extract and print the WIT interface of a WebAssembly component. ```bash # Print the WIT interface of a component $ wasm-tools component wit component.wasm ``` -------------------------------- ### Initialize Git Submodules for Spec Tests Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Ensure the spec test suite is checked out by running this command before executing all tests. ```bash $ git submodule update --init ``` -------------------------------- ### Parse WebAssembly Text to Binary Source: https://github.com/bytecodealliance/wasm-tools/blob/main/playground/pages/parse.html Use this command to translate WebAssembly text format to binary. Ensure the input is valid WebAssembly text. ```bash wasm-tools parse ``` -------------------------------- ### Demangle, Strip, and Objdump WebAssembly Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Chain commands to demangle symbol names, strip custom sections, and display remaining binary sections. ```bash # Demangle Rust/C++ symbol names in the `name` section, strip all other custom # sections, and then print out what binary sections remain. $ wasm-tools demangle foo.wasm | wasm-tools strip | wasm-tools objdump ``` -------------------------------- ### Convert Wasm to WAT using wasmprinter Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasmprinter/README.md Demonstrates how to use wasmprinter to convert a WebAssembly binary file or byte array into the WebAssembly Text Format (WAT). Ensure the `Result` type is in scope. ```rust fn main() -> Result<()> { let foo_wat = wasmprinter::print_file("path/to/foo.wasm")?; let binary = /* ... */; let wat = wasmprinter::print_bytes(&binary)?; // ... } ``` -------------------------------- ### Print Component Details Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md Prints a human-readable representation of a WebAssembly component's structure and contents. ```bash $ wasm-tools print demo.wasm ``` -------------------------------- ### Explore wasm-tools Subcommands Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md View available subcommands for the wasm-tools CLI. ```bash $ wasm-tools help ``` -------------------------------- ### Convert Core WASM with WASI to Component Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Convert a core WebAssembly binary using WASI to a component, adapting it with a WASI reactor. ```bash # Convert a core WebAssembly binary which uses WASI to a component. $ wasm-tools component new my-core.wasm -o my-component.wasm --adapt wasi_snapshot_preview1.reactor.wasm ``` -------------------------------- ### Regenerate `ffi.rs` with `rust-bindgen` Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-dylib/ffi/README.md Use `rust-bindgen` to regenerate the `ffi.rs` file from `wit_dylib.h`. This command generates bindings, ignoring functions and layout tests. ```bash bindgen wit_dylib.h --allowlist-file wit_dylib.h --no-layout-tests --ignore-functions > ./ffi/src/ffi.rs ``` -------------------------------- ### Convert WIT Text to Binary Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Convert WIT text files to a binary-encoded WIT package, printing the result to stdout or JSON. ```bash # Convert WIT text files to a binary-encoded WIT package, printing the result to # stdout $ wasm-tools component wit ./wit -t # Convert a WIT document to JSON $ wasm-tools component wit ./wit --json ``` -------------------------------- ### Create Component from Core WASM Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md Use this command to create a WebAssembly component from an existing core WASM module. ```bash $ wasm-tools component new core.wasm -o component.wasm ``` -------------------------------- ### Run CLI Tests Suite Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Execute all tests located in the `tests/cli/*` directory. ```bash $ cargo test --test cli ``` -------------------------------- ### Convert Core WASM to Component Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Convert a core WebAssembly binary into a component. Requires prior embedding of WIT metadata. ```bash # Convert a core WebAssembly binary into a component. Note that this requires # WIT metadata having previously been embedded in the core wasm module. $ wasm-tools component new my-core.wasm -o my-component.wasm ``` -------------------------------- ### Compose WebAssembly Component Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-compose/README.md Use the `compose` command to create a composed WebAssembly component. Dependencies are automatically searched for at the input component's location. Unresolved dependencies will remain as imports. ```sh wasm-tools compose -o composed.wasm component.wasm ``` -------------------------------- ### Round Trip WIT through Binary Format Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Convert WIT to binary and back to demonstrate round-trip capability. ```bash # Round trip WIT through the binary-encoded format to stdout. $ wasm-tools component wit ./wit --wasm | wasm-tools component wit ``` -------------------------------- ### Deduplicate WIT Imports by Semver Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md This WIT code demonstrates how imports with different semver versions of the same interface are deduplicated, keeping only the highest version. This is useful for allowing libraries to evolve at different paces. ```wit world { import wasi:cli/environment@0.2.0; import wasi:cli/environment@0.2.1; } ``` ```wit world { import wasi:cli/environment@0.2.1; } ``` -------------------------------- ### Build Fuzzers Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Build the fuzzing binaries using the Nightly Rust toolchain and `cargo-fuzz`. ```bash $ cargo +nightly fuzz build ``` -------------------------------- ### Run All Workspace Tests Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Execute all tests across the entire workspace after ensuring the spec test suite is initialized. ```bash $ cargo test --workspace ``` -------------------------------- ### Add wat to Cargo.toml Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wat/README.md Add the wat crate to your project's Cargo.toml file to include it as a dependency. ```sh $ cargo add wat ``` -------------------------------- ### Run Fuzzing Binary Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Execute the combined fuzzing binary. The main driver dispatches to individual fuzzers based on input. ```bash $ cargo +nightly fuzz run run ``` -------------------------------- ### Parse WAT to WebAssembly Binary Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wat/README.md Parse WebAssembly Text Format (WAT) from a file or a string into the WebAssembly binary format using the `wat` crate. ```rust // Parse from a file ... let binary = wat::parse_file("./foo.wat")?; ``` ```rust // ... or a string let wat = r#"( module (func $foo) (func (export "bar") call $foo ) )"#; let binary = wat::parse_str(wat)? ``` -------------------------------- ### Run Spec Test Suite Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Execute all tests that are part of the spec test suite. ```bash $ cargo test --test cli -- spec ``` -------------------------------- ### Run a Single CLI Test with `cargo run` Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Execute a single test from the `tests/cli` directory using `cargo run` with the test's arguments. ```bash $ cargo run wast tests/cli/empty.wast ``` -------------------------------- ### Run wasm-tools shrink CLI Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-shrink/README.md Execute the wasm-tools shrink command with a predicate script and an input Wasm file to produce a shrunken Wasm file. ```bash $ wasm-tools shrink predicate.sh test-case.wasm -o shrunken.wasm ``` -------------------------------- ### Encode Single-Line Multiline String Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Shows how to encode a simple single-line string using the multiline string syntax in WAVE. ```python """ A single line """ ``` -------------------------------- ### Run a Single Spec Test Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Filter and run a single spec test by providing a string argument that filters on the filename. ```bash $ cargo test --test cli binary-leb128.wast ``` -------------------------------- ### Convert Core WASM with Embedded WIT to Component Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md Converts a core WASM module that has an embedded WIT component section into a full WebAssembly component. ```bash $ wasm-tools component new demo.wasm -o demo.component.wasm ``` -------------------------------- ### Test Case Reduction (WIP) Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-mutate/README.md Prototype for using wasm-mutate as a Wasm test-case reducer. This pseudo-Rust code outlines a hill-climbing algorithm for shrinking Wasm modules. ```rust let wasmmutate = wasm_mutate::WasmMutate::default() .seed(seed) .fuel(1000) .preserve_semantics(true) .reduce(true); while MAX_ITERATIONS > 0 { let new_wasm = wasmmutate.run(&wasm); wasm = if check_equivalence(new_wasm, wasm) { wasm } else{ panic!("No valid transformations") } MAX_ITERATIONS -= 1; } return wasm ``` -------------------------------- ### Add wasm-shrink as a library dependency Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-shrink/README.md Add the wasm-shrink crate to your project's dependencies in Cargo.toml. ```bash $ cargo add wasm-shrink ``` -------------------------------- ### Add Wast Crate to Cargo.toml Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wast/README.md Add the 'wast' crate to your project's dependencies using Cargo. ```sh $ cargo add wast ``` -------------------------------- ### Extract WIT Interface from Component Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md Extracts the `*.wit` interface definition from a WebAssembly component. ```bash $ wasm-tools component wit component.wasm ``` -------------------------------- ### Mutate WebAssembly Module Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Mutate a WebAssembly module and print its text representation. Supports custom seeds and validation of mutated output. ```bash # Mutate a WebAssembly module and print its text representation to stdout $ wasm-tools mutate foo.wasm -t # Mutate a WebAssembly module with a non-default seed and validate that the # output is a valid module. $ wasm-tools mutate foo.wasm --seed 192 | wasm-tools validate ``` -------------------------------- ### Mutate Wasm Binary using CLI Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-mutate/README.md Mutate a WebAssembly binary using the wasm-tools mutate command-line interface. ```bash wasm-tools mutate original.wasm --seed 0 -o out.wasm --preserve-semantics ``` -------------------------------- ### Validate WebAssembly Files Source: https://github.com/bytecodealliance/wasm-tools/blob/main/README.md Validate WebAssembly files in binary or text format. Supports enabling/disabling features. ```bash # Validate a WebAssembly file $ wasm-tools validate foo.wasm # Validate a WebAssembly module in the text format, automatically converting to # binary. $ wasm-tools validate foo.wat # Validate a WebAssembly file enabling an off-by-default feature $ wasm-tools validate foo.wasm --features=exception-handling # Validate a WebAssembly file with a default-enabled feature disabled $ wasm-tools validate foo.wasm --features=-simd ``` -------------------------------- ### Embed WIT into Core WASM Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md Embeds a WIT interface into a core WASM binary, preparing it for componentization. This is useful for toolchain authors. ```sh cat demo.core.wat (module (import "my:demo/host" "hello" (func)) ) $ wasm-tools component embed demo.wit --world demo demo.core.wat -o demo.wasm ``` -------------------------------- ### Run a Single Spec Test with `cargo run` Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Execute a single spec test using `cargo run`, potentially ignoring error messages. ```bash $ cargo run wast tests/testsuite/binary-leb128.wast --ignore-error-messages ``` -------------------------------- ### Run a Single Fuzzer Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Configure the `FUZZER` environment variable to run a specific fuzzer, such as `roundtrip`. ```bash $ FUZZER=roundtrip cargo +nightly fuzz run run ``` -------------------------------- ### Test an Individual Crate Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Run unit and integration tests for a specific crate within the repository. Replace `wasmparser` with the desired crate name. ```bash $ cargo test -p wasmparser ``` -------------------------------- ### Generate Wasm module with wasm-tools smith Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-smith/README.md Use the wasm-tools smith command to convert arbitrary input into a valid Wasm module and save it to a file. ```shell head -c 100 /dev/urandom | wasm-tools smith -o test.wasm ``` -------------------------------- ### Validate Component Binary Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md Validates a WebAssembly component binary, ensuring it conforms to the component model specification. ```bash $ wasm-tools validate --features component-model demo.wasm ``` -------------------------------- ### Encode Multiline String with Indentation Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Illustrates encoding a multiline string where indentation is determined by the ending delimiter, demonstrating how leading spaces are handled. ```python """ Indentation determined by ending delimiter """ ``` -------------------------------- ### Add wasmprinter to Cargo.toml Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasmprinter/README.md Use this command to add the wasmprinter crate as a dependency to your Rust project. ```sh cargo add wasmprinter ``` -------------------------------- ### Inspect Component Custom Sections Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-component/README.md Inspects the custom sections of a WebAssembly binary, useful for verifying the presence of the component type section after embedding. ```bash $ wasm-tools objdump demo.wasm ``` -------------------------------- ### Encode and Decode WAVE String Value Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Demonstrates encoding a WAVE string to a `Val` type and then decoding it back to a string using the `wasm-wave` library. ```rust use wasmtime::component::{Type, Val}; let val: Val = wasm_wave::from_str(&Type::String, "\"👋 Hello, world! 👋\"").unwrap(); println!("{}", wasm_wave::to_string(&val).unwrap()); ``` -------------------------------- ### Add wasm-smith to fuzz target dependencies Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-smith/README.md Add wasm-smith to your Cargo.toml file when setting up a fuzz target. ```shell cargo add wasm-smith ``` -------------------------------- ### Add wasm-encoder to Cargo.toml Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-encoder/README.md Add the wasm-encoder crate as a dependency to your Rust project using Cargo. ```sh cargo add wasm-encoder ``` -------------------------------- ### Add wasm-mutate to Cargo.toml Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-mutate/README.md Add the wasm-mutate crate to your project's dependencies using cargo. ```shell $ cargo add wasm-mutate ``` -------------------------------- ### Define a Record Type Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Define a record with required and optional fields. Optional fields with a 'none' value can be omitted during encoding. ```clike record example { must-have: u8, optional: option, } ``` -------------------------------- ### Rust Interpreter Implementation with `export!` Macro Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wit-dylib/README.md When implementing an interpreter in Rust, you would implement the `Interpreter` trait and use the `export!` macro within your interpreter's build process. This is demonstrated in the test programs within the repository. ```rust export!( default_abi, "test-programs/src/bin/simple.rs", "test-programs/src/bin/simple_caller.rs", "test-programs/src/bin/simple_callee.rs", ); ``` -------------------------------- ### Define a Record with Only Optional Fields Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Define a record where all fields are optional. If all fields are omitted, the empty record is encoded as '{:}'. ```clike record all-optional { optional: option, } ``` -------------------------------- ### Run a Specific CLI Test by Name Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Filter and run a specific test within the CLI test suite using a name filter. ```bash $ cargo test --test cli -- test_name_filter ``` -------------------------------- ### Encode a Record Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Encode a record instance. Optional fields with 'none' can be omitted. Trailing commas are permitted. ```clike → {must-have: 123} = {must-have: 123, optional: none,} ``` -------------------------------- ### Add Wast Crate Without Default Features Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wast/README.md Add the 'wast' crate to your project's dependencies without enabling default features, useful for parsing only s-expressions. ```sh $ cargo add wast --no-default-features ``` -------------------------------- ### Define a fuzz target with wasm-smith Module Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-smith/README.md Define a fuzz target that accepts wasm_smith::Module, serializes it to bytes, and feeds it into your system for testing. ```rust #!/usr/bin/env fuzz use libfuzzer_sys::fuzz_target; use wasm_smith::Module; fuzz_target!(|module: Module| { let wasm_bytes = module.to_bytes(); // Your code here... }); ``` -------------------------------- ### Encode Enum Cases Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Encode enum cases. Cases matching WAVE keywords require a '%' prefix. ```clike → %ok, not-found ``` -------------------------------- ### WAVE Multiline String EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines the structure for multiline WAVE strings, enclosed in triple double quotes. ```ebnf multiline-string ::= '"""' line-break multiline-string-line* [ ]* '"""' multiline-string-line ::= [ ]* multiline-string-char* line-break multiline-string-char ::= common-char | ['"] ``` -------------------------------- ### Encode Multiline String with Escaping Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Demonstrates encoding a multiline string that requires escaping for carriage returns at line endings and for triple double-quote sequences. ```python """ Must escape carriage return at end of line: \r Must break up double quote triplets: ""\"" """ ``` -------------------------------- ### Define a Variant Type Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Define a variant type with different cases, including cases with payloads like lists or strings. WAVE keywords must be prefixed with '%'. ```clike variant response { empty, body(list), err(string), } ``` -------------------------------- ### Define an Enum Type Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Define an enum type with simple case labels. WAVE keywords must be prefixed with '%'. ```clike enum status { ok, not-found } ``` -------------------------------- ### WAVE Finite Number EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines finite WAVE numbers, composed of an integer part, an optional fraction, and an optional exponent. ```ebnf number_finite ::= integer number-fraction? number-exponent? integer ::= unsigned-integer | '-' unsigned-integer unsigned-integer ::= '0' | [1-9] [0-9]* number-fraction ::= '.' [0-9]+ number-exponent ::= [eE] [+-]? unsigned-integer ``` -------------------------------- ### WAVE Line Break EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines the possible line break sequences in WAVE. ```ebnf line-break ::= '\r\n' | '\n' ``` -------------------------------- ### Encode Function Results - No Results Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Encode a function call with no return values. This can be represented as '()' or omitted entirely. ```clike -> () ``` -------------------------------- ### WAVE String EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines the structure for WAVE strings, enclosed in double quotes. ```ebnf string ::= '"' string-char* '"' string-char ::= common-char | ['] ``` -------------------------------- ### Encode Function Results - Multiple Named Results Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Encode a function call with multiple named results. Results are provided as a comma-separated list of label-value pairs. ```clike -> (result-a: "abc", result-b: 123) ``` -------------------------------- ### Update Test Expectations Source: https://github.com/bytecodealliance/wasm-tools/blob/main/CONTRIBUTING.md Set the `BLESS=1` environment variable when running tests to update all automatically generated expectation files. ```bash BLESS=1 cargo test ``` -------------------------------- ### WAVE Record Fields EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines the fields within a WAVE record. ```ebnf record-fields ::= ws record-field ws | record-fields ',' record-field record-field ::= label ws ':' ws value ``` -------------------------------- ### WAVE Record EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines a WAVE record, which can be empty or a sequence of fields enclosed in curly braces. ```ebnf record ::= '{' ws ':' ws '}' | '{' record-fields ','? ws '}' ``` -------------------------------- ### WAVE Number EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines the structure for WAVE numbers, including finite numbers, NaN, and infinity. ```ebnf number ::= number_finite | 'nan' | 'inf' | '-inf' ``` -------------------------------- ### Encode Option Type Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Encode an option type. 'some' values can be encoded directly if not an option or result type, otherwise use 'some(...)'. 'none' is encoded as 'none'. ```clike - `option` → `123` = `some(123)` ``` -------------------------------- ### WAVE Flags Sequence EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines a sequence of labels used in WAVE flags. ```ebnf flags-seq ::= ws label ws | flags-seq ',' label ``` -------------------------------- ### WAVE Label EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines a WAVE label, which can optionally be prefixed with '%' and consists of words separated by hyphens. ```ebnf label ::= '%'? inner-label inner-label ::= word | inner-label '-' word word ::= [a-z][a-z0-9]* | [A-Z][A-Z0-9]* ``` -------------------------------- ### WAVE Tuple EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines a WAVE tuple, which is a sequence of values enclosed in parentheses. ```ebnf tuple ::= '(' values-seq ','? ws ')' ``` -------------------------------- ### WAVE List EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines a WAVE list, which can be empty or a sequence of values enclosed in square brackets. ```ebnf list ::= '[' ws ']' | '[' values-seq ','? ws ']' ``` -------------------------------- ### Encode Function Call Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Encode a function call with a string argument. The function identifier is followed by parenthesized arguments. ```clike my-func("param") ``` -------------------------------- ### WAVE Value with Whitespace EBNF Grammar Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/wave_ebnf.md Defines a WAVE value that can optionally be surrounded by whitespace, including comments. ```ebnf value-ws ::= ws value ws ws ::= ([ \t\n\r]* comment?)* comment ::= '//' [^\n]* ``` -------------------------------- ### Encode an Empty Record Source: https://github.com/bytecodealliance/wasm-tools/blob/main/crates/wasm-wave/README.md Encode an empty record where all fields are optional and omitted. ```clike → {:} = {optional: none} ```