csharpc

ADR 0011 — WebAssembly (wasm32-wasip1): explicit exception propagation, spilled GC roots, one thread

  • Status: Accepted, implemented (--target wasm32-wasip1).

Context

Roadmap M3 adds WebAssembly next to Linux, macOS and Windows: C# programs compiled to a .wasm module that runs under a WASI runtime (wasmtime in CI), behaving exactly like the same program under .NET. Four things that the native targets get from the operating system are missing or different:

  1. Exceptions. csharpc lowers try/catch/finally to Itanium-style invoke/landingpad with its own personality, driven by a two-phase unwinder (ADR 0005). WebAssembly has no unwinder and no way to inspect its own stack. The exception-handling proposal exists in two encodings: LLVM 18 emits only the legacy one (try/catch/delegate, from funclet IR: catchswitch/catchpad/cleanuppad), while wasmtime implements the standardized one (exnref, behind -W exceptions) and lists the legacy one as deprecated. Support in other WASI runtimes varies.
  2. GC roots. csrt’s collector is conservative: it scans the stack, the registers (spilled by setjmp) and the data segment for anything that looks like a pointer into the heap. In WebAssembly, function locals and the operand stack live inside the engine. Only allocas whose address escapes are in linear memory (LLVM’s shadow stack, below __stack_pointer). A reference held only in a wasm local is invisible to the collector, which then frees a live object.
  3. Threads. WASI preview 1 has no threads. wasi-threads exists but is not universally available and is being superseded. wasi-libc for wasm32-wasip1 declares the pthread API without implementing it.
  4. Operating system. WASI preview 1 gives files in preopened directories, clocks, randomness, arguments and environment variables, and process exit, and nothing else: no processes, signals, sockets (in preview 1), dynamic loading or memory mapping. wasm32 also means 32-bit pointers, where every native target so far was 64-bit.

Decision

Toolchain and target

  • --target wasm32-wasip1 (also spelled wasm32-wasi). wasm64, wasm32-wasip1-threads and other WebAssembly triples are rejected with an explicit error.
  • The WASI SDK ($WASI_SDK_PATH, default /opt/wasi-sdk) provides clang, wasm-ld, wasi-libc and compiler-rt. Its clang must be LLVM 18 like csharpc’s (wasi-sdk 22–24; CI pins wasi-sdk 24), because the runtime is linked into the program as LLVM bitcode.
  • The runtime’s bitcode is always linked into the program on wasm, at every optimization level and for every output kind. The two passes below need the whole program, the C runtime included.
  • wasm-ld links statically. The 8 MiB stack (the default main-thread stack of .NET on Linux) is placed first in linear memory, so an overflow traps at address 0 instead of overwriting static data. main(argc, argv) is exported as __main_argc_argv, the name wasi-libc’s start code calls.
  • Object layouts are computed from the target data layout. The few offsets that were written for 64-bit (task/iterator payload, the Task.Run work item) follow the pointer size. Boxed values keep their payload at offset 8 on every target.

Exceptions: explicit propagation (option b)

The options were: (a) a funclet-based lowering using the EH proposal, (b) explicit error propagation after each call that may throw, and (c) setjmp/longjmp emulation.

csharpc uses (b), implemented as a whole-module LLVM IR pass (src/Csharpc/Wasm/ExceptionLowering.cs) that runs on the IR codegen already produces for every target, before optimization:

  • Throwing (csrt_throw_object, every csrt_throw_* helper) stores the exception in the global csrt_pending_exception and returns (CSRT_THROWS is not _Noreturn on wasm).
  • After every call that may throw, the caller loads the global and branches. An invoke becomes a call plus a branch to its landing-pad block or its normal destination. A plain call branches to the function’s propagate block, which returns at once. The return value is meaningless and never read, because every caller tests the global first. In main, the propagate block reports the unhandled exception.
  • landingpad instructions disappear. Their block is reached by an ordinary branch, and csrt_begin_catch takes the exception out of the global. The handler-selection code (type tests, when filters, finally routing, rethrow) is codegen’s unchanged landing-pad code, so the semantics are the same as on the native targets by construction. As there, filters run in the handling frame after the inner finally blocks, and an exception no frame catches still runs every finally block before the “Unhandled exception.” report.
  • “May throw” is computed over the call graph. The roots are the functions that store a non-null value into the global. Clang inlines csrt_throw_object into the runtime’s helpers, so the pass looks for the store itself. Indirect calls (virtual, interface, delegate, function pointer) may throw. Declarations (wasi-libc) never throw. noreturn and memory-effect attributes are removed from the functions and call sites that may throw: they now return, and they write the global.
  • The C runtime is lowered with the same pass, so C frames between a throw and its handler propagate too (for example, csrt_object_to_string calling a user ToString that throws). The C functions that catch (csrt_call_catching_*, csrt_trap_call) read the global themselves and are left alone.

Why (b):

  • Engine support. It needs nothing beyond WebAssembly MVP features, so it works on every WASI runtime today. (a) needs the EH proposal in an encoding LLVM 18 doesn’t emit for the engine we test with. (c) is no alternative: wasi-libc’s setjmp/longjmp is itself built on the EH proposal (-mllvm -wasm-enable-sjlj) and refuses to compile without it.
  • Correctness by reuse. (a) would mean a second lowering of every CFG region (catchswitch dispatch, cleanuppads for finally, funclet-local state), duplicated in the coroutine (async and iterator) paths. (b) reuses the landing-pad code that the native test suites already exercise. Its only new logic is “test a flag after a call”, which is easy to check. The funclet lowering remains the route for a future MSVC target, where the unwinder exists and the cost model differs.
  • Cost. The non-throwing path pays one load, one compare and one branch after each call that may throw. After inlining, LLVM removes most of them: the global is internal and never has its address taken, so alias analysis proves that code which doesn’t throw leaves it unchanged. Throwing is cheap, with no unwinder and no table lookups. Code size grows by the tests (see “Measurements” in 04-runtime.md).

GC roots: spill slots written by the compiler

The options were: Binaryen’s --spill-pointers pass on the linked module, spilling references to a shadow stack in codegen, or collecting only at points where no locals hold references.

csharpc spills in the compiler, as an LLVM IR pass that runs after optimization and before instruction selection (src/Csharpc/Wasm/RootSpilling.cs):

  • “May collect” is computed over the call graph. The root is csrt_gc_collect_now, the collector’s single entry point, which is never inlined. Indirect calls may collect.
  • In each function that may collect, a liveness analysis over the SSA values finds every value that may hold a reference and is live across a call that may collect. Such values are pointers, aggregates and vectors containing pointers, and integers made from pointers by ptrtoint. Each one gets a slot (an alloca, placed in the linear-memory stack frame) and a volatile store right where the value is defined: after the instruction, after the phis of its block, or at entry for an argument.
  • A slot always holds the latest value of its SSA value and keeps it until the function returns. So every object that a frame can still reach, directly or through an interior pointer derived from one of its values, is in linear memory whenever the collector runs. The collector (gc.c) scans the stack from its own frame up to __stack_high, plus the data segment. The rest is unchanged: interior pointers resolve to their object, and objects are scanned conservatively.

Why not the alternatives:

  • Binaryen --spill-pointers. It computes liveness over wasm locals only. A value that the LLVM backend left on the operand stack across a call, as in (i32.add (local.get $x) (call $f)), is not spilled. Neither is a pointer in an i64 or v128 local. It would need --flatten first and another pinned tool in the toolchain. Working on LLVM IR, with the pointer types still known, avoids both problems.
  • Spilling in codegen (FunctionCodeGen). Before optimization most values are in allocas anyway. The problem is what the optimizer creates (SROA, GVN, LICM, inlining of the runtime), so the spill has to come after it.
  • Collecting only where no locals hold references isn’t something the compiler can guarantee for arbitrary code: every allocation is a potential collection, and allocations happen while values are live.

The cost is one store per definition of a spilled value and a stack frame for functions that had none. CSRT_GC_STRESS=N (every platform) collects on every N-th allocation and makes every allocation take the slow path. CI runs tests/samples/310_gc_roots_in_locals on wasm with a collection at every allocation. Without root spilling that program prints wrong totals; with it, the output matches .NET.

Threads: one thread, .NET’s single-threaded WebAssembly behavior

  • Thread.Start throws PlatformNotSupportedException (“Operation is not supported on this platform.”), as in .NET’s single-threaded WebAssembly builds.
  • Environment.ProcessorCount is 1, so Parallel.For/ForEach/Invoke run their iterations inline on the calling thread, in order.
  • Task.Run work items, continuations and timers (Task.Delay, CancelAfter) go to the same queue as on native targets. Whatever blocks runs them: .Wait(), .Result, GetResult(), async Main and Thread.Sleep run queued work and fire due timers on the main thread (async.c). Programs whose output doesn’t depend on thread scheduling, which is all of the tests, print the same as under .NET.
  • A blocking wait that nothing can satisfy (Monitor.Wait without a timeout, a task no queued work completes, Thread.Sleep(Infinite)) prints an explicit “deadlock” message and exits with status 134 instead of hanging. Waits with a timeout sleep until it expires. Locks are bookkeeping only (src/runtime/wasi.c).

Operating system surface

  • System.IO, Environment and the clocks use wasi-libc through the corelib’s existing POSIX layer, with WASI’s flag values, errno numbers and struct layouts (CSHARPC_TARGET_WASI in corelib/IO/Posix.cs). Relative paths resolve against $PWD when it names a preopened directory. WASI itself has no current directory; tests/wasm-run.sh preopens / and passes the environment.
  • P/Invoke binds libc and libm, which means wasi-libc, statically and with strong references: wasm-ld does not extract archive members for weak ones. A symbol that wasi-libc lacks is a link error. Any other library throws DllNotFoundException at the call, as .NET does when a library can’t be loaded.
  • Environment.ProcessId is 42, the value wasi-libc’s getpid emulation reports. MachineName is “localhost”.
  • An unhandled exception prints .NET’s message on stderr and aborts. That traps, and wasmtime exits with status 134, the same status as .NET on Linux (SIGABRT). WASI exit codes are limited to 0–125: wasmtime refuses larger ones, so Environment.Exit(200) can’t be reproduced there.
  • --sanitize and --hardening max are rejected. The engine already provides control-flow integrity: structured control flow, type-checked indirect calls, and return addresses outside linear memory. The default hardening level builds the runtime with zero-initialized locals.

Test oracle

The expectations stay the ones recorded with .NET on Linux: there is no .NET for plain WASI to record with, and the goal is the same behavior as a native run. tests/platform-skips.txt lists, under wasi, the tests whose recorded behavior WebAssembly cannot have, each with a reason: threads, processes, LP64 P/Invoke signatures, errno numbers that a test prints, exit codes of 126 and above. Everything else must match byte for byte.

Consequences

  • WebAssembly programs behave like native ones for everything except the documented platform limits, and every limit produces an explicit message or exception, never wrong output.
  • Exceptions cost a test after calls on the non-throwing path; throwing is cheaper than on native targets. GC roots cost a store per spilled definition. Both are whole-program IR passes, so wasm builds always link the runtime as bitcode, at -O0 too.
  • A future target with the EH proposal everywhere could switch exceptions to (a) without touching codegen’s region lowering, by replacing ExceptionLowering. Likewise a precise collector with LLVM statepoints would replace RootSpilling.
  • Real threads (wasi-threads / shared-everything threads) would need the GC’s stop-the-world handshake reworked: there are no signals, and other threads’ locals are just as invisible.