Hosting Modules Outside the Browser
local graph
Chapter 6 — Hosting Modules Outside the Browser
Section titled “Chapter 6 — Hosting Modules Outside the Browser”CHAPTER 6
Hosting Modules Outside the Browser
Now that you’ve learned the ins and outs of creating WebAssembly modules with the wast syntax and with Rust, and you’ve learned how a web browser provides the necessary functionality to host WebAssembly modules, it’s time to take that knowledge to the next level: Rust hosting.
At the very beginning of the book, I asked you to trust me when I told you WebAssembly was about more than just the web—it was about creating portable modules that could be slotted into all kinds of hosts, not just browsers.
In this chapter, I’ll make good on that promise and show you how to write Rust code that performs the same job as a web browser in order to host WebAssembly modules. You’ll see how to load, interpret, and execute those modules as well as how to provide callable host functions and to take advantage of functions and memory exported from a WebAssembly module. By the end of the chapter, you’ll be able to build a console application that can load checkers modules and interactively play them, all without even a hint of the Internet or a web browser.
How to Be a Good Host
So far, you’ve seen what the browser does for WebAssembly modules, and you probably have a good instinct for what tasks the browser is performing. But I haven’t yet been explicit about the things a host needs to do in order to play nice in the WebAssembly ecosystem.
WebAssembly specifies a mutual contract between the module and the host responsible for it. This contract details the things that the host must provide to the module, the things the module must provide to the host, as well as other assertions that are required to “make the magic happen.” As you’ll see, the terms of this contract are what allow WebAssembly to be so portable, and to work in or out of a web browser—a characteristic that sets this technology apart from so many of its predecessors.
To be a good host, you need to ensure that you do all of the following:
Load and Validate the wasm Binary The binary wasm file format is a well-documented specification. Any appli- cation acting as a host is responsible for loading the bytes from that file and validating that all of the preconditions for the raw format of the file are correct. This doesn’t validate behavior, only that the file itself is valid. This may seem obvious, but it has a number of important implications, including the inability for a WebAssembly module to bootstrap its own execution and thus become an attack vector.
Expose Exports Every WebAssembly module has to have at least one function export. Otherwise, the host can do nothing with it. Each host is responsible for going through the list of exported functions, linear memory, and so on, and choosing how to deal with that. For functions, the host is responsible for providing the bridge “glue” that allows a function invocation from the host to execute the appropriate function in the WebAssembly module.
Satisfy Imports In addition to exporting things for the host to use, WebAssembly modules can also import things that must be satisfied by the host, like functions and linear memory. There is some flexibility in the how and when, but every host needs to be able to validate that the demands made by the module imports can be met, and if not, providing an appropriate error to the host-based code.
Interpret (execute) the Module Once asked to invoke a WebAssembly function, the host is responsible for traversing through the list of instructions (the numeric/opcode versions of the instructions you saw when you wrote wast by hand earlier in the book), maintaining state, and handling errors. If a module has a start() function, the host needs to at least offer the option to execute that so the module can initialize itself.
Module Isolation The host is responsible for properly isolating modules. They shouldn’t be able to talk to each other or view or modify any data without going through the proper channels. There is nothing preventing a host from allowing exported memory from one module to be imported by another module. Whether or not to allow this sort of behavior is entirely up to the host. A module failure should never be able to crash another module, nor should it be possible to execute un-exported (private) functions or see private data. Now that we know the rules for being a good host, let’s go build one in Rust.
Interpreting WebAssembly Modules with Rust
Section titled “Interpreting WebAssembly Modules with Rust”If we really enjoyed punishing ourselves with loads of tedious work, we could start with the binary interface and write a parser for it. We could then write code that maintains the stack state, executes the various WebAssembly core instructions, and manages linear memory and all the other things needed for the low-level interface.
Thankfully we don’t have to do that. The creators of the wasmi¹ crate have done us a huge favor in that regard. Originally designed as a way to help Parity Tech create an ethereum client for contracts implemented in WebAssembly. Parity pulled the core pieces out of their code and made separate crates for interpreting and manipulating WebAssembly modules.
You’ll get your first exposure to this crate by accomplishing the simplest task —executing a WebAssembly function in a module that has no import needs and exports nothing but a single function. To get started, create a new binary Rust project with the following command:
$ cargo new —bin wasmi_add
This creates a new Rust project that is a standalone binary (we’ve been creating dynamic libraries for WebAssembly modules so far) that can be executed from the command line. The first step is to add a dependency on the wasmi crate to the project:
wasmi_add/Cargo.toml [package] name = “wasmi_add” version = “0.1.0” authors = [“Your Address [email protected]”]
[dependencies]wasmi = "0.4.0"Replace your default main.rs with the following code. We’ll be adding to it piece by piece as this code is probably new, even to many veteran Rust programmers. In the first section, our main() function returns a Result type. This lets us use the ? operation that will either give us the good value inside the result or return an error from the function immediately.
[1] github.com/paritytech/wasmi
The first thing you’ll do is load the WebAssembly module from the fundamentals chapter (add.wasm) into a vector of bytes (the u8 type) and create a Module from that buffer:
wasmi_add/src/main.rs
extern crate wasmi;use std::error::Error;use std::fs::File;use std::io::Read;use wasmi::{ImportsBuilder, ModuleInstance, NopExternals, RuntimeValue};
fn main() -> Result<(), Box<Error>> { let mut buffer = Vec::new(); { let mut f = File::open("../fundamentals/add.wasm")?; f.read_to_end(&mut buffer)?; } let module = wasmi::Module::from_buffer(buffer)?;}Next, we’ll create an instance of the module. You can think of this as a “running copy” of the module, which has its own state, memory, etc. As a host, the module instance is what you’ll interact with most of the time:
wasmi_add/src/main.rs
let instance = ModuleInstance::new(&module, &ImportsBuilder::default()) .expect("Failed to instantiate WASM module") .assert_no_start();This code creates a new module with a default set of imports, meaning we’re not satisfying any imports demanded by the module yet. The assert_no_start() function gives us an executable module instance that will panic if the module has a start() function. If we knew our module needed initialization, we’d call the run_start() function instead. The use of expect() is just another way of forcing a panic if we get a failing result.
Now that we’ve got a module instance, we can invoke a function. As a refresher, here’s what our add() function looked like:
(module (func $add (param $lhs i32) (param $rhs i32) (result i32) (i32.add (get_local $lhs) (get_local $rhs) ) ) (export "add" (func $add)))This code takes two i32 parameters and returns an i32 value. We execute that using the wasmi crate like so:
wasmi_add/src/main.rs
let mut args = Vec::<RuntimeValue>::new();args.push(RuntimeValue::from(42));args.push(RuntimeValue::from(1));let result: Option<RuntimeValue> = instance.invoke_export("add", &args, &mut NopExternals)?;Here you call invoke_export() with the name of the exported function. This name must match and is case-sensitive. The RuntimeValue is used as a way of converting from Rust-native data types into values that can be passed onto the WebAssembly stack as function parameters. It’s an enum, and as such, it’s incredibly easy to use pattern matching to extract results from, as shown in the rest of the code from main.rs:
wasmi_add/src/main.rs
match result { Some(RuntimeValue::I32(v)) => { println!("The answer to your addition was {}", v); } Some(_) => { println!("Got a value of an unexpected data type"); } None => { println!("Failed to get a result from wasm invocation"); }}Ok(())There are a couple of places in this code that are more verbose than they needed to be, but it helps to see how everything works in long form before taking some shortcuts. When you run this code, you should see that it performs the addition just the way you’d expect:
$ cargo runCompiling wasmi_add v0.1.0(file:///home/kevin/Code/Rust/wasmbook/khrust/Book/code/wasmi_add)Finished dev [unoptimized + debuginfo] target(s) in 1.48sRunning `target/debug/wasmi_add`The answer to your addition was 43
And just like that, you’ve created a Rust console application that hosts a WebAssembly module. Hopefully the real power of WebAssembly is starting to hit you. Because next, we’re going to build a Rust console application that can run the checkers game we wrote earlier in the book.
Building a Console Host Checkers Player
Section titled “Building a Console Host Checkers Player”As exciting as it may have been to be able to invoke the add() function in one of our earlier WebAssembly modules, eventually writing all of that low-level code is going to feel tedious. As a result, a pattern starts to emerge when we create Rust hosts for WebAssembly modules. This pattern involves:
Creating an Imports Resolver
Section titled “Creating an Imports Resolver”In wasmi terms, this is an implementation of the ModuleImportResolver trait. Its job is to provide a signature and numeric invocation index for each function imported by the module.
Creating a Runtime for Externals
Section titled “Creating a Runtime for Externals”Each time the host invokes a module function, it has to pass something that implements the Externals trait. This is typically referred to as the runtime, and it’s what allows the module to invoke imported functions.
Creating an API Wrapper for Exported Functions
Section titled “Creating an API Wrapper for Exported Functions”Manual invocations of WebAssembly module functions is tedious and just feels very clumsy and stiff compared to idiomatic Rust. So, when we are hosting a WebAssembly module, we can create a wrapper API around it for the same reason that wasm-bindgen does when it builds a JavaScript wrapper file.
We’ll be walking through each of these steps individually as we build the checkers host. But first, create a new Rust binary project called wasmi_checkers and add the wasmi dependency to it.
Resolving Imports
Section titled “Resolving Imports”Import resolution is done callback style. As the wasmi system goes through the module to create a running instance, it sifts through the list of imports in a module. For each one of those imports, it will call the resolve_func() on the import resolver that we’ve specified during the module instantiation.
This function is responsible for turning the name of the import (remember, case-sensitive) into an instance of something that can then be used for function invocation. This is the wasmi type FuncRef, which is built by supplying a function index and some metadata about the function signature. If the signature we provide as a host doesn’t match the signature defined in the module, we can return an error and stop execution.
Our checkers module had two imports that needed to be provided by the host: piecemoved and piececrowned. These imports were in the events scope or namespace. To refresh your memory, here’s the declaration of those imports from the original code:
(import "events" "piecemoved" (func $notify_piecemoved (param $fromX i32) (param $fromY i32) (param $toX i32) (param $toY i32)))(import "events" "piececrowned" (func $notify_piececrowned (param $pieceX i32) (param $pieceY i32)))To build a resolver that handles these, create a new file called imports.rs in the same directory as your main.rs. Add the following code:
wasmi_checkers/src/imports.rs
use wasmi::{ Error as InterpreterError, FuncInstance, FuncRef, ModuleImportResolver, Signature, ValueType,};pub const PIECEMOVED_INDEX: usize = 0;pub const PIECECROWNED_INDEX: usize = 1;pub struct RuntimeModuleImportResolver;impl RuntimeModuleImportResolver { pub fn new() -> RuntimeModuleImportResolver { RuntimeModuleImportResolver {} }}impl<'a> ModuleImportResolver for RuntimeModuleImportResolver { fn resolve_func( &self, field_name: &str, _signature: &Signature, ) -> Result<FuncRef, InterpreterError> { let func_ref = match field_name { "piecemoved" => FuncInstance::alloc_host( Signature::new( &[ ValueType::I32, ValueType::I32, ValueType::I32, ValueType::I32, ][..], None, ), PIECEMOVED_INDEX, ), "piececrowned" => FuncInstance::alloc_host( Signature::new(&[ValueType::I32, ValueType::I32][..], None), PIECECROWNED_INDEX, ), _ => {return Err(InterpreterError::Function(format!( "host module doesn't export function with name {}", field_name)))};Ok(func_ref)}① Provide a FuncRef for the piecemoved() function.
② Provide a FuncRef for the piececrowned() function.
③ Return an error if the module is trying to import a function we don’t know about.
Where the import resolver is all about assigning numeric indexes and metadata to imported functions, the runtime performs the actual execution, as you’ll see next.
Satisfying Externals with a Runtime
Section titled “Satisfying Externals with a Runtime”The complement to the resolve_func() function is the invoke_index() function, called on an implementation of the Externals trait. This central function operates like a dispatcher, and it’s our job to pull out the arguments, analyze the function index, and decide what to invoke and how to invoke it.
It’s a pretty good choice to have the target of your dispatch function be on the same anchor struct. That way, in case your runtime host needs to maintain its own state, it can make that state available to the functions being called by the module. This also helps ensure that data correlated to each module is isolated from other modules you might be running in memory. Add the runtime.rs file to your src directory and place the following code in it:
wasm_i_checkers/src/runtime.rs
use super::imports::{PIECECROWNED_INDEX, PIECEMOVED_INDEX};use wasmi::{Externals, RuntimeArgs, RuntimeValue, Trap};①
pub struct Runtime {}
impl Runtime { pub fn new() -> Runtime { Runtime {} }
② fn handle_piece_moved( &self, from: (i32, i32), to: (i32, i32),) -> Result<Option<RuntimeValue>, Trap> { println!( "A piece was moved from ({}, {}) to ({}, {})", from.0, from.1, to.0, to.1 ); Ok(None)}
fn handle_piece_crowned( &self, loc: (i32, i32)) -> Result<Option<RuntimeValue>, Trap> { println!("A piece was crowned at ({}, {})", loc.0, loc.1); Ok(None)}
impl Externals for Runtime { fn invoke_index( &mut self, index: usize, args: RuntimeArgs, ) -> Result<Option<RuntimeValue>, Trap> { match index { PIECECROWNED_INDEX => { let piece_x: i32 = args.nth(0); let piece_y: i32 = args.nth(1); self.handle_piece_crowned((piece_x, piece_y)) } PIECEMOVED_INDEX => { let from_x: i32 = args.nth(0); let from_y: i32 = args.nth(1); let to_x: i32 = args.nth(2); let to_y: i32 = args.nth(3); self.handle_piece_moved((from_x, from_y), (to_x, to_y)) } _ => panic!("unknown function index"), } }}① Great place to put module-specific state ② Dispatcher calls this function when appropriate ③ Dispatcher calls this function when appropriate ④ Central dispatcher, converts function index to call result
We now have a checkers runtime and a checkers import resolver. The two of these things can be encapsulated within a single checkers API that hides all of the wasmi implementation details and can even hide the presence of WebAssembly entirely. We’ll build such an API next.
Module State
Perhaps you’re wondering why we would want to maintain our own state for a module when, as we know, the module is capable of maintaining its own state via linear memory. Host state bound to a particular module comes in handy when we want to maintain data that we don’t want the module to manipulate directly.
For example, we could maintain the health or hit points of the entity controlled by a WebAssembly module, and we don’t want the module to cheat by having direct access to that state. We could also maintain a win/loss count for a checkers module, etc.
Creating the Checkers Game API
There’s one last thing to do before we can use Rust to host our checkers WebAssembly module—build an API layer. We don’t want to expose to the consumer of the checkers game all of the low-level details of how to interface with WebAssembly modules. If we wanted, we could even try to hide the existence of the wasm file itself. But in this case, we want syntax like CheckersGame::new(“/path/to/file.wasm”).
To do this, create a checkersgame.rs file in the src directory of your project. Add this initial bit of code to the file to create a function that encapsulates the logic to read the file from disk and create a module instance from it:
wasmi_checkers/src/checkersgame.rs
use std::error::Error;use std::fs::File;use std::io::prelude::*;use wasmi::{ ExternVal, ImportsBuilder, MemoryRef, Module, ModuleImportResolver, ModuleInstance, ModuleRef, RuntimeValue,};use super::imports::RuntimeModuleImportResolver;use super::runtime::Runtime;pub struct CheckersGame { runtime: Runtime, module_instance: ModuleRef,}
#[derive(Debug)]pub enum PieceColor { White, Black,}type Result
type Coordinate = (i32, i32);fn load_instance(import_resolver: &impl ModuleImportResolver, module_file: &str) -> Result<ModuleRef>{ let mut buffer = Vec::new(); let mut f = File::open(module_file)?; f.read_to_end(&mut buffer)?; let module = Module::from_buffer(buffer)?; let mut builder = ImportsBuilder::new(); builder.push_resolver("events", import_resolver);
Ok(ModuleInstance::new(&module, &builder) .expect("Failed to instantiate WASM module") .assert_no_start())}There’s a little bit of Rust generics in here, but it’s not too intimidating. The load_instance() function merely takes as its import_resolver parameter anything that can implement the ModuleImportResolver trait. We’ve already implemented that, so we’re in good shape here. Add a few more functions to the file:
wasmi_checkers/src/checkersgame.rsimpl CheckersGame { pub fn new(module_file: &str) -> CheckersGame { let resolver = RuntimeModuleImportResolver::new(); let instance = load_instance(&resolver, module_file).unwrap(); let runtime = Runtime::new();
CheckersGame { module_instance: instance, runtime, } }
pub fn init(&mut self) -> Result<()> { self.module_instance .invoke_export("initBoard", &[], &mut self.runtime)?; Ok(()) }
pub fn move_piece(&mut self, from: &Coordinate, to: &Coordinate) -> Result<bool> { let res = self.module_instance.invoke_export( "move", &[ RuntimeValue::from(from.0), RuntimeValue::from(from.1), RuntimeValue::from(to.0), RuntimeValue::from(to.1), ], &mut self.runtime, )?; Ok(res) }}match res { Some(RuntimeValue::I32(v)) => Ok(v != 0), _ => { println!("Did not get an appropriate response from move."); Ok(false) }}
pub fn get_turn_owner(&mut self) -> Result<PieceColor> { let res = self .module_instance .invoke_export("getTurnOwner", &[], &mut self.runtime)?; match res { Some(RuntimeValue::I32(v)) => { if v == 1 { Ok(PieceColor::Black) } else { Ok(PieceColor::White) } } _ => Err(From::from("Bad invocation")), }}① A wrapper for the initBoard() module function.
② Converts co-ordinate tuples into simple i32s and calls move.
③ Converts a numeric turn owner from the module to a more API-friendly enum (PieceColor).
This is great, and so far, we’ve just been providing idiomatic wrappers around the WebAssembly module functions. But I think we can do more. For one thing, we have access to the module’s raw linear memory. Since we know how that module stores the board state, we can grab the raw bytes and convert it into a way to display the game board.
Since we’re writing all the host code in Rust, we have access to some pretty cool functions, like the ability to do easy-to-read math and read and write from the module’s memory. Take a look at the code we can write to render the board contents as a string:
wasmi_checkers/src/checkersgame.rspub fn get_board_contents(&mut self) -> Result<String> { let export = self.module_instance.export_by_name("memory"); let header = r#" 0 1 2 3 4 5 6 7 .---.---.---.---.---.---.---.---."#; let footer = " `---^---^---^---^---^---^---^---'";let middle_string = match export { Some(ExternVal::Memory(mr)) => gen_board(&mr), _ => " -- no board data found -- ".to_string(),};
Ok(format!("{}\n{}\n", header, middle_string, footer))}
fn gen_board(memory: &MemoryRef) -> String { let mut vals = Vec::<String>::new();
for y in 0..8 { vals.push(format!("{} ", y)); for x in 0..8 { let offset = calc_offset(x, y); let bytevec: Vec<u8> = memory.get(offset, 4).unwrap(); let value = to_u32(&bytevec[..]);
vals.push(format!("|{}", value_label(value))); } vals.push("|\n".into()); }
vals.join("")}
fn value_label(v: u32) -> String { match v { 0 => " ", 1 => " B ", 2 => " W ", 5 => " B*", 6 => " W*", _ => "???", }.into()}
fn to_u32(bytes: &[u8]) -> u32 { bytes.iter().rev().fold(0, |acc, &b| acc * 2 + b as u32)}
fn calc_offset(x: usize, y: usize) -> u32 { ((x + y * 8) * 4) as u32}The calc_offset() function should look pretty familiar, as we implemented it earlier in the book in the checkers module in wast. Really, the only somewhat complicated piece here is pulling out strips of 4 bytes into a vector and then converting that into a 32-bit unsigned int via the to_u32() function. This version of the function that uses an accumulator and a fold is a little easier to read than some of the “shift left” techniques for coming up with the same result.
Now all we need to do is write our main() function and we should be able to play checkers with a Rust host.
Playing Checkers
Replace whatever your main.rs has with the following code:
wasm_i_checkers/src/main.rs
extern crate wasmi;mod checkersgame;mod imports;mod runtime;
use checkersgame::CheckersGame;use std::error::Error;
fn main() -> Result<(), Box<Error>> { let mut game = CheckersGame::new("../checkers/checkers.wasm"); game.init()?;
let board_display = game.get_board_contents()?; println!("game board at start:\n{}\n", board_display);
println!( "At game start, current turn is : {:?}", game.get_turn_owner()? ); game.move_piece(&(0, 5), &(0, 4))?; println!( "After first move, current turn is : {:?}", game.get_turn_owner()? );
let board_display = game.get_board_contents()?; println!("game board after 1 move:\n{}\n", board_display);
Ok(())}The ../checkers/checkers.wasm file here refers to the non-Rust, raw wast version of checkers we built earlier in the book. If you don’t want to compile your own, you can grab a copy from the book’s resource files.
Let’s run it and see what happens:
$ cargo run Compiling wasm_i_checkers v0.1.0 (file:///home/kevin/Code/Rust/wasmbook/khrust/Book/code/wasm_i_checkers) Finished dev [unoptimized + debuginfo] target(s) in 0.94s Running ‘target/debug/wasm_i_checkers’ game board at start: 0 1 2 3 4 5 6 7 0 | W | W | W | W | W | W | W | 1 | W | W | W | W | W | W | W | 2 | | | | | | | | 3 | | | | | | | | 4 | B | B | B | B | B | B | B | 5 | B | B | B | B | B | B | B | 6 | B | B | B | B | B | B | B | 7 | B | B | B | B | B | B | B |
At game start, current turn is : Black A piece was moved from (0,5) to (0,4) After first move, current turn is : White game board after 1 move: 0 1 2 3 4 5 6 7 0 | W | W | W | W | W | W | W | 1 | W | W | W | W | W | W | W | 2 | | | | | | | | 3 | | | | | | | | 4 | B | | | | | | | 5 | B | B | B | B | B | B | B | 6 | B | B | B | B | B | B | B | 7 | B | B | B | B | B | B | B |
Not only were we able to flawlessly execute all of the WebAssembly code in the module from a Rust host, but we improved the functionality by wrapping it with our own API and even added an ASCII visualization for the game board.
This same module can now be used interchangeably to play checkers in a web browser, on a console application, or on some kind of server back end, all without making a single change to the compiled wasm file. This is where WebAssembly really shines.
Wrapping Up
Section titled “Wrapping Up”You’ve now taken your WebAssembly skills to the next level. You should now have a deep understanding of how WebAssembly modules interact with their hosts, and what services the hosts provide for those modules. You’ve seen how web browsers act as hosts and the services they provide, and you’ve now built a Rust application that can host a WebAssembly module.
Now that you have been able to build this Rust WebAssembly host, it’s time to amp up the fun level a little bit. In the next chapter, you will see how WebAssembly’s portable binary modules can be used to dramatically improve the development experience with the Internet of Things.