Repository navigation
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
Taskmade for it, as desktop .NET's JIT does. ExecutionContext,AsyncLocal<T>andSynchronizationContextbehave 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, withNetWasmManagedStackTrace(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.wasmprints 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
returnstops
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.CreateInstanceFromArrayTypeand
Type.MakeArrayTypeno 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 withtypeof(including as a type argument, such as
typeof(Point?)ortypeof(IEnumerable<Point>)) and those whose arrays it
uses. For any other value typeArray.CreateInstancethrows
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
O1up, 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.NoneandO0keep the faster analysis for edits. - The receiver's declared type narrows it too: a reference read from an array
ofTis aT, and aType,MethodBaseorFieldInfofrom reflection
calls only those types' overrides, soGetType().ToString()no longer
compiles every type'sToString. - 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 atO0, 13.5 atO1, 14.9 atO2, 15.8
atO3, 11.1 atOsand 14.3 atOz. With the array change above, this
addresses the memory growth reported in #253. - Binaryen's
wasm-opt, which runs after the compiler fromO1up, can still
need more memory than the compiler on applications this large.
Null references
- A read or write through a
refwhose address is 0 throws
NullReferenceException, as with Mono AOT:Unsafe.NullRef<T>(), a default
reffield, 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 doUnsafe.ReadUnalignedandUnsafe.WriteUnaligned. In 0.15 most
reads and writes through arefat 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 arefnon-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:
JSExceptionis
System.Runtime.InteropServices.JavaScript.JSException, the name .NET uses,
with .NET's public surface (JSException(string)), and the
System.Runtime.InteropServices.JavaScriptassembly forwards it. A library
built fornet10.0that catches it now compiles (#270), and so do
libraries namingJSObject,JSHost,JSTypeand the other public types of
that namespace. In 0.15 the type wasSystem.JSException, and nothing
forwards that name. - A failed
[JSImport]raises aJSExceptionwhose message is the JavaScript
value'stoString(), such asNotAllowedError: Permission denied, and which
keeps the value. AJSExceptionholding 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. AnErrorcrossing as a value also reads astoString()
now; it read as.messagebefore. - A program pays for giving errors back only when it can build a
JSException
that holds one: a minimal synchronous export program atOzis 7,133 bytes
with no imports. - An async
[JSImport]with aJSObjectargument 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 andTask.Delaydo, and queued work (Task.Run, thread pool items,
the code afterTask.Yield) runs in batches of up to 30 ms, as on .NET's
browser runtime. In 0.15Task.Yield()stayed in the current turn.- The code after an
awaiton 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 fromsetTimeout(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,
NoneandO0included. 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 atO0whereO2succeeds. 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
throwsPlatformNotSupportedExceptionwhen 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
outparameter that pins
Utf16StringMarshaller.GetPinnableReferenceand calls a function pointer
inside the pinned region compiles (#269). - Avalonia's
CommandBarcompiles atOz(#271). - At
O0, abreakon a short-circuit condition, in a loop insidetry/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
O0builds. - A
catchthat returns from inside aforeach, followed by an innerfor
loop, compiles at every optimization level (#275). The reported method failed
with NW1011 atNone,O0andO1, the default Debug build included.
Related shapes compile too: acatchthat continues, breaks or jumps ahead,
a secondtryin the same loop, and aforloop, anIEnumerable<T>or an
explicitfinallyin place of theforeachover a list. - On Windows, the Node.js host behind
dotnet runopens 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.IsFaultedcarries .NET's nullable annotation, so
task.Exception.InnerExceptionsafter anIsFaultedcheck compiles without a
nullable warning, as it does on .NET.- A
finallyblock whose checks share one throw helper, as inlined
Span.SliceandCopyTocalls 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,GetCharsand the decoders)
also keeps the decoder's exception fallback and the code that formats its
error messages, about 10 KB of uncompressed code, althoughEncoding.UTF8
never runs it: it replaces invalid bytes instead of throwing. The compiler
can't yet prove thatUTF8Encodingnever picks the throwing fallback. - A program that calls a
[JSImport]carries the code that builds a failed
import'sJSExceptionand the finalization that releases the JavaScript
value the exception keeps. For a synchronous export calling one synchronous
import atOz, that's about 850 bytes after Brotli.