Skip to content

NetWasm 0.15.0: your NuGet packages, native ones included, and a generational collector

Latest

Choose a tag to compare

@zion-sati zion-sati released this 20 Nov 09:27
87a4233

NetWasm 0.15.0: your NuGet packages, native ones included, and a generational collector

NetWasm 0.15.0 is available on NuGet.org.

Your NuGet packages, as they are. Projects now target net10.0-netwasm, a
.NET platform target framework, so NuGet takes a package's net10.0, net9.0,
net8.0 or .NET Standard build, newest first. Static archives built by
Emscripten link as they are, the ones SkiaSharp and HarfBuzzSharp ship
included, and Avalonia 12's headless platform renders the same frame as on
desktop .NET, unchanged. dotnet test runs net10.0-netwasm test projects.

A generational collector. NetWasmGen is NetWasmGC with generations:
most of its collections look only at the objects allocated since the last one
and at the old objects the program stored a reference into. A program that
keeps a large set of objects alive while short-lived ones come and go runs up
to three times as fast as under NetWasmGC, and binary-trees 1.6 to 1.8 times as
fast; across 57 garbage-collection programs it takes 0.93 of NetWasmGC's time.
Choose it for services over in-memory state, per-frame garbage and building and
discarding trees; see
when to choose it.

Collection out of the way. A page, a worker and a component's event loop
collect while the program waits, so collections land between interactions
instead of inside them: in a session of mixed interactions on a page, most
collections moved out of the interactions and the heap halved.

TLS clients. SslStream runs over WASI's wasi:tls, and upstream's
SocketsHttpHandler over it with connection pooling and HTTP/2, so wss://
WebSockets and SmtpClient over TLS work too, in NetWasm's Node.js host and in
Wasmtime.

Interop as on .NET. Raw DllImport declarations take .NET's runtime
marshalling of handles, strings, arrays and structs. JSObject has .NET's
property API, JSHost.ImportAsync works, and libraries built for the browser by
.NET's SDK work in NetWasm programs, their [JSImport] and [JSExport] methods
included.

More of .NET. A program can read its manifest resources through
ResourceManager, load its assemblies by name, and query the attributes of a
Type known only at run time.

Faster pages. A page starts every startup download as soon as its module
loads, and loads less of the runtime.

The platform target framework

  • New projects and templates target net10.0-netwasm. NuGet treats it as
    net10.0 on a platform, so a package's newest .NET build wins over its .NET
    Standard one, as for any .NET platform. Modern builds suit NetWasm better:
    SkiaSharp's and HarfBuzzSharp's call native code through plain P/Invokes,
    where their .NET Standard builds need runtime marshalling.
  • net10.0 names the contract and keeps the .NET 10 SDK the floor; NetWasm's
    CoreLib is .NET 11's. An app compiles against NetWasm.App.Ref as before, and
    a build names any API a package reaches that NetWasm lacks.
  • dotnet run starts a net10.0-netwasm executable on NetWasm's launcher.
  • A net10.0-netwasm build takes no desktop native assets from a package's
    runtimes/ folder.
  • netwasm0.1 still builds, with a deprecation warning, so a library can
    build both from one SDK. It is removed in a later release, 1.0 at the latest.
  • A library that targets both net10.0-netwasm and netwasm0.1 restores a
    package that netwasm0.1 takes through its .NET Standard fallback, warnings
    as errors included. NuGet restores such a project from its outer evaluation,
    where the SDK's suppression of NU1701 did not apply.
  • A net10.0-netwasm project cannot use a package that ships only
    netwasm0.1 assets: NuGet cannot read that framework back from its assets
    file. Such a package needs a net10.0-netwasm or net8.0 and later build.
  • The out-of-band libraries (dependency injection, logging, configuration
    binding, options and the rest) are built for net10.0-netwasm.
  • NetWasm.Microsoft.Extensions.DependencyInjection: a single service resolved
    after its IEnumerable<T> is the last registration, as with Microsoft's
    container; it was the first.
  • Microsoft's own Microsoft.Extensions.Primitives,
    Microsoft.Extensions.Configuration (with its abstractions and the
    environment-variable, command-line and JSON providers) and
    Microsoft.Extensions.Caching.Abstractions 11.0.0 packages run on NetWasm as
    published, so NetWasm.Libraries no longer ports them and its packages
    depend on Microsoft's.
  • dotnet test runs net10.0-netwasm test projects. VSTest reports such a
    project as .NETCoreApp,Version=v10.0, like a desktop one, so
    NetWasm.Testing.VSTest's build adds a NetWasm.TargetFramework test run
    parameter by which its runtime provider recognizes the run. TUnit-NetWasm's
    packages now target net10.0-netwasm; a netwasm0.1 test project stays on
    an earlier TUnit-NetWasm release. A netwasm0.1 project cannot reference a
    net10.0-netwasm-only project (NU1201), so a library under test targets
    net10.0-netwasm.

Manifest resources and assembly names

  • A program that reads an assembly's manifest resources carries every embedded
    resource of every assembly it compiles, in its module's data. A program that
    never reaches a resource API carries none.
  • ResourceManager(string, Assembly) reads the assembly's embedded
    .resources, so a resx-generated resource class works (Microsoft.Testing.Platform's
    strings among them). NetWasm runs invariant globalization, so the neutral
    resources are the main assembly's, as .NET finds them in that mode.
    new ResourceManager(typeof(T)), which generated resource classes use,
    names the resources after T at compile time; a Type the compiler cannot
    see throws PlatformNotSupportedException.
  • Assemblies have their simple names at run time. AppDomain.GetAssemblies()
    and Assembly.Load(name) answer for the assemblies compiled into the
    program, when a program reaches them.
  • An assembly's own attributes ([assembly: ...]) can be read from an
    assembly the compiler can see, Assembly.GetExecutingAssembly() or
    typeof(T).Assembly, through GetCustomAttribute, GetCustomAttributes
    and IsDefined, for a sealed attribute type such as
    AssemblyInformationalVersionAttribute or AssemblyMetadataAttribute.
    As with type and member attributes, the compiler resolves the query; other
    assembly queries throw PlatformNotSupportedException.
  • Attribute queries on a Type known only at run time are answered: a Type
    parameter, a lambda's argument, a field or obj.GetType(), through
    GetCustomAttribute, GetCustomAttributes, IsDefined and Attribute's
    statics, when the filter is one closed attribute type. The compiler answers
    from the types the program already has at run time that carry the attribute,
    so a program constructs only the attribute types it queries, only for those
    types, and keeps no attribute table. A null target throws as on .NET. Queries
    on other members known only at run time, such as a MethodInfo, and filters
    known only at run time still throw PlatformNotSupportedException
    (custom attributes).
  • An attribute query whose filter is an open generic attribute type, such as
    typeof(TagAttribute<>), finds every attribute whose type, or a base of it,
    is a constructed instance of it, and returns them as Attribute[], as .NET
    does. This works on types known at compile time or only at run time, and on
    an assembly's own attributes when the generic attribute type is sealed. It
    used to throw PlatformNotSupportedException. A query for a sealed attribute
    type on an assembly that also carries generic attributes no longer returns
    those as well.
  • typeof of an open generic class whose base the program uses nowhere else,
    such as typeof(TagAttribute<>) in a program that creates no attribute, no
    longer stops the build with NW1008, and the definition's BaseType is that
    base, as on .NET.

Native archives built by Emscripten

  • An executable links a package's static archives built by Emscripten with no
    NativeLibrary item, in either layout packages use for .NET's WebAssembly
    SDKs: SkiaSharp's and HarfBuzzSharp's, one archive per Emscripten version and
    variant, and .NET's runtimes/browser-wasm/nativeassets/<framework>/, one per
    .NET release (SQLitePCLRaw's). The SDK takes the newest build no newer than
    the Emscripten NetWasm's runtime is built with, single-threaded, with SIMD
    where there is one. A project's own NativeLibrary item replaces it.
  • Archives that use Wasm exception handling link in either encoding: legacy
    archives are translated to exnref. Emscripten's setjmp/longjmp, libc++
    and libc++abi, with their exception-handling builds for archives that throw
    or catch C++ exceptions, link only when an archive needs them. A longjmp or
    C++ exception that escapes into managed code aborts, as on .NET for Linux.
  • Functions Emscripten implements in JavaScript get stand-ins that fail
    cleanly: WebGL reports no GPU, so Skia renders on the CPU, in a component and
    a JsModule alike. Raw WebAssembly output can instead let the app's
    JavaScript supply the functions a project declares; declaring one of the GL
    functions means its JavaScript supplies them all. A function nobody supplies
    fails the build, naming it.
  • The C library native code calls has no file system: file, directory and
    dynamic loading calls fail as unavailable rather than failing the link.
  • Native code that throws or catches with the C++ exception tag itself, without
    calling the C++ ABI's exception functions, links with the C++ exception
    runtime too.

Native interop

  • [DisableRuntimeMarshalling] is honored as on desktop .NET, for imports,
    callbacks, function-pointer calls and struct fields. PreserveSig = false is
    rejected; CharSet, BestFitMapping and ThrowOnUnmappableChar are
    accepted and change nothing.
  • Raw DllImport declarations take desktop .NET's runtime marshalling of
    SafeHandle and CriticalHandle arguments, results, out and ref
    parameters, HandleRef arguments and arrays of blittable elements, which
    are pinned. Strings, delegates and conversions fail the build where reached.
  • Raw DllImport declarations that keep runtime marshalling convert bool and
    char as desktop .NET does on Unix, by value, by reference and as results:
    bool as a 4-byte BOOL or, with [MarshalAs(UnmanagedType.U1)] or I1,
    one byte; char as a UTF-16 code unit under CharSet.Unicode or U2, and
    otherwise as one ANSI byte. A [MarshalAs] that restates a scalar's own type,
    such as I4 on an int, is accepted. They used to fail with NW1012.
  • Raw DllImport declarations that keep runtime marshalling pass a string
    argument as desktop .NET does on Unix: a UTF-8 copy freed after the call, or
    under CharSet.Unicode or LPWStr the string pinned, with native writes
    showing in it. A string result is decoded from its native buffer, which is
    then freed with the C library's free, as desktop .NET frees it.
  • Raw DllImport declarations that keep runtime marshalling pass a struct
    holding a bool or char as desktop .NET lays it out natively on Unix: a
    BOOL (or a byte with U1), an ANSI byte or, under the struct's
    CharSet.Unicode, a UTF-16 code unit, nested structs in their own native
    layout; by value, by reference with the copy written back, and as results.
    The struct and its nested structs and enums may come from any assembly.
    They used to fail with NW1012.
  • Calls through unmanaged function pointers (delegate* unmanaged) in an
    assembly that keeps runtime marshalling convert bool, char, string and
    structs that hold a bool or char as desktop .NET's runtime marshalling
    does at an unmanaged calli: as a raw DllImport without attributes
    converts them. They used to fail with NW1012.
  • [UnmanagedCallersOnly] callbacks take and return structs by value as the
    C ABI passes them: through the caller's copy or result buffer, or as a single
    scalar for a one-field struct. They used to fail with NW1012.
  • Marshal.SizeOf, OffsetOf, StructureToPtr, PtrToStructure and
    DestroyStructure on a struct that holds a bool or char use the same
    native layout as desktop .NET: native size and field offsets, each field
    converted on the way out (padding zeroed) and back. They used to throw
    PlatformNotSupportedException.
  • The same members convert formatted classes (base class fields first, and
    PtrToStructure into an existing object), string fields (UTF-8 or UTF-16
    CoTaskMem copies that DestroyStructure frees, or inline ByValTStr),
    ByValArray arrays of primitives and null delegate fields, as desktop .NET
    does on Unix, and throw desktop's exceptions for fields it rejects. As on
    desktop, StructureToPtr writes no field when one fails: it clears the
    native structure and throws, without leaving a string copy behind. A
    non-null delegate field, which NetWasm does not convert, throws
    PlatformNotSupportedException before any memory is touched, in both
    directions: StructureToPtr with fDeleteOld frees nothing, and
    PtrToStructure leaves the object it fills as it was. A fixed
    buffer of UTF-16 chars copies whole, in these members and in a struct
    passed to a P/Invoke, as on desktop.
  • A NUL follows every string's characters, as on CoreCLR, so a string pinned
    with fixed or by LibraryImport's UTF-16 marshalling reaches native code
    terminated; native code used to read past its end.
  • NativeMemory, and Marshal's HGlobal and CoTaskMem memory, are the C
    library's malloc, realloc and free, as on .NET for Unix, so a block can
    be allocated on one side of a native call and freed on the other. Freeing a
    native library's malloc block with Marshal.FreeCoTaskMem used to corrupt
    memory.
  • A ref, in or out pointer, unmanaged function pointer or struct the C
    ABI lays out is passed by its address, as desktop .NET pins it.
  • A struct passed to C may hold unmanaged function pointers.
  • Marshal.GetLastSystemError and .NET 11's ANSI, BSTR, UTF-16 and
    pointer-array marshallers, which LibraryImport's generated code calls, are
    in CoreLib.
  • CLong and CULong are C's long and unsigned long, pointer-sized as on
    .NET for Linux, and pass to and from native code as C passes them. The
    exception marshallers the COM source generator uses
    (ExceptionAsHResultMarshaller<T>, ExceptionAsNaNMarshaller<T>,
    ExceptionAsDefaultMarshaller<T> and ExceptionAsVoidMarshaller) are there
    too.
  • ComWrappers, ObjectiveCMarshal and JavaMarshal, with their flags and
    callback types, are there and behave as .NET ships them where the platform
    has no such interop: ComWrappers' lookups answer false, and their other
    members throw PlatformNotSupportedException. TypeMapping throws
    NotSupportedException, as on Mono. ComVariant and
    StandardOleMarshalObject work as on .NET. So do the COM source generator's
    support types (StrategyBasedComWrappers, ComInterfaceMarshaller<T>,
    ComVariantMarshaller, [GeneratedComInterface] and the rest): a library
    built with the generator binds, and its COM calls throw
    PlatformNotSupportedException. A package that names any of them failed to
    bind before.
  • IDynamicInterfaceCastable works as on .NET: an object whose class
    implements it can be cast to, stored in an array of and called through an
    interface its class does not implement. Casts ask IsInterfaceImplemented,
    and calls go to the default methods of the
    [DynamicInterfaceCastableImplementation] interface that
    GetInterfaceImplementation names, with .NET's exceptions for an invalid
    answer or a missing method. A program that never allocates such a class
    pays nothing for it.
  • NativeLibrary and DllImportResolver are there, for libraries that probe
    for their native library or register a resolver as they start. Native code is
    linked when the program is built, so they answer as .NET does for a library
    that is not there: Load throws DllNotFoundException, TryLoad returns
    false, and an export lookup fails as for a missing symbol. A registered
    resolver is recorded, with .NET's checks, and the library's DllImport calls
    reach its linked archive as before.
  • A method with an exception filter that calls native code compiles.
  • C variadic functions declared through several fixed-signature DllImport
    overloads, as SQLitePCLRaw declares sqlite3_config and
    sqlite3_db_config, are called as C calls them: the compiler reads the
    function's type from the linked archive (its Wasm objects, or its LLVM
    bitcode under LTO) and passes the variadic arguments in a buffer laid out as
    WebAssembly's C ABI lays them out. Such overloads failed the build before.

Runtime and compiler

  • A constant ReadOnlySpan of an enum, as ReadOnlySpan<Color> colors = [Color.Red, Color.Green] or a call to a params ReadOnlySpan<TEnum> method
    writes, reads its elements from the program's data as one of its underlying
    type does. It threw PlatformNotSupportedException before.
  • A library that names a type, method or field NetWasm does not have no longer
    stops the build (#252). A method that names one throws TypeLoadException,
    MissingMethodException or MissingFieldException when called, as .NET
    throws when it first compiles such a method and Native AOT compiles it to a
    throw, and the build warns NW1016 for each one the program reaches. A method
    nothing calls costs nothing. <NetWasmMissingApiAsError>true</NetWasmMissingApiAsError>
    makes NW1016 an error again. A library that names an assembly the program
    does not have at all still fails the build. A missing instance method's
    message names the type the library names, not System.Object.
  • ldfld, ldflda and stfld on a static field evaluate their object, drop
    it without a null check and access the static, as CoreCLR does (#247).
    Avalonia's XAML compiler emits them for every event handler set in XAML, and
    such a method used to fail the build with NW1008.
  • A branch whose arms only compute a number becomes a branch-free select
    (NetWasmManagedConditionalSelects, on from O1 and at Os and Oz): c ? x : y,
    if (c) v = x;, if (c) return x; return y;, and conditions joined with &&
    and || when the second only computes numbers. Arms never read memory, call,
    divide or convert a floating-point value to an integer, so nothing runs that
    the branch would have skipped, and floating-point comparisons keep their NaN
    results. Data a branch predictor cannot learn, such as image pixels, no longer
    costs a mispredicted branch: PNG's Paeth filter now runs as fast as Mono AOT's.
    Modules also get slightly smaller. A conditional update of a value a loop
    carries from one iteration to the next, as if (x > 1) sum += x; updates a
    running sum, keeps its branch, as LLVM keeps it: a select would make every
    iteration wait for the comparison.
  • A local passed by reference to a method inlined into its caller, as a
    checksum's running sums are, stays in a register when the method reads a span
    between its uses: the local's address now folds past the span indexer's
    bounds check. At O3, a counted loop that reads a span at start + index, as a
    checksum reads each chunk, tests start >= 0 and start + count <= length
    once and then runs a copy of the loop without the per-element check, which
    the unroller then unrolls; when the test fails, the loop as written runs and
    throws where it did. Sdcb.SimdCodecs.Png's managed Adler-32 is several times
    faster at O3. The test also covers reads at an offset from the index, such as
    a pixel's left neighbor at start + index - 1 and the pixel above it at
    start + index - width: a loop that adds the row above to each pixel runs
    about 1.7 times as fast. A loop bounded by a count that reads a span at the
    index itself, values[index] for index < count, is versioned the same way.
  • At O3 and Oz, a loop follows its method's int and array parameters as it
    follows locals. A loop bounded by a count parameter, walking an array
    parameter or reading a span at start + index with start a parameter now
    loses its bounds checks, unrolls and is versioned as it was only after its
    method was inlined or had copied its parameters into locals.
  • Large programs whose Release build stopped in wasm-opt on macOS (NW1010,
    with no message) build again. ldvirtftn, a managed calli, cloning a
    delegate, DynamicInvoke and member execution tested their candidates in
    turn, one nested if per receiver type, static method, delegate type or
    member. With thousands of candidates, as in Avalonia's Skia backend and
    compiled XAML, Binaryen's recursion over nested ifs ran past the 512 KiB
    stacks macOS gives worker threads. They now search their candidates, as
    virtual calls do, so the code nests only as deep as the search's halvings and
    each lookup takes logarithmic time. A build tool that fails without output
    now reports its exit code or signal.
  • Arrays of function pointers, such as delegate*<int, int>[] and its
    multidimensional forms, compile; they stopped the build with NW1008. A
    function pointer type reports what .NET reports: IsFunctionPointer,
    IsUnmanagedFunctionPointer by its calling convention, a class with no base
    type, the name System.Int32(System.Int32) from ToString(), and the pointer
    size from Marshal.SizeOf. typeof(int*).IsValueType, and the same for a
    function pointer type, is false, as in .NET; it was true. A struct that
    holds a function pointer compares it in Equals.
  • Vector128's GetLower, GetUpper, WithLower, WithUpper, Create from
    two Vector64 values and Vector64.ToVector128 move a half in one lane load
    or store, as .NET's JIT expands them, instead of copying the vector through
    memory; a 4x4 float transpose written with them runs about ten times faster,
    as fast as its Shuffle form (#246). Small core library methods marked
    [Intrinsic] that NetWasm keeps as managed code are inlined at O1, O2 and Oz
    too, as the JIT expands them, where they used to stay calls outside loops.
  • Vector64<T> values live in SIMD registers, as Vector2 already did and as
    .NET's JIT keeps them, instead of in memory: GetUpper, WithLower,
    WithUpper, Create from two halves and ToVector128 are one shuffle each,
    and GetLower costs nothing.
  • A Vector2, Vector3, Vector4 or Quaternion local or argument written
    through its address stays a SIMD register value, as .NET's JIT keeps a
    promoted SIMD local: a lane assignment (v.X = a, v.Y += a), an indexer
    store, a ref local, an Unsafe.As view, an inlined ref or in
    parameter, and a vector field of a struct local. Such methods used to keep the
    vector in a value frame and store and reload it at every assignment.
  • Code that writes into a buffer and updates fields in a row, as a writer's
    buffer[length++] = b does, reloads less from memory. From O1, a field read
    right after a store through the same local, or to the same static, takes the
    stored value. At O2, O3 and Oz, accesses of one array within a block read its
    length once and check it for null once. A method whose only calls that can
    collect are in one arm of its leading if, as a grow-on-demand check is,
    enters and leaves its GC root frame in that arm alone, now at Os and Oz too.
    An instance method whose every caller has already checked its object, as
    callvirt does, no longer tests this for null.
  • Static methods of a type with an explicit static constructor inline into each
    other, and such a method checks its type's initialization once, at its entry,
    instead of before every call and field access. Code that keeps its helpers in
    one class with a static constructor, as SIMD kernels with precomputed
    constants often do, no longer pays for a check per helper call.
  • A method with .locals init that is inlined finds the locals it reads before
    writing them zero each time it runs, as it would as a call. Inlined into a
    loop, or into a method with [SkipLocalsInit], a local read through
    Unsafe.SkipInit or a struct field it never wrote used to keep the previous
    iteration's value. This is the inlining counterpart of the stackalloc fix
    (#245).
  • Core library members carry .NET's own inlining attributes again: 228 had lost
    AggressiveInlining and 317 [Intrinsic] (among them Math, MathF,
    Single and Double helpers, integer Log2 and DivRem, Interlocked,
    Volatile, ValueTask and the async method builders), so they inline where
    the JIT inlines them, at Oz too. Math.Abs of an integer throws its
    OverflowException with desktop's message.
  • O2 and Oz inline a callee of at most 16 IL bytes that neither allocates nor
    throws wherever it is called, as .NET's JIT always inlines such a callee;
    they used to inline outside loops only what asked to be inlined and field
    accessors. Small forwarding and arithmetic helpers no longer cost a call, and
    most programs get smaller at Oz.
  • Inside a loop, a straight-line helper that makes no calls and does not branch
    inlines when it fits the 128 IL bytes .NET's JIT weighs a loop's callee by,
    not only when it has at most 32 instructions: a pixel helper that packs four
    channels no longer costs a call per pixel.
  • O3 and Oz no longer merge every large function into its only caller:
    Binaryen's single-caller inlining stops at a function of 1,000 expressions, so
    a decoder's pixel loop keeps its pointers in registers instead of in a
    function too large for the engine's register allocator.
  • A static readonly array that nothing reads loses its element initialization
    also when the elements' struct constructor is inlined, at every optimization
    level; at O3 such arrays used to keep it.
  • A conditional block that stores one value and then checks it, throwing when
    the check fails, as Math.Abs does, becomes a select and one branch to the
    throw, instead of branching on the data, which mispredicts on values such as
    an image codec's residuals. A parameter assigned in an if
    (if (x < 0) x = 0;) becomes a select as a local does.
  • Enum operations, Array.CreateInstance, GetValue and SetValue,
    RuntimeHelpers.GetUninitializedObject and RunClassConstructor,
    Nullable.GetUnderlyingType, struct marshalling, unboxing checks, exception
    filters and finalizers search the program's types instead of testing each in
    turn, so their cost no longer grows with the number of types in the program.
  • Type names are on in every configuration (NetWasmTypeNames defaults to
    true; it was on only in Debug). They stay in the type-symbols sidecar, and
    only a program that reads a name carries the code that loads them; a program
    that reads none, such as Console 42, carries none of it. That code is also
    smaller, and names are made as they are read rather than all at startup. A Release program that probes for a type by name, as
    Microsoft.Data.Sqlite's bundle initializer does, now gets null for a type it
    doesn't have, as in Debug. NetWasmTypeNames=false opts out: names read
    type#<id>, and looking a type up by name throws
    PlatformNotSupportedException.
  • [SkipLocalsInit] is honored: localloc zeroes its block only under
    localsinit, and reference-free locals are not zeroed at entry. CoreLib and
    NetWasm.App's libraries compile with it, as .NET's do.
  • GC.AllocateUninitializedArray skips the collector's clear for large arrays
    of reference-free elements, as .NET does; ArrayPool and ToArray calls
    reach it. A program that never calls it pays nothing.
  • Megamorphic virtual calls share one dispatch function per declaration, and
    Enum.ToObject's code grows with the number of enums, not its square, which
    makes large UI programs much smaller.
  • A tail.-prefixed call runs as an ordinary call, as compiled XAML needs.
  • MemoryMarshal, Buffer and Array.Copy take upstream's bodies and element
    type rules.
  • Enum.IsDefined<TEnum> inlined into ordinary code produced invalid
    WebAssembly that failed the build; it compiles.
  • A static virtual call on a type that does not implement the method runs the
    interface's default implementation. It used to run an overload whose
    parameters only shared their stack kinds, so generic UTF-8 parsing of
    Decimal32, Decimal64 and Decimal128 always failed.
  • NetWasm.App ships System.Text.Encoding.CodePages.
  • Methods publish far fewer roots at their calls, so large methods are smaller
    and spend less time on bookkeeping. A method with an exception filter no
    longer copies every local the filter can see at each call: the collector
    reads them where they live. A value held on the evaluation stack across
    several calls is published once, and a method with many references zeroes
    its frame on entry instead of clearing dead slots at its first calls. Large
    async methods that catch with filters gain the most; TUnit's test engine
    shrinks by several megabytes at O3.
  • Code behind a platform check NetWasm is not, such as
    OperatingSystem.IsWindows(), IsLinux(), their VersionAtLeast forms,
    OperatingSystem.IsOSPlatform("windows") or
    RuntimeInformation.IsOSPlatform(OSPlatform.Linux), is left out before its
    references are resolved, so an assembly only another platform's code uses
    (DnsClient's Microsoft.Win32.Registry) need not be present. Debug builds'
    combined || and && checks are covered too.
  • Libraries built for the browser by .NET's SDK work in NetWasm programs. In
    a program a JavaScript host runs, their [JSImport] methods, whose bodies
    .NET's JavaScript generator wrote, are NetWasm's own imports and call
    JavaScript, and their [JSExport] methods join the module's open()
    object, Task results included. A binding whose shape NetWasm's interop
    does not take, such as an export with a delegate parameter, stays an
    ordinary method with warning NW1018, where it used to stop the build.
    Without a JavaScript host, as in a WASI component, the imports compile as
    ordinary code: CoreLib has .NET's JavaScript binding surface
    (JSFunctionBinding, JSMarshalerType, JSMarshalerArgument), whose
    members throw PlatformNotSupportedException, as .NET's do on platforms
    without a browser.
  • The compiler's build warnings NW1016 (a missing member compiled to a
    throw), NW1017 (an unlinked native library) and NW1018 (a declined
    JavaScript binding) appear in the build output; nwc used to keep them in
    its diagnostic log only.
  • A [JSExport] method returning Task that a program calls from C# compiles
    in a program without a JavaScript host, where nothing is exported; it used to
    stop the build with NW1008.
  • NetWasmGC paces collections by what survives them. When at least 60% of the
    heap survives a collection, as while a program builds data it keeps, the
    heap may grow to three times the survivors before the next one, not twice.
    A collection is never due before small objects refill the most they have
    occupied before, which takes no new memory. When no memory is left before a
    collection is due, an allocation collects once and tries again before it
    throws OutOfMemoryException. See
    Collection policy.
  • The runtime exports collect_when_idle, for a host to call between calls
    into the module when it is idle: the collector then collects if the heap has
    grown enough for that to be worth its while, so the collection need not
    happen during the next call. A JsModule in a page does this itself, in the
    browser's idle periods; in a session of mixed interactions it moved most
    collections out of the interactions and halved the heap's size. A JsModule
    in a worker or in Node.js does the same on a short timer.
  • The runtime exports collect_when_quiet, which collects whatever the heap
    has grown by and reports the share it freed. A JsModule host calls it once
    the module has run and then stayed quiet for a second or more, so what a
    program drops without allocating, as when it clears a table, does not stay
    in the heap while the page sits idle. It paces itself by what each such
    collection freed and took. See
    Collection policy.
  • A component's event loop gives the collector the time an asynchronous
    program waits, as a JsModule host does: an idle collection a fifth of a
    second after the program last ran and a quiet one once it has not run for a
    quiet period, on timers that never keep the loop waiting. A synchronous
    Main is unchanged.
  • A component's event loop runs the finalizers a collection has queued while an
    asynchronous program keeps working, as Mono's single-threaded runtimes run
    them from their event loop. They used to run only when a call into the
    program returned, so an asynchronous program that kept working, yielding
    between steps, kept every finalizable object it dropped, and everything that
    object referenced, until Main returned. An exception a finalizer lets
    escape ends the program, as one on .NET's finalizer thread does.
  • A faulted task whose exception is observed, by await or by reading
    Exception, no longer stays registered for finalization, as .NET's
    TaskExceptionHolder stops reporting a handled fault. Each awaited fault kept
    about 320 bytes until its tracker was finalized: a loop that awaited and
    caught 3,000,000 faults held 967 MB, and one that caught more ran out of
    memory. An unobserved fault still raises TaskScheduler.UnobservedTaskException.
  • NetWasmGarbageCollector=NetWasmGen selects NetWasmGC with generations, an
    opt-in collector for programs that keep a large set of objects alive and
    allocate short-lived ones on top. Most of its collections look only at the
    objects allocated since the last one and at the older objects a reference
    was stored into since, which the program records: a program built for it
    follows each store of a reference with a write barrier, and the link refuses
    its runtime for a program built for another collector. A program built for
    any other collector has no barrier and imports nothing new. A store into an
    object allocated with no collection possible since has no barrier, nor has
    a constructor's store into its this before anything in it can collect when
    every way the program reaches the constructor passes an object just
    allocated. Under it
    GC.MaxGeneration is 1, GC.GetGeneration tells an object that has
    survived a collection from a new one, and GC.Collect(0) runs a minor
    collection, which frees young objects only. See
    Choosing a garbage collector.
  • nwc -gc:<collector> names the collector a program is compiled for; the
    SDK passes NetWasmGarbageCollector.
  • The compiler's diagnostic log (-p:NetWasmDiagnosticLogPath=<path>) records
    the compiler's memory after each stage and every 30 seconds, and the growth of
    its reachability analysis every 10 seconds: methods and types reached, methods
    queued, and the generic definitions with the most instances. A compile that
    runs out of memory leaves them in the log up to the failure. See
    Compiler support bundles.
  • The diagnostic log keeps Debug entries and up by default; it used to keep
    Trace too, an entry for each emitted function and each method's metrics,
    which for a large program is hundreds of megabytes.
    -p:NetWasmDiagnosticLogLevel=Trace (nwc -diagnosticloglevel:Trace) keeps
    them, and any other level of Microsoft.Extensions.Logging sets the least
    severe entries the log keeps.
  • The SDK no longer sets DOTNET_GCgen0size and DOTNET_GCLOHThreshold for
    nwc. They were budgets for the .NET server collector; nwc has collected
    with Satori since 0.11.2, which does not read them.
  • A module initializer ([ModuleInitializer]) runs once, before the
    program's first code: before Main, or before the first export or callback a
    host calls. It used to run while the host instantiated the component, where
    WASI 0.3 lets nothing wait, so one that wrote to the console or read a type
    name stopped the program before Main under NetWasm's JavaScript host.
    TUnit.Core's module initializer reads a type name, so a program that
    referenced TUnit could not start.
  • A component without Main, such as a library of WIT exports or an HTTP
    service, reads local time and type names when its code first needs them, as
    a JavaScript module does. With TZ set to a zone, every export of such a
    component used to fail, even one that never reads local time.
  • A method whose branches nest thousands deep compiles. A 3,000-arm
    if/else if chain made the compiler overflow its stack at every
    optimization level, and so did a Debug build of a program that queries an
    attribute on a run-time Type that thousands of types carry, as
    type.IsDefined(typeof(CompilerGeneratedAttribute), false) does. The
    compiler's passes now run on threads with a large stack, and its
    control-flow component analysis no longer recurses.

JavaScript interop

Code written for .NET's browser runtime ports with fewer changes:

  • A dotted import name, such as [JSImport("Format.wrap", "app.bundled")], is
    a path through its module, and the function runs with the object it was
    found on as this. An import without a module names a global function as
    "globalThis.<path>", as .NET resolves it; other module-less names fail the
    build with the rule named.
  • JSObject has .NET's property API: HasProperty, GetTypeOfProperty,
    GetPropertyAs{Boolean,Int32,Double,String,JSObject,ByteArray},
    SetProperty and IsDisposed. A program pays only for the members it calls.
  • JSHost.GlobalThis is the global object, and JSHost.ImportAsync
    completes with a module the build declares or the host supplies, so code
    that imports its module before calling into it runs unchanged.
  • An import of any result takes callbacks, as .NET's does: a delegate passed
    to an import that returns no JSSubscription belongs to JavaScript and
    stays alive until JavaScript collects the function it received.
    JSSubscription remains the way for C# to end a callback itself.
  • An import takes an ArraySegment<T> of a number as .NET's MemoryView:
    JavaScript gets an IMemoryView that reads and writes the array in place
    and keeps it alive until disposed, so an asynchronous import can take one.
  • undefined reads as null for a string, JSObject, array or nullable,
    whether an import returns it, a Promise settles with it or JavaScript passes
    it to an export.
  • A plain JavaScript array of numbers entering C# is copied into the number
    array, as a typed array is.
  • An export called with fewer arguments than it declares gives the rest their
    defaults. More arguments than it declares are still an error.
  • A JsModule, worker, CoreModule or Component links its packages'
    assemblies, as an executable does.
  • A page's generated module (<Assembly>.mjs) starts every startup download
    when it loads: it preloads the page bundle and the runtime modules, and
    fetches deployment.json and the files the runtime reads at startup, which
    open() hands to the runtime to verify and use. They used to be found one
    import or one fetch at a time.
  • A number array (byte[], double[] and the others) that crosses from
    JavaScript into C#, as an export's or a callback's argument or an import's
    result, is copied straight into the program's memory, and C# builds the
    array from it with one copy. It used to cross through a handle that C# read
    back with calls into JavaScript. In Chromium at O3, a callback taking an
    int and a five-byte byte[] went from about 1.5 to 0.7 microseconds a
    call, and an export taking them from about 1.1 to 0.4.
  • A page loads less of the runtime. It preloads only the runtime modules it
    imports at startup; the SHA-256 that a page without crypto.subtle (one
    served over plain HTTP) falls back to loads the first time such a page
    hashes; and a page or worker whose program links no filesystem leaves out
    the code that mounts the program's sidecar files.
  • Every browser runtime file asks V8 to compile its functions as it loads
    (//# allFunctionsCalledOnLoad), so a page's first calls do not wait for
    lazy compilation.

APIs newer than .NET Standard 2.1

A package's net8.0 or newer build reaches members its .NET Standard build
does not. These now behave as upstream's WASI build does:

  • System.Net.Http has .NET 11's public surface: synchronous HttpContent
    serialization (ReadAsStream, CopyTo, overridable SerializeToStream and
    CreateContentReadStream), HttpVersionPolicy with HttpClient's default
    request version and policy, the cancellable Get*Async overloads,
    HttpHeaders.NonValidated, HttpMethod.Query, Connect and Parse,
    HttpIOException, HttpProtocolException, MultipartContent's header
    encoding selector, and gzip and Brotli compressed content.
    Zstandard content is not supported.
  • TLS: SslStream is a TLS client over WASI's wasi:tls, and upstream's
    SocketsHttpHandler (connection pooling, HTTP/1.1 and HTTP/2, without
    HTTP/3) runs over WASI sockets and it, so wss:// and SmtpClient's
    EnableSsl work too. A program that can reach TLS imports wasi:tls, which
    its host must provide; NetWasm's Node.js host does, and Wasmtime with
    -Stls. For a host without it, <NetWasmTlsSupport>false</NetWasmTlsSupport>
    leaves the import out, and SslStream throws
    PlatformNotSupportedException.
  • System.Net.Http.Json adds the source-generated metadata overloads of
    DeleteFromJsonAsync, PatchAsJsonAsync, GetFromJsonAsAsyncEnumerable
    and ReadFromJsonAsAsyncEnumerable, and JsonContent serializes
    synchronously. The reflection-based overloads stay outside the profile.
  • System.Text.Json's source-generated metadata covers interface, concurrent,
    immutable, stack and queue collections, Memory<T>, DateOnly,
    TimeOnly, Half, Int128, UInt128, the IEEE decimals, BFloat16,
    Memory<byte> and JsonDocument, which failed the build before. The
    JsonElement and JsonDocument overloads of JsonSerializer,
    JsonDocument.ParseAsync, JsonNode.ParseAsync, JsonMarshal and
    JsonNumberEnumConverter<TEnum> are there too, and so are
    JsonException's legacy serialization constructor and GetObjectData,
    which a library's exception derived from it may call.
  • HttpStatusCode is in System.Net.Primitives, as on .NET, and
    System.Net.Http forwards it for programs built against earlier releases.
  • A package built against an older contract that declared a type .NET has
    since moved binds as on .NET: System.ComponentModel.TypeConverter
    forwards Component, ISupportInitialize, TypeConverterAttribute and the
    other component types it used to declare, System.Net.Requests forwards
    WebHeaderCollection and HttpRequestHeader, and
    System.Runtime.Serialization.Xml forwards
    InvalidDataContractException. System.Drawing, WindowsBase and
    System.ServiceModel.Web are facades for the types NetWasm.App has
    (Color, Point, ObservableCollection<T>, DataContractJsonSerializer
    and the rest).
  • IPNetwork, and DecompressionMethods.Brotli, Zstandard and All.
  • RuntimeHelpers.AllocateTypeAssociatedMemory, and
    Marshal.GetExceptionPointers, which throws PlatformNotSupportedException
    as on NativeAOT and Mono.
  • StackTrace(IEnumerable<StackFrame>).
  • X509Certificate2.CreateFromPem, CreateFromPemFile,
    CreateFromEncryptedPem and CreateFromEncryptedPemFile.
  • NetWasm.App has a System.Runtime.InteropServices.JavaScript facade, so a
    package that names its types binds.
  • System.Runtime.Loader is complete. AssemblyLoadContext.Default holds the
    program's assemblies and resolves names as Assembly.Load does, a context
    the program creates resolves through its own Load first, and unloading and
    contextual reflection behave as on .NET. Loading from a path, a stream or a
    native library throws PlatformNotSupportedException, as Assembly.LoadFrom
    does. AssemblyDependencyResolver, MetadataUpdater and
    AssemblyExtensions.TryGetRawMetadata behave as on Native AOT.
    Microsoft.Testing.Platform looks for optional extensions through them.
  • NFloat is float on wasm32 and double on wasm64, as on .NET's 32-bit and
    64-bit platforms: its size, bits, arithmetic, parsing and formatting follow
    the native type.
  • System.Diagnostics.Process has .NET 11's public surface: the
    ProcessStartInfo argument-list constructor and launch settings, Run,
    RunAsync, RunAndCaptureText, StartAndForget, the ReadAll* readers,
    WaitForExitAsync, the exit-status methods, Kill(bool), Signal,
    TryGetProcessById, the newer SafeProcessHandle members and the
    process start-argument types. NetWasm cannot start processes, so each one
    checks its arguments as .NET does where processes cannot be started (iOS
    and tvOS) and then throws PlatformNotSupportedException.
  • CryptographicOperations has the HMAC one-shots (HmacData,
    TryHmacData, VerifyHmac and their stream and asynchronous forms) and
    HashDataAsync.
  • Task.WaitAll(ReadOnlySpan<Task>), Task.WaitAll(IEnumerable<Task>, CancellationToken) and Task.Wait(TimeSpan, CancellationToken).
  • NetWasm.App ships System.ComponentModel.DataAnnotations. Each validation
    attribute validates a value itself, with .NET's messages, and
    Validator.TryValidateValue and ValidateValue (and their async forms)
    validate a value against the attributes given. Validating an object or a
    property finds the attributes by reflection, which NetWasm does not support:
    those Validator methods throw PlatformNotSupportedException.
    Microsoft.Extensions.Options' [OptionsValidator] generator validates
    options without reflection.
  • System.Text.Json serializes polymorphically: a value typed object is
    written as its runtime type, which the source-generated context must
    describe (as on .NET), and [JsonPolymorphic] and [JsonDerivedType]
    hierarchies write and read their type discriminators. The port wrote such
    values as {} and ignored derived types before. NetWasm reads no attributes
    at run time, so the polymorphism comes from the generated metadata, which
    .NET 11's System.Text.Json generator emits. A program without polymorphic
    types or object-typed values carries none of this code.
  • NetWasm.App.Ref ships .NET 11's System.Text.Json and Regex source
    generators, which match NetWasm.App's .NET 11 libraries. They load into the
    compiler of any supported .NET 10 SDK.

Qualified packages

Each runs a program on NetWasm, wasm32 and wasm64, Debug and Release, and
compares its output with desktop .NET's. CI now builds the ones marked (CI)
on every change, at the versions named here, from that change's packages
(eng/open-source-suts):

  • Avalonia 12 headless with Skia, compiled XAML and the Fluent theme: a
    rendered frame's pixels.
  • SixLabors.ImageSharp 3.1.12 (CI): resampling, rotation, color processing
    and the PNG, JPEG, TIFF, BMP, GIF and WebP codecs.
  • Sdcb.SimdCodecs 2.0.0 (CI): PNG, JPEG (baseline and progressive), WebP
    (lossy and lossless), QOI and BMP, encoded and decoded at full and half
    scale.
  • MemoryPack 1.22.0 (CI): classes, records, structs, unions, version-tolerant
    types and collections. Register each type with
    MemoryPackFormatterProvider.Register<T>(), and a collection serialized on
    its own with its formatter, as for MemoryPack's other ahead-of-time targets:
    otherwise MemoryPack registers them by reflection on first use.
  • Sep 0.18.0 (CI): CSV parsing and writing.
  • Microsoft.Extensions.Configuration 11.0.0 (CI): its in-memory, JSON and
    command-line providers.
  • SwitchMediator 4.0.0 (CI), a source-generated mediator with MediatR's API,
    over Jab 0.12.0, a source-generated container: requests and notifications.
  • System.IO.Hashing and System.Formats.Cbor 11.0.0, Microsoft's packages as
    published: every hash with its streaming and stream APIs, and CBOR writing
    and reading in every conformance mode, match desktop .NET 11. Their
    NetWasm.System.IO.Hashing and NetWasm.System.Formats.Cbor ports are not
    released for 0.15; their last releases keep serving netwasm0.1 projects.
  • FluentValidation 12.2.0, the package as published: validators, rule sets,
    collection and child rules, polymorphic validators, custom messages, nested
    struct members and boxing conversions in rules run in a net10.0-netwasm
    project. A culture other than the invariant one is unavailable, as NetWasm's
    globalization is invariant. NetWasm.FluentValidation is not released for
    0.15; its last release keeps serving netwasm0.1 projects.

Breaking changes

  • New projects target net10.0-netwasm; netwasm0.1 is deprecated. A
    net10.0-netwasm project cannot use a package built only for netwasm0.1;
    rebuild the package for net10.0-netwasm, or keep its consumers on
    netwasm0.1 until it is.
  • NetWasm.System.IO.Hashing and NetWasm.System.Formats.Cbor have no 0.15
    release. A net10.0-netwasm project references Microsoft's System.IO.Hashing
    and System.Formats.Cbor instead.
  • NetWasm.FluentValidation has no 0.15 release. A net10.0-netwasm project
    references FluentValidation itself.
  • NetWasm.Microsoft.Extensions.Primitives,
    NetWasm.Microsoft.Extensions.Configuration,
    NetWasm.Microsoft.Extensions.Configuration.Abstractions,
    NetWasm.Microsoft.Extensions.Configuration.EnvironmentVariables,
    NetWasm.Microsoft.Extensions.Configuration.CommandLine,
    NetWasm.Microsoft.Extensions.Configuration.Json and
    NetWasm.Microsoft.Extensions.Caching.Abstractions have no 0.15 release.
    Reference Microsoft's packages of the same names instead; the 0.15
    NetWasm.Libraries packages already depend on them.
  • NetWasm.Libraries packages target net10.0-netwasm only. A netwasm0.1
    project keeps the earlier packages built for it.
  • NetWasmTypeNames defaults to true in Release too. A Release program that
    reads type names now loads <program>.wasm.type-symbols at startup; deploy it
    beside the program, or a host that does not mount it gets one "skipped" line
    on standard error and the names read type#<id>. Set
    NetWasmTypeNames=false for the previous Release behavior.

Known gaps

These are known in this release. We plan to address them soon.

  • NetWasm.Microsoft.Extensions.DependencyInjection resolves an IEnumerable<T>
    only where the program's own source asks for it, which its build-time
    generator reads. A sequence asked for from a library's compiled code is not
    found: SwitchMediator's notifications through AddMediator<T>() are one
    case. SwitchMediator works over Jab (see Qualified packages).
  • Array.CreateInstance(elementType, length) creates only an array whose type
    the program itself uses; for any other it throws NotSupportedException.
  • With NetWasm.Microsoft.Extensions.DependencyInjection:
    • a sequence of a private nested service type (GetServices<T>() with a
      private T) does not build;
    • a generic method that resolves its own type parameter
      (provider.GetRequiredService<T>()) does not build (NWDI010);
    • ActivatorUtilities.CreateInstance<T> needs T to be registered;
    • scope validation's error does not name the scoped service.
  • With NetWasm.Microsoft.Extensions.Configuration.Binder, a type without a
    public parameterless constructor (a record or another type bound through its
    constructor) does not build, and Half cannot be bound (NWCFG011).
  • IL that compares an int32 with a native int directly is rejected with
    NW1002. C# converts one side first, so only hand-written IL or another
    compiler's output meets this.
  • GetCustomAttribute<T>() and GetCustomAttributes(Type) on an Assembly
    with a closed generic attribute type, such as TagAttribute<short>, throw
    PlatformNotSupportedException.
  • Some code runs slower than with 0.14.2. Of the 2,213 cases in NetWasm's
    micro-benchmark suite (O3, NetWasmGC, Wasmtime), 37 take more than 5% longer,
    confirmed at two code alignments, while 584 take at least 5% less:
    • A method that needs a frame for the collector's roots on one path only can
      set that frame up on entry, on every call, where 0.14 set it up only on
      that path. Dhrystone's Proc1 is one such method: the Dhrystone benchmark
      runs about 1.25 times as long as with 0.14.2.
    • MemoryMarshal.TryGetArray takes about 1.3 times as long, and
      Buffer.BlockCopy of 10 to 100 elements about 1.2 times.
    • LINQ's GroupBy, CountBy and OrderBy take 1.08 to 1.11 times as long.
    • Some float and double math functions (Hypot, Atan2, AtanPi,
      Asinh, Sinh, Log10, FusedMultiplyAdd) and short span searches and
      comparisons (IndexOfAny, LastIndexOfAny, LastIndexOf,
      SequenceCompareTo) take 1.05 to 1.14 times as long.
  • dotnet run --no-build of a net10.0-netwasm project can print a restore
    warning, such as a NuGet audit warning, on standard output before the
    program's own output.