WebAssembly
editThe WebAssembly API of the scripts is available when the browsing context has a WebAssembly runtime. The Meziantou.Framework.WebPlatform.Wasmtime package provides one, based on Wasmtime, which compiles the modules to native code:
dotnet package add Meziantou.Framework.WebPlatform.Wasmtimeusing var runtime = new WasmtimeRuntime(); // can be shared by the browsing contexts
using var engine = new JavaScriptScriptEngine();
using var context = new BrowsingContext(new BrowsingContextOptions
{
ScriptEngine = engine,
WebAssemblyRuntime = runtime,
});
var document = await context.NavigateAsync("https://example.com/", _ => """
<output></output>
<script>
// (module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add))
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1, 0,
7, 7, 1, 3, 97, 100, 100, 0, 0, 10, 9, 1, 7, 0, 32, 0, 32, 1, 106, 11]);
WebAssembly.instantiate(bytes).then(({ instance }) => {
document.querySelector('output').textContent = instance.exports.add(2, 3);
});
</script>
""");
await context.EventLoop.RunUntilIdleAsync();
Assert.Equal("5", document.QuerySelector("output")!.TextContent);- The runtime can be shared by the browsing contexts and the script engines; dispose it when you are done.
validate(),compile(),instantiate(),compileStreaming()andinstantiateStreaming(), theModule,Instance,Memory,Table,Global,TagandExceptionobjects, and the imported JavaScript functions are supported.- The features of WebAssembly 3.0 are enabled (reference types, garbage collection types, exceptions, tail calls, memory64, multiple memories, SIMD), and the threads: see Threads.
- The legacy exception handling instructions (
try,catch,catch_all,rethrow,delegate), which Emscripten and the runtime of .NET in the browser (Blazor WebAssembly) still emit by default, are supported: the modules that use them are translated to the exception references of WebAssembly 3.0 (try_table,throw_ref) before they are compiled, as Wasmtime only supports those. - The JS String Builtins are supported: the
builtins: ["js-string"]compile option provides the functions of thewasm:js-stringmodule (length,concat,charCodeAt,fromCharCodeArray...), andimportedStringConstantsturns the globals imported from a module into string constants (the name of the import is the string). - The type reflection is supported:
type()of theMemory,Table,Global,Tagand exported functions describes their type ({ minimum, maximum, shared },{ element, minimum, maximum },{ mutable, value },{ parameters },{ parameters, results }), the descriptors acceptminimuminstead ofinitial, andnew WebAssembly.Function({ parameters, results }, fn)creates a WebAssembly function from a JavaScript function: it can be stored in a table. The exported functions areWebAssembly.Functionobjects. memory.toResizableBuffer()gives a resizableArrayBufferof the bytes of a memory:resize()grows the memory by whole pages, and the buffer follows the size of the memory.- The running code is interrupted by the limits of the script engine, such as Timeout.
WasmtimeRuntimeOptions sets the size of the stack of the WebAssembly code (MaxStackSize, 512 KiB by default: a deeper recursion throws a RangeError), the largest size of a memory (MaxMemorySize: the memories are .NET arrays, shared with the ArrayBuffer objects of the scripts), and how often the running code checks whether it must stop (InterruptionCheckInterval, 10 ms by default). A table has at most 10,000,000 elements, the limit of the JavaScript API of browsers: table.grow returns -1 beyond it.
Compiling a large module takes time: the runtime of .NET in a Blazor WebAssembly application takes from a second to tens of seconds. Set ModuleCacheDirectory to save the compiled code of the modules in a folder: the next compilations of the same module, by any runtime that uses the folder, load it in milliseconds. The files are native code that the runtime runs without validating it, so use a folder that only the current user can write to. They are about ten times as large as the modules, and are never deleted.
Module scripts
A module script can import a WebAssembly module, as a JavaScript module (ESM integration): a response whose MIME type is application/wasm is a WebAssembly module.
using var runtime = new WasmtimeRuntime();
using var engine = new JavaScriptScriptEngine();
using var context = new BrowsingContext(new BrowsingContextOptions
{
ScriptEngine = engine,
WebAssemblyRuntime = runtime,
});
var document = await context.NavigateAsync("https://example.com/", _ => """
<output></output>
<script type="module">
// A response whose MIME type is application/wasm (a data: URL here) is a WebAssembly module:
// (module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add))
import { add } from "data:application/wasm;base64,AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
// A source phase import gives the compiled WebAssembly.Module, without instantiating it
import source addModule from "data:application/wasm;base64,AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
const { exports } = new WebAssembly.Instance(addModule);
document.querySelector('output').textContent = add(2, 3) + ' ' + exports.add(4, 5);
</script>
""");
await context.EventLoop.RunUntilIdleAsync();
Assert.Equal("5 9", document.QuerySelector("output")!.TextContent);<script type="module" src="app.wasm">,import,import(),<link rel="modulepreload">and the script of a module worker (new Worker("app.wasm", { type: "module" })) load WebAssembly modules.- The imports of the module are the exports of other modules:
(import "./lib.js" "log" (func))imports thelogexport of./lib.js, and an import of a WebAssembly module gets the export of its instance. The names are checked when the module graph is linked: an import that the module does not export is aSyntaxError, and no module of the graph runs. The modules it imports run before it; a module that is not evaluated yet (a cycle) gives aLinkError, as does a value whose type does not match the import. - Its exports are the bindings of the module: the functions, memories and tables are the objects of the exports of the instance, the globals are their values. The binding of a mutable global follows its value; the one of a
v128global throws aReferenceError.WebAssembly.namespaceInstance(ns)returns theWebAssembly.Instance. import source mod from "./app.wasm"andimport.source()give the compiledWebAssembly.Modulewithout instantiating it.- The modules are compiled with the JS String Builtins (
wasm:js-string) and the imported string constants ofwasm:js/string-constants. A module that does not compile is aCompileError, a module whose imports or exports use the reserved names (wasm:,wasm-js:) aLinkError, reported as the error of the script. - A WebAssembly module is a script: the
script-srcdirective of the Content Security Policy applies, not'wasm-unsafe-eval'.
Threads
The modules compiled with the threads, such as the Emscripten builds with -pthread, run in the windows and the workers of a page:
- A shared memory, created by
new WebAssembly.Memory({ initial, maximum, shared: true })or declared by a module, hasSharedArrayBufferbuffers. The modules import it, and the atomic instructions (i32.atomic.rmw.add,memory.atomic.wait32,memory.atomic.notify...) run on it. postMessage()sends aWebAssembly.Moduleand a sharedWebAssembly.Memoryto the workers of the agent cluster: the module is not compiled again, and the copies of the memory share its bytes. When a copy grows the memory, thebufferof each copy gets the new size. A shared memory can only be sent by a cross-origin isolated page (Cross-Origin-Opener-PolicyandCross-Origin-Embedder-Policyheaders).Atomics.wait(),Atomics.waitAsync()andAtomics.notify()on the buffers of a shared memory and thememory.atomic.wait32,memory.atomic.wait64andmemory.atomic.notifyinstructions use the same waiters: a script wakes the WebAssembly code that waits, and the reverse. AnAtomics.waitAsync()waits on a thread of its own.
using var runtime = new WasmtimeRuntime();
using var engine = new JavaScriptScriptEngine();
using var context = new BrowsingContext(new BrowsingContextOptions
{
ScriptEngine = engine,
WebAssemblyRuntime = runtime,
});
var document = await context.NavigateAsync("https://example.com/", _ => """
<output></output>
<script>
// (module (import "env" "memory" (memory 1 1 shared))
// (func (export "add") (param i32 i32) (result i32) (i32.atomic.rmw.add (local.get 0) (local.get 1))))
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 2, 16, 1, 3, 101,
110, 118, 6, 109, 101, 109, 111, 114, 121, 2, 3, 1, 1, 3, 2, 1, 0, 7, 7, 1, 3, 97, 100, 100, 0, 0, 10, 12, 1,
10, 0, 32, 0, 32, 1, 254, 30, 2, 0, 11]);
const memory = new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
WebAssembly.instantiate(bytes, { env: { memory } }).then(({ instance }) => {
const counter = new Int32Array(memory.buffer); // a SharedArrayBuffer: postMessage() shares it with the workers
Atomics.store(counter, 0, 40);
instance.exports.add(0, 2);
document.querySelector('output').textContent = Atomics.load(counter, 0);
});
</script>
""");
await context.EventLoop.RunUntilIdleAsync();
Assert.Equal("42", document.QuerySelector("output")!.TextContent);The bytes of a shared memory never move: they are allocated for the maximum size of the memory when it is created, up to MaxMemorySize and 2 GiB minus one page (32,767 pages). The memory cannot grow beyond: give the shared memories a maximum no larger than the memory they need.
A memory.atomic.wait32 or memory.atomic.wait64 instruction blocks the thread until it is notified or its timeout elapses: the limits of the script engine do not interrupt it. An Atomics.waitAsync() on the buffer of a shared memory uses a thread until it completes: a process runs at most 1,024 of them at once (beyond, Atomics.waitAsync() throws a RangeError), and they stop when their window or worker is closed. The threads of WebAssembly are a tier 2 feature of Wasmtime.
Wasmtime is a native library: it comes with the Wasmtime package, a dependency of Meziantou.Framework.WebPlatform.Wasmtime.