Skip to content

NetWasm 0.16.0

Latest

Choose a tag to compare

@zion-sati zion-sati released this 29 Nov 20:11
eecc8b4

NetWasm 0.16.0: runtime async in WebAssembly

NetWasm 0.16.0 is available on NuGet.org.

NetWasm 0.16.0 compiles .NET 11's runtime async to WebAssembly. Every async
method in a project is built with Roslyn's runtime-async code generation and
runs on NetWasm's own suspension runtime: no state machine per method, chains of
async calls up to six times faster, and smaller code, in the browser and under
WASI. On .NET 11, Blazor WebAssembly runs on Mono, which cannot run
runtime-async methods
(dotnet/runtime#137984).

A Debug build now also carries debug information: each managed method's name,
and DWARF line information that maps the code to the C# lines it came from.
Wasmtime's trap backtraces name the managed frames with their files and lines,
and LLDB debugs the program by C# line under Wasmtime.

Runtime async

  • Every project compiles its async methods with Roslyn's runtime-async code
    generation: no state machine per method. NetWasm lowers each one onto its own
    runtime, which suspends a method's frame and resumes it in place. There is
    nothing to set. Async methods in prebuilt libraries keep their state machines
    and run as before.
  • Loops that suspend on every iteration run as fast as with state machines or
    faster, at O3 and at Oz. Chains of async calls run up to six times faster, and
    the async code is smaller.
  • An awaited call of another runtime-async method is a direct call, with no
    Task made for it, as desktop .NET's JIT does.
  • ExecutionContext, AsyncLocal<T> and SynchronizationContext behave as on
    desktop .NET 11 across suspensions. A program that never changes them pays
    nothing for them.
  • A suspension keeps only the values live after it, and saves numbers without
    allocating.

Debug information

  • NetWasmDebugInfo, on by default in Debug and off in Release, writes a name
    section naming each managed method and, with NetWasmManagedStackTrace (also
    on in Debug), DWARF line information into the linked module: a subprogram per
    managed method with source lines and a line table. It covers components, raw
    modules and JavaScript modules.
  • WASMTIME_BACKTRACE_DETAILS=1 wasmtime run App.wasm prints a trap's managed
    frames with their files and lines, for example
    App.Program.Fail at /src/App/Program.cs:17.
  • LLDB under Wasmtime (wasmtime run -D debug-info=y) sets breakpoints on C#
    lines, steps and shows backtraces. See diagnostics for
    the recipe.
  • A method's closing brace has its own line, so stepping over a return stops
    at the brace, as on desktop .NET.
  • Release output is unchanged. Debug information makes a Debug module larger:
    Avalonia 12's headless sample grows by 15%, mostly method names.
  • Frames of libraries that link their sources by URL (Source Link), such as
    NetWasm's own, are named without lines.
  • Variables and types are not described yet.

Arrays created from a type

  • Array.CreateInstance, Array.CreateInstanceFromArrayType and
    Type.MakeArrayType no longer compile an array type for every type the
    program names. An array of a reference type the program has no array type of
    shares one compiled form per rank, which keeps its element type, as Native AOT
    shares one form across arrays of references; casts, stores, copies,
    GetType() and the array's interfaces answer as for an array of that element.
    Large programs that create arrays this way, such as those that resolve
    IEnumerable<T> services through dependency injection, compile with much less
    memory and in less time, and a program that never creates an array from a
    type is unchanged.
  • Breaking: an array of a value type is created only for the value types the
    program names with typeof (including as a type argument, such as
    typeof(Point?) or typeof(IEnumerable<Point>)) and those whose arrays it
    uses. For any other value type Array.CreateInstance throws
    NotSupportedException, as Native AOT does for an array it did not compile.
    In 0.15 every value type the program named had one.

Calls dispatch to what reaches them

  • From O1 up, every virtual and interface call is compiled for the types that
    can actually reach its receiver at that call, instead of for every type that
    implements the method. The compiler follows each value from the allocations
    and fields it comes from to the calls it reaches, so a call through an
    interface that many types implement compiles a case only for the few that
    arrive there. None and O0 keep the faster analysis for edits.
  • The receiver's declared type narrows it too: a reference read from an array
    of T is a T, and a Type, MethodBase or FieldInfo from reflection
    calls only those types' overrides, so GetType().ToString() no longer
    compiles every type's ToString.
  • Code that only unreachable blocks name is no longer compiled. Inlining a
    method that always throws leaves the code after the call unreachable; the
    methods, types and strings only that code named are now left out.
  • Modules get smaller: Console 42 (Console.WriteLine(42)) is 27,848 bytes
    with the default collector, against 28,998 in 0.15.2, and 31,990 with
    NetWasmGC, against 33,227. Programs with large class hierarchies,
    expression trees or reflection shrink more.

Compile memory on large applications

  • The compiler holds far less while it analyzes a large program: the first
    pass over the program keeps only what later passes reuse, and calls that
    see the same receivers share one set of targets.
  • The large Avalonia application used to reproduce #253 (three Avalonia samples
    compiled together) now peaks below 16 GiB of compiler memory at every
    optimization level: about 14.9 GiB at O0, 13.5 at O1, 14.9 at O2, 15.8
    at O3, 11.1 at Os and 14.3 at Oz. With the array change above, this
    addresses the memory growth reported in #253.
  • Binaryen's wasm-opt, which runs after the compiler from O1 up, can still
    need more memory than the compiler on applications this large.

Null references

  • A read or write through a ref whose address is 0 throws
    NullReferenceException, as with Mono AOT: Unsafe.NullRef<T>(), a default
    ref field, or the first element of a span made over a null reference. An
    address past 0 (a null reference plus an offset) reads memory, as on Mono AOT,
    and so do Unsafe.ReadUnaligned and Unsafe.WriteUnaligned. In 0.15 most
    reads and writes through a ref at address 0 read or wrote memory.
  • Every optimization level throws at the same access as an unoptimized build.
    The checks cost little where the compiler cannot prove a ref non-null: a
    span loop runs a copy without them when a test before it finds none of its
    elements at address 0.

JavaScript interop

  • Breaking: JSException is
    System.Runtime.InteropServices.JavaScript.JSException, the name .NET uses,
    with .NET's public surface (JSException(string)), and the
    System.Runtime.InteropServices.JavaScript assembly forwards it. A library
    built for net10.0 that catches it now compiles (#270), and so do
    libraries naming JSObject, JSHost, JSType and the other public types of
    that namespace. In 0.15 the type was System.JSException, and nothing
    forwards that name.
  • A failed [JSImport] raises a JSException whose message is the JavaScript
    value's toString(), such as NotAllowedError: Permission denied, and which
    keeps the value. A JSException holding a JavaScript error that leaves a
    [JSExport], synchronous or async, gives JavaScript the original error, as on
    .NET. A managed exception that crossed to JavaScript and comes back raises the
    original exception. An Error crossing as a value also reads as toString()
    now; it read as .message before.
  • A program pays for giving errors back only when it can build a JSException
    that holds one: a minimal synchronous export program at Oz is 7,133 bytes
    with no imports.
  • An async [JSImport] with a JSObject argument no longer hangs when the
    object's handle and the task's differ. Completing, rejecting or canceling a
    task with a handle that names no task now fails loudly instead of silently.
  • Task.Yield() returns to the browser's event loop under a JavaScript host,
    as timers and Task.Delay do, and queued work (Task.Run, thread pool items,
    the code after Task.Yield) runs in batches of up to 30 ms, as on .NET's
    browser runtime. In 0.15 Task.Yield() stayed in the current turn.
  • The code after an await on an imported Promise runs inside that Promise's
    reaction, before control returns to the browser's event loop. An IndexedDB
    transaction therefore stays open across awaited requests of that transaction.
    .NET's browser runtime continues from setTimeout(0) instead, where a
    transaction ends at its first awaited request. See
    JavaScript interop.

Debug builds reach what Release builds reach

  • A static field that no code writes reads as its default at every level,
    None and O0 included. The core library guards local time, the wall clock
    and culture behind such fields, so a Debug build no longer imports those host
    capabilities where a Release build leaves them out: a host that withholds one
    no longer rejects the Debug build alone, and a compile without a WIT world no
    longer fails at O0 where O2 succeeds. Edits that change what the rule
    folds recompile in full, so edit-and-run stays exact.

Build warnings and errors

  • New warning NW1019: a reached attribute query (IsDefined,
    GetCustomAttribute, GetCustomAttributes) that the compiler cannot answer
    throws PlatformNotSupportedException when it runs, and the build now says so,
    with the reason and a fix. The reasons include an attribute it cannot build, a
    filter or an assembly known only at run time, a method or property as the
    target, and a delegate or expression tree that calls the query. In 0.15 the
    build was silent. See diagnostics.
  • NW1009, a host import that needs a WIT world, now names how the program
    reached the import, step by step.

Fixes

  • A function pointer call whose signature uses an enum declared in another
    assembly, directly or through a type argument, compiles (#268).
  • A method with an out parameter that pins
    Utf16StringMarshaller.GetPinnableReference and calls a function pointer
    inside the pinned region compiles (#269).
  • Avalonia's CommandBar compiles at Oz (#271).
  • At O0, a break on a short-circuit condition, in a loop inside try/finally,
    leaves the loop instead of starting it again (#272). Avalonia's layout pass
    had this shape, so an Avalonia browser app no longer freezes at start-up in
    O0 builds.
  • A catch that returns from inside a foreach, followed by an inner for
    loop, compiles at every optimization level (#275). The reported method failed
    with NW1011 at None, O0 and O1, the default Debug build included.
    Related shapes compile too: a catch that continues, breaks or jumps ahead,
    a second try in the same loop, and a for loop, an IEnumerable<T> or an
    explicit finally in place of the foreach over a list.
  • On Windows, the Node.js host behind dotnet run opens files in a preopened
    directory, the working directory and the temporary directory included
    (#274). It compared the host's real paths, which use backslashes on Windows,
    against a / separator, so every open failed with
    UnauthorizedAccessException.
  • Task.IsFaulted carries .NET's nullable annotation, so
    task.Exception.InnerExceptions after an IsFaulted check compiles without a
    nullable warning, as it does on .NET.
  • A finally block whose checks share one throw helper, as inlined
    Span.Slice and CopyTo calls do, ends where its code ends instead of
    falling through into the throw. 0.15.2 compiled such a method into code that
    trapped when it ran.

Known issues

Both are fixed in 0.16.1.

  • Decoding UTF-8 (Encoding.UTF8.GetString, GetChars and the decoders)
    also keeps the decoder's exception fallback and the code that formats its
    error messages, about 10 KB of uncompressed code, although Encoding.UTF8
    never runs it: it replaces invalid bytes instead of throwing. The compiler
    can't yet prove that UTF8Encoding never picks the throwing fallback.
  • A program that calls a [JSImport] carries the code that builds a failed
    import's JSException and the finalization that releases the JavaScript
    value the exception keeps. For a synchronous export calling one synchronous
    import at Oz, that's about 850 bytes after Brotli.