The webassembly spec is somewhat vague on what a trap is. The spec only says:
Traps
Under some conditions, certain instructions may produce a trap, which immediately aborts execution. Traps cannot be handled by WebAssembly code, but are reported to the outside environment, where they typically can be caught.
In particular, there doesn't seem to be anything specifying that traps actually have to be caught, or that the VM has to report anything to the outside environment beside "a trap occurred, sucks to be you". In practice, all browsers throw exceptions on traps (though I'm not sure if the JS API specifies this is what needs to happen?)
So, some dumb questions, mostly out of curiosity:
Traps are not equivalent to exceptions as exceptions may be added to Wasm in the future (see https://github.com/WebAssembly/exception-handling). They're more analogous to a "signal" that can't be handled by Wasm, but can be handled in the host environment.
Wasmtime has a guaranteed representation of a trap in its Rust API, which is wasmtime::Trap
; this representation is used both for any traps Wasm code might cause or from host functions that may "trap".
Wasm only has the unreachable
instruction that explicitly is for trapping; other instructions may cause traps when runtime validation fails (i.e. divide by zero, an out-of-bounds memory access, an indirect call type signature mismatch, etc). The Wasm spec just outlines the trap conditions; it's the responsibility of a runtime like Wasmtime to ensure that traps are raised when those conditions are met.
Wasm itself can't "abort" like one would do in a C program; it may execute an unreachable
instruction to cause a trap or call a host function that "aborts" (for example, in WASI there's a proc_exit
function which implementations may treat as a special trap to "exit" the Wasm "process")
Wasm also can't "segfault"; it can read or write memory at an offset that isn't valid for the current size of the memory being referenced, which is a trap condition; it's up to the runtime to ensure a trap gets returned back to the host environment. One way to do that would have bounds checks for every memory instruction. Wasmtime can be configured to do bounds checking, but for performance, it uses guard memory regions that will cause OS signals and then translates those signals to traps by default.
Last updated: Nov 22 2024 at 16:03 UTC