Repository navigation
NetWasm 0.13.0: programs carry no type names, calls through unmanaged function pointers, smaller programs
NetWasm 0.13.0: programs carry no type names, calls through unmanaged function pointers, smaller programs
NetWasm 0.13.0 is available on NuGet.org.
This release breaks programs that print or compare type names: a program no
longer carries them, so a type reads type#<id> unless its names are loaded
from a file beside the program. In exchange, one GetType().Name no longer
grows every program by the names of all its types. Reflection over a program's
types now answers much as on .NET (Type.Assembly, GetInterfaces,
GetElementType, Attributes, GetTypeInfo() and lookups over the program's
types), from one compact table that holds each part only when a program can ask
for it. It also adds calls through unmanaged function pointers, makes async
programs about half the size and the program that prints 42 26% smaller, and
fixes the console output that JavaScript hosts could lose.
Type names come from a file beside the program
- Breaking:
Type.Name,FullNameandToString()readtype#<id>, the
type's runtime ID (type#37), andNamespaceisnull. So do the default
Object.ToString()andValueType.ToString(), the start of
Exception.ToString(), and every framework message built from a type.
Nothing throws for a name, and each type's text is unique, so maps keyed by
type name keep working
(#225). - Why: one reachable name read made every type with a runtime descriptor carry
its name. The program that prints 42 grew from about 38.5 KB to 50.1 KB with
oneGetType().Name, and to 56.2 KB with oneGetType().FullName. Names are
now pay for use. NetWasmTypeNames(on in Debug, off in Release) writes every type's names,
and its assemblies' names, to<program>.wasm.type-symbolsbeside the
program; with it, names read exactly as .NET forms them, assembly names
included (CoreLib's isNetWasm.CoreLib). Without it an assembly name reads
<Assembly name unavailable>.
A component that exports synchronous WIT functions and has no process entry
cannot read files when it starts, so its names read as IDs.
Every build writes the exception types' names there, so a host's crash report
names an unhandled exception's type even in Release.NetWasmManagedStackTrace(on in Debug) writes method names, and file and
line in Debug, to<program>.wasm.method-symbols. Without it, a frame reads
method#<id>.- Breaking: every file beside the program, time zone data included, is opened
under/netwasm-sidecars/by the name the build gave it (App.wasm.tz-info
replaces/netwasm-timezones/netwasm-timezones.nwtz). Mounting the build or
publish folder there just works:
wasmtime run --dir bin/Debug/netwasm0.1::/netwasm-sidecars App.wasm.
NetWasm's JavaScript hosts mount the same names. - A missing, unreadable, malformed or stale symbols file never fails a program:
it runs as if built without names, after one line to standard error. ILogger<T>categories keep their names (Namespace.Type): NetWasm's
dependency injection generator writes them when it compiles the program.- Member names (
MemberInfo.Name, which expression trees and FluentValidation
read) stay in the program: only members a program reads carry one.
Type information in one table
- A program describes its types in one bit-packed table that the runtime reads
once when the program starts, where it made one registration call per type.
The runtime keeps in memory only what allocation, the collector, boxing and
casts read;Type's queries read the rest of the table where it lies. Type.DeclaringType,ReflectedTypeandIsNestedanswer as on .NET 11,
where they threwPlatformNotSupportedException: a nested type of a generic
type reports the open definition (typeof(Outer<int>.Inner).DeclaringTypeis
typeof(Outer<>)), a generic type parameter its owner, and an array, pointer,
primitive orNullable<T>null.Type.GetGenericTypeDefinition()returns a constructed type's open
definition, where it threwPlatformNotSupportedException.Type.AssemblyandAssembly.GetAssembly(Type)return oneAssemblyper
assembly, where they threwPlatformNotSupportedException, so assemblies
compare and key as on .NET.Assembly.GetExecutingAssembly()returns the
calling method's assembly andGetEntryAssembly()the entry point's. An
assembly answers as a NativeAOT one does (an emptyLocation, one module
named<Unknown>), andGetTypes()andGetExportedTypes()list its types.
GetCallingAssembly(),Assembly.Load, resources and assembly attributes
stay outside the profile.Type.GetElementType(),GetInterfaces(),GetInterface(string),
GetNestedTypes(),GetNestedType(string),Attributesand the queries
built on it (IsPublic,IsVisible,IsSerializable, the visibility and
layout queries),GenericParameterPosition,GenericParameterAttributes,
Type.ModuleandIsAssignableToanswer as on .NET 11, where they threw
PlatformNotSupportedExceptionor were missing.IsByRefLikeistruefor a
ref struct, and a generic parameter is a class or, under thestruct
constraint, a value type, withObjectorValueTypeas its base type.- With type names loaded (
NetWasmTypeNames),Type.GetType(string),
Assembly.GetType(string)andModule.GetType(string)find the program's type
whoseFullNameorAssemblyQualifiedNameis the string, and
GetNestedType(string)andGetInterface(string)match by name. Without type
names they throwPlatformNotSupportedException.
MakeArrayType,MakePointerType,MakeByRefTypeandMakeGenericType
return the program's type, and throwPlatformNotSupportedExceptionfor one it
does not use. Type.GetTypeInfo()returns the type itself, as on .NET, where it threw
PlatformNotSupportedException: a type'sTypeobject is aTypeInfo,Type
is abstract, andImplementedInterfaces,GenericTypeParameters,
DeclaredNestedTypesandAssembly.DefinedTypesanswer.- These lists and lookups see only the types a program uses, as the compiler
leaves every other type out of it. - CoreLib's types carry the
[Serializable]andsealed.NET gives them, so
IsSerializableandIsSealedanswer as on .NET forObject, the primitives
and the exception types. Type.GetArrayRank(),IsTypeDefinition,IsGenericParameter,
IsGenericTypeParameterandIsGenericMethodParameteranswer as on .NET,
where they returned 0 orfalsefor every type.- What any type can be asked at run time costs a few bits per type, and
everything past its kind, base type and assignability is in the table only
when a program reads it. Member information (aMethodInfo, a
PropertyInfo, a delegate'sInvokesignature) exists only for what the
compiler sees a program name. - Breaking:
Delegate.DynamicInvokeon a value typedDelegateor
MulticastDelegateruns only a parameterlessAction, or a parameterless
Func<T>whoseTis a reference type, and throws
PlatformNotSupportedExceptionfor any other delegate. Only the run knows
that delegate's type, and running any delegate would put every delegate
type'sInvokesignature and invocation code into every program that calls
it once. Called on a value of its own delegate type (Func<int, int> f; f.DynamicInvoke(1)), it works as before, and only that type carries the
code. - Breaking:
Expression.Invokeon an expression that is not a lambda, such as a
parameter or constant of a delegate type, throws
PlatformNotSupportedExceptionfor the same reason. Invoking a lambda
expression works as before.
Calls through unmanaged function pointers
delegate* unmanaged<...>calls native functions and[UnmanagedCallersOnly]
methods with the C ABI's scalar, narrow, floating-point, pointer and
aggregate signatures
(#226). A call through a
managed function pointer with a value type result compiles too.- Every calling convention .NET accepts on its 64-bit platforms means the C ABI,
as it does there:Cdecl,StdcallandThiscall, with
SuppressGCTransitionorMemberFunction, on a function pointer, an
[UnmanagedCallersOnly]method or a[DllImport](itsCallingConvention
or[UnmanagedCallConv]). TheCallConvtypes that name them are now in the
framework, and an import marked[SuppressGCTransition]compiles.Fastcall,
which .NET rejects everywhere,Swift, which it supports only on Apple
platforms, and two base conventions at once fail withNW1012naming them. sbyte,byte,shortandushortcross as C's narrow integers in imports,
callbacks and function pointers, as on .NET, whereNW1012refused them.- Several
DllImports of one native function, such as anIntPtrand a
byte*overload, share its import, where the build failed withNW1009.
Declarations whose C signatures differ fail withNW1012naming both.
Smaller programs
- An async method's state machine publishes the references it holds to the
collector precisely and once: a byref (a struct'sthis, as inMoveNext) is
published, never everything it points into, an argument that never changes
is not republished at every await, and what one path already published is not
published again where paths join. Roots stay as precise as desktop .NET's. - With that and type names leaving the program, an async workload of eight
patterns (completed and suspendingTasks andValueTasks, chains,
Task.Yield,IValueTaskSource, ping-pong,IAsyncEnumerable,
Task.WhenAll) is about half the size in Release: 297,847 -> 144,459 bytes
with the Compact collector atOz(Brotli-11 46,989 -> 38,621), 301,848 ->
148,483 with NetWasmGC, and 484,480 -> 300,651 with Compact atO3. - The program that prints 42, the template's top-level
Console.WriteLine(42);, is 28,377 bytes, 9,791 (26%) fewer than with
0.12.2, from the same source: console output encodes UTF-8 without
constructing anEncodingand writes integers without reaching culture
state, aMainthat never readsargsno longer reads the command line, and
avoid Mainthat never setsEnvironment.ExitCodeno longer imports
wasi:cli/exit. Together they more than pay for its exit now closing the
standard streams (#224, below). - A
Main(string[] args)that never readsargs, as top-level statements that
ignore them compile, no longer reads and copies the command line. - A static field no code in the program writes reads as its default, so the
code its value decides compiles away: avoid Mainwhose program never sets
Environment.ExitCodeexits as anint Mainreturning 0 does. A program
that sets the exit code exits with it, as on .NET.
(NetWasmManagedUnwrittenStaticFieldFolding, on fromO2.)
Faster small copies and clears
- Span and array copies and clears of 17 to 64 bytes use Wasm's
memory.copy
andmemory.fill, which Wasmtime runs faster than the unrolled loads and
stores they replace: a 33-byteSpan<byte>.CopyTotakes 14% less time and
smallSpan<T>.Clearcalls 4 to 13% less, with larger copies, fills and
clears unchanged. Programs are smaller too.
Diagnostics
NW1009for a binding outside the selected WIT world now names the
interface the program reaches and the line that adds it, for example
imports 'wasi:cli/exit@0.3.2', which world 'wasi:clocks/imports@0.3.2' does not import; add `import wasi:cli/exit@0.3.2;` to the world.NW1013(nowFunctionLimit) also names a method that compiles to a function
with more than 50,000 locals or 1,000 parameters, which browsers, Node and
Wasmtime refuse, instead of failing after linking with a byte offset.
Fixes
- A conditional branch to the next instruction, which a Debug build emits for
anifaround a call to a partial method without a body or a
[Conditional]method, no longer crashes the compiler with NW1014
(#221). Everyleaveand
try entry that ECMA-335 allows now compiles, including aleavethat exits
no block and a catch'sleaveback into its own try. - A virtual or interface call over many boxed enums emits each shared target
once, soConvert.ChangeType(object, Type)grows linearly with the number of
enum types instead of with its square and no longer fails NW1013 at about 115
enums (#222). - A delegate converts to another delegate type
(#223), and every method a
delegate or function pointer can name binds and runs: an extension method's
group, a struct'sbase.Equals, the groups ofValueType.Equalsand
GetHashCode, a boxed value'sGetType, aconstrained.method pointer and
static virtuals, including a static abstract member called through a type
parameter whose argument is a class that is not sealed
(#228). A delegate closed over a null instance throws
ArgumentException, andEnum.HasFlag(null)throwsArgumentNullException,
as on .NET. - A
RuntimeTypeHandlekeeps its whole type ID wherever it is copied: in a
program with more than 255 types, a handle stored in an array or a field, or
copied in a Debug build, read type 256 as type 0, soType.GetTypeFromHandle
returned the wrong type andExpression.LambdathrewArgumentException
for delegate types past the 255th. - Console output in JavaScript hosts
(#224): a line written
before a long computation appears at once and stays when a time limit stops
the run, as on desktop .NET, because the host now takes the bytes when the
program writes them instead of on a timer the computation starved. A
program's exit closes each standard stream and waits for the host to write it
out, and a program that yields resumes on the next turn of the event loop, so
browsers print every line and 10,000 lines take under half a second on the
Node.js host instead of about 12 seconds. - A JavaScript host whose output sink refuses more output, as a page that caps
its console does, no longer leaves the program waiting on its standard output
until jco reports a deadlock: the program sees a closed pipe and runs on, as
on .NET. - A large program built with compiled units (the default at
O0andNone)
no longer fails withNW1014: Cannot allocate a buffer of size 2147483592
(#229): a build writes as
many cache segments as it needs, and stores each dispatch site's target list
and each type test's matching types once rather than at every site, so the
cache is smaller (by a fifth for the micro-benchmark runner atO0, and by
more where many sites call widely implemented methods). - A struct split into locals no longer stores its fields again before each call
that takes its address when nothing changed them (O1toO3). - Checking the neighbours of each fixed issue found two more. A function
pointer to a[JSImport]method (&Host.Twice) calls the import through
the forwarder a delegate uses, where it failed Wasm validation. And a
struct's defaultEqualsandGetHashCodekeep the boxed value they compare
alive when a field's ownEqualsorGetHashCodestarts a collection, where
they read freed memory: a wrong result on wasm32 and a trap on wasm64.
Upgrading
- Code that prints or compares type names: compare
Typeobjects, or build with
NetWasmTypeNamesand deploy<program>.wasm.type-symbolsbeside the program. - Code that calls
DynamicInvokeon aDelegatewith arguments, or on a
delegate that returns a value type: keep the delegate in a variable of its own
type, or call it directly. - Expression trees that invoke a delegate-typed parameter or constant: invoke a
lambda expression instead. - Hosts that mounted time zone data at
/netwasm-timezones/: mount the folder
that holds<program>.wasm.tz-infoat/netwasm-sidecars/instead.