Repository navigation
NetWasm 0.15.0: your NuGet packages, native ones included, and a generational collector
LatestNetWasm 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.0on 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.0names 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 runstarts anet10.0-netwasmexecutable on NetWasm's launcher.- A
net10.0-netwasmbuild takes no desktop native assets from a package's
runtimes/folder. netwasm0.1still 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-netwasmandnetwasm0.1restores a
package thatnetwasm0.1takes 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-netwasmproject cannot use a package that ships only
netwasm0.1assets: NuGet cannot read that framework back from its assets
file. Such a package needs anet10.0-netwasmornet8.0and later build. - The out-of-band libraries (dependency injection, logging, configuration
binding, options and the rest) are built fornet10.0-netwasm. - NetWasm.Microsoft.Extensions.DependencyInjection: a single service resolved
after itsIEnumerable<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 testrunsnet10.0-netwasmtest projects. VSTest reports such a
project as.NETCoreApp,Version=v10.0, like a desktop one, so
NetWasm.Testing.VSTest's build adds aNetWasm.TargetFrameworktest run
parameter by which its runtime provider recognizes the run. TUnit-NetWasm's
packages now targetnet10.0-netwasm; anetwasm0.1test project stays on
an earlier TUnit-NetWasm release. Anetwasm0.1project 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 afterTat compile time; aTypethe compiler cannot
see throwsPlatformNotSupportedException.- Assemblies have their simple names at run time.
AppDomain.GetAssemblies()
andAssembly.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, throughGetCustomAttribute,GetCustomAttributes
andIsDefined, for a sealed attribute type such as
AssemblyInformationalVersionAttributeorAssemblyMetadataAttribute.
As with type and member attributes, the compiler resolves the query; other
assembly queries throwPlatformNotSupportedException. - Attribute queries on a
Typeknown only at run time are answered: aType
parameter, a lambda's argument, a field orobj.GetType(), through
GetCustomAttribute,GetCustomAttributes,IsDefinedandAttribute'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 aMethodInfo, and filters
known only at run time still throwPlatformNotSupportedException
(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 asAttribute[], 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 throwPlatformNotSupportedException. A query for a sealed attribute
type on an assembly that also carries generic attributes no longer returns
those as well. typeofof an open generic class whose base the program uses nowhere else,
such astypeof(TagAttribute<>)in a program that creates no attribute, no
longer stops the build with NW1008, and the definition'sBaseTypeis that
base, as on .NET.
Native archives built by Emscripten
- An executable links a package's static archives built by Emscripten with no
NativeLibraryitem, in either layout packages use for .NET's WebAssembly
SDKs: SkiaSharp's and HarfBuzzSharp's, one archive per Emscripten version and
variant, and .NET'sruntimes/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 ownNativeLibraryitem replaces it. - Archives that use Wasm exception handling link in either encoding: legacy
archives are translated to exnref. Emscripten'ssetjmp/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. Alongjmpor
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
aJsModulealike. 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 = falseis
rejected;CharSet,BestFitMappingandThrowOnUnmappableCharare
accepted and change nothing.- Raw
DllImportdeclarations take desktop .NET's runtime marshalling of
SafeHandleandCriticalHandlearguments, results,outandref
parameters,HandleRefarguments and arrays of blittable elements, which
are pinned. Strings, delegates and conversions fail the build where reached. - Raw
DllImportdeclarations that keep runtime marshalling convertbooland
charas desktop .NET does on Unix, by value, by reference and as results:
boolas a 4-byteBOOLor, with[MarshalAs(UnmanagedType.U1)]orI1,
one byte;charas a UTF-16 code unit underCharSet.UnicodeorU2, and
otherwise as one ANSI byte. A[MarshalAs]that restates a scalar's own type,
such asI4on anint, is accepted. They used to fail with NW1012. - Raw
DllImportdeclarations that keep runtime marshalling pass astring
argument as desktop .NET does on Unix: a UTF-8 copy freed after the call, or
underCharSet.UnicodeorLPWStrthe string pinned, with native writes
showing in it. Astringresult is decoded from its native buffer, which is
then freed with the C library'sfree, as desktop .NET frees it. - Raw
DllImportdeclarations that keep runtime marshalling pass a struct
holding aboolorcharas desktop .NET lays it out natively on Unix: a
BOOL(or a byte withU1), 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 convertbool,char,stringand
structs that hold aboolorcharas desktop .NET's runtime marshalling
does at an unmanagedcalli: as a rawDllImportwithout 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,PtrToStructureand
DestroyStructureon a struct that holds aboolorcharuse 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
PtrToStructureinto an existing object),stringfields (UTF-8 or UTF-16
CoTaskMem copies thatDestroyStructurefrees, or inlineByValTStr),
ByValArrayarrays of primitives and null delegate fields, as desktop .NET
does on Unix, and throw desktop's exceptions for fields it rejects. As on
desktop,StructureToPtrwrites 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
PlatformNotSupportedExceptionbefore any memory is touched, in both
directions:StructureToPtrwithfDeleteOldfrees nothing, and
PtrToStructureleaves the object it fills as it was. A fixed
buffer of UTF-16chars 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
withfixedor byLibraryImport's UTF-16 marshalling reaches native code
terminated; native code used to read past its end. NativeMemory, andMarshal's HGlobal and CoTaskMem memory, are the C
library'smalloc,reallocandfree, 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'smallocblock withMarshal.FreeCoTaskMemused to corrupt
memory.- A
ref,inoroutpointer, 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.GetLastSystemErrorand .NET 11's ANSI, BSTR, UTF-16 and
pointer-array marshallers, whichLibraryImport's generated code calls, are
in CoreLib.CLongandCULongare C'slongandunsigned 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>andExceptionAsVoidMarshaller) are there
too.ComWrappers,ObjectiveCMarshalandJavaMarshal, with their flags and
callback types, are there and behave as .NET ships them where the platform
has no such interop:ComWrappers' lookups answerfalse, and their other
members throwPlatformNotSupportedException.TypeMappingthrows
NotSupportedException, as on Mono.ComVariantand
StandardOleMarshalObjectwork 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.IDynamicInterfaceCastableworks 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 askIsInterfaceImplemented,
and calls go to the default methods of the
[DynamicInterfaceCastableImplementation]interface that
GetInterfaceImplementationnames, with .NET's exceptions for an invalid
answer or a missing method. A program that never allocates such a class
pays nothing for it.NativeLibraryandDllImportResolverare 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:LoadthrowsDllNotFoundException,TryLoadreturns
false, and an export lookup fails as for a missing symbol. A registered
resolver is recorded, with .NET's checks, and the library'sDllImportcalls
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 declaressqlite3_configand
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
ReadOnlySpanof an enum, asReadOnlySpan<Color> colors = [Color.Red, Color.Green]or a call to aparams ReadOnlySpan<TEnum>method
writes, reads its elements from the program's data as one of its underlying
type does. It threwPlatformNotSupportedExceptionbefore. - A library that names a type, method or field NetWasm does not have no longer
stops the build (#252). A method that names one throwsTypeLoadException,
MissingMethodExceptionorMissingFieldExceptionwhen 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, notSystem.Object. ldfld,ldfldaandstfldon 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, asif (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 atstart + index, as a
checksum reads each chunk, testsstart >= 0andstart + 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 atstart + index - 1and 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]forindex < count, is versioned the same way. - At O3 and Oz, a loop follows its method's
intand array parameters as it
follows locals. A loop bounded by acountparameter, walking an array
parameter or reading a span atstart + indexwithstarta 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-opton macOS (NW1010,
with no message) build again.ldvirtftn, a managedcalli, cloning a
delegate,DynamicInvokeand member execution tested their candidates in
turn, one nestedifper 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 nestedifs 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,
IsUnmanagedFunctionPointerby its calling convention, a class with no base
type, the nameSystem.Int32(System.Int32)fromToString(), and the pointer
size fromMarshal.SizeOf.typeof(int*).IsValueType, and the same for a
function pointer type, isfalse, as in .NET; it wastrue. A struct that
holds a function pointer compares it inEquals. Vector128'sGetLower,GetUpper,WithLower,WithUpper,Createfrom
twoVector64values andVector64.ToVector128move 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 itsShuffleform (#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, asVector2already did and as
.NET's JIT keeps them, instead of in memory:GetUpper,WithLower,
WithUpper,Createfrom two halves andToVector128are one shuffle each,
andGetLowercosts nothing.- A
Vector2,Vector3,Vector4orQuaternionlocal 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, areflocal, anUnsafe.Asview, an inlinedreforin
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++] = bdoes, 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 leadingif, 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
callvirtdoes, no longer teststhisfor 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 initthat 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.SkipInitor a struct field it never wrote used to keep the previous
iteration's value. This is the inlining counterpart of thestackallocfix
(#245). - Core library members carry .NET's own inlining attributes again: 228 had lost
AggressiveInliningand 317[Intrinsic](among themMath,MathF,
SingleandDoublehelpers, integerLog2andDivRem,Interlocked,
Volatile,ValueTaskand the async method builders), so they inline where
the JIT inlines them, at Oz too.Math.Absof an integer throws its
OverflowExceptionwith 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, asMath.Absdoes, 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 anif
(if (x < 0) x = 0;) becomes a select as a local does. Enumoperations,Array.CreateInstance,GetValueandSetValue,
RuntimeHelpers.GetUninitializedObjectandRunClassConstructor,
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 (
NetWasmTypeNamesdefaults 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 getsnullfor a type it
doesn't have, as in Debug.NetWasmTypeNames=falseopts out: names read
type#<id>, and looking a type up by name throws
PlatformNotSupportedException. [SkipLocalsInit]is honored:localloczeroes 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.AllocateUninitializedArrayskips the collector's clear for large arrays
of reference-free elements, as .NET does;ArrayPoolandToArraycalls
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,BufferandArray.Copytake 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,Decimal64andDecimal128always 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(), theirVersionAtLeastforms,
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'sMicrosoft.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'sopen()
object,Taskresults included. A binding whose shape NetWasm's interop
does not take, such as an export with a delegate parameter, stays an
ordinary method with warningNW1018, 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 throwPlatformNotSupportedException, 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) andNW1018(a declined
JavaScript binding) appear in the build output;nwcused to keep them in
its diagnostic log only. - A
[JSExport]method returningTaskthat a program calls from C# compiles
in a program without a JavaScript host, where nothing is exported; it used to
stop the build withNW1008. - 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
throwsOutOfMemoryException. 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. AJsModulein 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. AJsModule
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. AJsModulehost 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 aJsModulehost 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
Mainis 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, untilMainreturned. 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
awaitor by reading
Exception, no longer stays registered for finalization, as .NET's
TaskExceptionHolderstops 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 raisesTaskScheduler.UnobservedTaskException. NetWasmGarbageCollector=NetWasmGenselects 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.MaxGenerationis 1,GC.GetGenerationtells an object that has
survived a collection from a new one, andGC.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 passesNetWasmGarbageCollector.- 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_GCgen0sizeandDOTNET_GCLOHThresholdfor
nwc. They were budgets for the .NET server collector;nwchas collected
with Satori since 0.11.2, which does not read them. - A module initializer (
[ModuleInitializer]) runs once, before the
program's first code: beforeMain, 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 beforeMainunder 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. WithTZset 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 ifchain 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-timeTypethat 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 asthis. 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. JSObjecthas .NET's property API:HasProperty,GetTypeOfProperty,
GetPropertyAs{Boolean,Int32,Double,String,JSObject,ByteArray},
SetPropertyandIsDisposed. A program pays only for the members it calls.JSHost.GlobalThisis the global object, andJSHost.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 noJSSubscriptionbelongs to JavaScript and
stays alive until JavaScript collects the function it received.
JSSubscriptionremains the way for C# to end a callback itself. - An import takes an
ArraySegment<T>of a number as .NET'sMemoryView:
JavaScript gets anIMemoryViewthat reads and writes the array in place
and keeps it alive until disposed, so an asynchronous import can take one. undefinedreads asnullfor 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,CoreModuleorComponentlinks 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
fetchesdeployment.jsonand 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 atO3, a callback taking an
intand a five-bytebyte[]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 withoutcrypto.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.Httphas .NET 11's public surface: synchronousHttpContent
serialization (ReadAsStream,CopyTo, overridableSerializeToStreamand
CreateContentReadStream),HttpVersionPolicywithHttpClient's default
request version and policy, the cancellableGet*Asyncoverloads,
HttpHeaders.NonValidated,HttpMethod.Query,ConnectandParse,
HttpIOException,HttpProtocolException,MultipartContent's header
encoding selector, and gzip and Brotli compressed content.
Zstandard content is not supported.- TLS:
SslStreamis a TLS client over WASI'swasi:tls, and upstream's
SocketsHttpHandler(connection pooling, HTTP/1.1 and HTTP/2, without
HTTP/3) runs over WASI sockets and it, sowss://andSmtpClient's
EnableSslwork too. A program that can reach TLS importswasi: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, andSslStreamthrows
PlatformNotSupportedException. System.Net.Http.Jsonadds the source-generated metadata overloads of
DeleteFromJsonAsync,PatchAsJsonAsync,GetFromJsonAsAsyncEnumerable
andReadFromJsonAsAsyncEnumerable, andJsonContentserializes
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>andJsonDocument, which failed the build before. The
JsonElementandJsonDocumentoverloads ofJsonSerializer,
JsonDocument.ParseAsync,JsonNode.ParseAsync,JsonMarshaland
JsonNumberEnumConverter<TEnum>are there too, and so are
JsonException's legacy serialization constructor andGetObjectData,
which a library's exception derived from it may call.HttpStatusCodeis inSystem.Net.Primitives, as on .NET, and
System.Net.Httpforwards 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
forwardsComponent,ISupportInitialize,TypeConverterAttributeand the
other component types it used to declare,System.Net.Requestsforwards
WebHeaderCollectionandHttpRequestHeader, and
System.Runtime.Serialization.Xmlforwards
InvalidDataContractException.System.Drawing,WindowsBaseand
System.ServiceModel.Webare facades for the types NetWasm.App has
(Color,Point,ObservableCollection<T>,DataContractJsonSerializer
and the rest). IPNetwork, andDecompressionMethods.Brotli,ZstandardandAll.RuntimeHelpers.AllocateTypeAssociatedMemory, and
Marshal.GetExceptionPointers, which throwsPlatformNotSupportedException
as on NativeAOT and Mono.StackTrace(IEnumerable<StackFrame>).X509Certificate2.CreateFromPem,CreateFromPemFile,
CreateFromEncryptedPemandCreateFromEncryptedPemFile.- NetWasm.App has a
System.Runtime.InteropServices.JavaScriptfacade, so a
package that names its types binds. System.Runtime.Loaderis complete.AssemblyLoadContext.Defaultholds the
program's assemblies and resolves names asAssembly.Loaddoes, a context
the program creates resolves through its ownLoadfirst, and unloading and
contextual reflection behave as on .NET. Loading from a path, a stream or a
native library throwsPlatformNotSupportedException, asAssembly.LoadFrom
does.AssemblyDependencyResolver,MetadataUpdaterand
AssemblyExtensions.TryGetRawMetadatabehave as on Native AOT.
Microsoft.Testing.Platform looks for optional extensions through them.NFloatisfloaton wasm32 anddoubleon wasm64, as on .NET's 32-bit and
64-bit platforms: its size, bits, arithmetic, parsing and formatting follow
the native type.System.Diagnostics.Processhas .NET 11's public surface: the
ProcessStartInfoargument-list constructor and launch settings,Run,
RunAsync,RunAndCaptureText,StartAndForget, theReadAll*readers,
WaitForExitAsync, the exit-status methods,Kill(bool),Signal,
TryGetProcessById, the newerSafeProcessHandlemembers 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 throwsPlatformNotSupportedException.CryptographicOperationshas the HMAC one-shots (HmacData,
TryHmacData,VerifyHmacand their stream and asynchronous forms) and
HashDataAsync.Task.WaitAll(ReadOnlySpan<Task>),Task.WaitAll(IEnumerable<Task>, CancellationToken)andTask.Wait(TimeSpan, CancellationToken).- NetWasm.App ships
System.ComponentModel.DataAnnotations. Each validation
attribute validates a value itself, with .NET's messages, and
Validator.TryValidateValueandValidateValue(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:
thoseValidatormethods throwPlatformNotSupportedException.
Microsoft.Extensions.Options'[OptionsValidator]generator validates
options without reflection. System.Text.Jsonserializes polymorphically: a value typedobjectis
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 servingnetwasm0.1projects. - 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 anet10.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 servingnetwasm0.1projects.
Breaking changes
- New projects target
net10.0-netwasm;netwasm0.1is deprecated. A
net10.0-netwasmproject cannot use a package built only fornetwasm0.1;
rebuild the package fornet10.0-netwasm, or keep its consumers on
netwasm0.1until it is. - NetWasm.System.IO.Hashing and NetWasm.System.Formats.Cbor have no 0.15
release. Anet10.0-netwasmproject references Microsoft's System.IO.Hashing
and System.Formats.Cbor instead. - NetWasm.FluentValidation has no 0.15 release. A
net10.0-netwasmproject
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-netwasmonly. Anetwasm0.1
project keeps the earlier packages built for it. NetWasmTypeNamesdefaults totruein Release too. A Release program that
reads type names now loads<program>.wasm.type-symbolsat startup; deploy it
beside the program, or a host that does not mount it gets one "skipped" line
on standard error and the names readtype#<id>. Set
NetWasmTypeNames=falsefor 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 throughAddMediator<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 throwsNotSupportedException.- With NetWasm.Microsoft.Extensions.DependencyInjection:
- a sequence of a private nested service type (
GetServices<T>()with a
privateT) does not build; - a generic method that resolves its own type parameter
(provider.GetRequiredService<T>()) does not build (NWDI010); ActivatorUtilities.CreateInstance<T>needsTto be registered;- scope validation's error does not name the scoped service.
- a sequence of a private nested service type (
- 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, andHalfcannot be bound (NWCFG011). - IL that compares an
int32with anative intdirectly is rejected with
NW1002. C# converts one side first, so only hand-written IL or another
compiler's output meets this. GetCustomAttribute<T>()andGetCustomAttributes(Type)on anAssembly
with a closed generic attribute type, such asTagAttribute<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'sProc1is one such method: the Dhrystone benchmark
runs about 1.25 times as long as with 0.14.2. MemoryMarshal.TryGetArraytakes about 1.3 times as long, and
Buffer.BlockCopyof 10 to 100 elements about 1.2 times.- LINQ's
GroupBy,CountByandOrderBytake 1.08 to 1.11 times as long. - Some
floatanddoublemath 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.
- A method that needs a frame for the collector's roots on one path only can
dotnet run --no-buildof anet10.0-netwasmproject can print a restore
warning, such as a NuGet audit warning, on standard output before the
program's own output.