csharpc

04 — Runtime

Every compiled program links against csrt, the csharpc native runtime: the C11 sources in src/runtime (csrt.h is the ABI). The driver compiles it on demand and caches the object under ~/.cache/csharpc/ (02-architecture.md).

csrt is the “native layer”. Library logic lives in the C# corelib instead (ADR 0007, ADR 0008); see the C / C# boundary.

ABI contract

The compiler and csrt must agree on these layouts (see csrt.h, TypeMapper.cs, ModuleCodeGen.cs):

struct csrt_MethodTable {                   // 40 bytes on 64-bit targets (pointer-size dependent on wasm32)
    const csrt_MethodTable* base;           // null for System.Object and interfaces
    const char* name;                       // fully qualified CLR name, UTF-8: "Ns.Outer+Inner"
    uint32_t instance_size;                 // bytes, including the header
    uint32_t flags;                         // CSRT_MT_*: abstract, interface, no references (never scanned),
                                            // value type / enum / primitive box, delegate, array kinds, ...
    const csrt_InterfaceMapEntry* interfaces;  // every implemented interface (flattened): { interface MT, slots }
    uint32_t interface_count;
    uint32_t reserved;                      // rank of a rectangular array, element size of a 1-D array
    // void* vtable[] follows; slots 0..2 = ToString, Equals, GetHashCode
};

object : { const csrt_MethodTable* mt; fields... }
string : { const csrt_MethodTable* mt; int32_t length; uint16_t chars[length]; }   // UTF-16
T[]    : { const csrt_MethodTable* mt; int64_t length; T data[length]; }           // data @ 16
T[,]   : { mt; int64_t total; int64_t lengths[rank]; T data[total]; }               // row-major

The built-in types csrt_Object_MT, csrt_String_MT and csrt_Array_MT are csrt_BuiltinMethodTables (header plus three vtable slots), so any object, including a string held in an object variable, can be dispatched through slot 0 by csrt_object_to_string. Array method tables end with the element type’s method table, which the array covariance checks use.

Compiler-generated method tables for the program’s classes are emitted by csharpc as internal constants with the same header. Their base points at the base class’s table or at csrt_Object_MT.

What csrt contains

File Role
csrt.c, type.c, delegates.c, records.c, strings.c, span.c startup (csrt_init/csrt_shutdown, arguments), allocation entry points, casts and interface lookup, System.Type objects over the compile-time metadata tables, delegate combination, helpers for records and anonymous types, span primitives
gc.c the collector: allocator, mark-sweep, weak references and ephemerons, finalizers, Objective-C tracking, the opt-in nursery and concurrent marker (GC)
eh.c exceptions: throw/rethrow, the personality routine, filters, stack-trace recording and formatting, the exception trap for pool workers
threads.c, async.c, signals.c, sockets.c threads, Monitor/Lock, wait handles and the Parallel worker pool (14-threading.md); tasks, the thread-pool scheduler, timers and iterator objects (10-async.md); POSIX signals; epoll for the corelib’s socket engine
console.c, pinvoke.c, bclmisc.c console input and stderr, dlopen-based library resolution and last-error capture for P/Invoke, System.Array/Convert helpers
decimal.c, datetime.c, int128.c the method tables of the boxed value types and the clocks; the arithmetic itself is C#
win32.c, wasi.c, windows-shims/ the pthread subset and missing libc functions on Windows and WASI (Platforms)
globalization/ .NET’s ICU shim (19-globalization.md)

Number formatting and parsing (C#)

Number formatting and parsing aren’t in csrt anymore. They’re corelib C# (src/Csharpc/corelib/Number*.cs, ADR 0008) and follow .NET’s own algorithms; the culture-dependent parts (symbols, group sizes, patterns) come from the NumberFormatInfo of the provider or the current culture (19 — Globalization). With the invariant culture:

  • double.ToString() / "R" / "G": the shortest digits that round-trip, from the Steele & White / Burger & Dybvig free-format algorithm on exact big integers (BigNum.cs). Fixed notation is used while the decimal exponent is at most 17 for double (9 for float) and at least −5; otherwise scientific notation (1E+18, 1E-05). Special values print as NaN, Infinity, -Infinity and -0.
  • F/E/N/P/C/G<n> on doubles round the exact binary value, ties to even (0.125.ToString("F2") == "0.12"). Custom formats first round doubles to 15 significant digits (floats: 7), then round half up, as .NET does. Integers and decimals round half up and never print -0.
  • Parsing is correctly rounded: Clinger’s fast path when the digits and the power of ten are exact doubles, otherwise an exact big-integer quotient with a sticky bit.

Because the test oracle is real .NET (05-testing.md), any divergence shows up as a test failure (tests/samples/162_number_format, 163_number_parse).

Exceptions and stack traces

Exceptions are zero-cost Itanium-style unwinding with csrt’s own personality (ADR 0005); on WebAssembly, explicit propagation (ADR 0011). An unhandled exception runs the finally blocks, flushes stdout, prints Unhandled exception. <ToString()> to stderr and ends the process like .NET (SIGABRT, status 134, on Unix; 0xE0434352 on Windows). Runtime-raised exceptions use .NET’s exact message texts (Object reference not set to an instance of an object., …).

Dispatch has .NET’s two passes: every when filter up to the handler runs before any finally block on the way there. Each filter is a function of its own that reaches the method’s variables through its try’s frame record, linked into a per-thread chain while the try is active; the personality’s search phase (on wasm32, the throw itself, walking the chain) runs it, and the verdict travels with the exception (eh.c, “Exception filters”; FunctionCodeGen.Filters.cs). Code without filters is unchanged on native targets; a try with a filter costs two runtime stores on entry and one on exit.

Stack traces (ADR 0012): in programs that read Exception.StackTrace or turn an exception into text (or with --stack-traces), every call site of the program’s own code that may throw has a landing pad whose first catch clause is a { tag | flags | method[, file, line] } descriptor; csrt_personality appends the descriptors it meets during the search phase to the exception’s trace field, so the frames are exactly those from the throw point to the catching frame, inlined ones included (on wasm32 the pad code records them). eh.c formats them on demand like .NET’s StackTrace.ToString() ( at Ns.Type.Method(Int32 x) in /path/file.cs:line 12), handles throw; / throw e; / ExceptionDispatchInfo semantics, and ToString() appends the trace. Names of lambdas and local functions and the lines come from a PDB of the user’s sources emitted by Roslyn at compile time. Methods compiled from IL (the program as IL, libraries, framework IL) are frames named from their metadata, with lines where .NET would find their PDB. Frames inside the BCL code the corelib implements are reproduced for common members only (CoreIntrinsics.LibraryFrames; CSLLVM0006 warns where a program prints a trace). The formatter applies StackTrace.ToString’s filters: [StackTraceHidden] and AggressiveInlining frames are left out, and the “previous location” marker an await or ExceptionDispatchInfo adds is printed only after a frame that is not an async method’s.

The C / C# boundary

The target architecture is the one Rust and NativeAOT use: library code written in the language itself, on top of a thin native layer.

┌──────────────────────────────────────────────────────────────┐
│ user code (C#)                                               │
├──────────────────────────────────────────────────────────────┤
│ csharpc corelib (C#, src/Csharpc/corelib, compiled with the  │  collections, LINQ, strings, char,
│ program; ADR 0008)                                           │  StringBuilder, number formatting and
│                                                              │  parsing, decimal, BigInteger,
│                                                              │  DateTime/TimeSpan, Math.Round, ...
├──────────────────────────────────────────────────────────────┤
│ csrt (C, src/runtime)                                        │  GC + allocator, unwinding/EH, threads,
│                                                              │  async scheduler core, console + OS calls,
│                                                              │  startup, type-system primitives
└──────────────────────────────────────────────────────────────┘

Stays in C: things that are native by nature or live below the object model:

  • the GC and allocator (gc.c);
  • exception unwinding and messages (eh.c);
  • threads and monitors (threads.c) and the async scheduler core (async.c);
  • console I/O and syscalls (console.c, csrt.c);
  • startup (csrt_init);
  • casts, interface dispatch and boxing method tables (csrt.c, type.c, delegates.c).

Also in C: .NET’s ICU shim (globalization/, System.Globalization.Native, see 19 — Globalization). Enum.Parse moved to the C# corelib (corelib/EnumRuntime.cs, its integers parsed by CoreLib’s own parser from IL, #426). The decimal.c and datetime.c files that remain only hold boxed method tables and the clocks.

Lives in C#: library logic that is ordinary code:

  • number formatting and parsing (Number.Formatting.cs, Number.Parsing.cs, Number.cs, BigNum.cs);
  • the string operations codegen calls itself (StringRuntime.cs) and the ordinal case tables generated from .NET (OrdinalCasing.cs, UnicodeData.g.cs, tools/unicode); string’s and char’s library members come from CoreLib’s IL (upstream-types/System.String.txt);
  • StringBuilder (StringBuilder.cs, .NET’s chunk list and growth policy, so GetChunks and Capacity match);
  • decimal (DecimalOps.cs) and DateTime/TimeSpan (DateTimeOps.cs); BigInteger is the framework’s IL (System.Runtime.Numerics);
  • collections and LINQ.

How the two sides call each other:

  • Compiler → C#. Library members are implemented, in order of preference, by:

    1. a corelib shadow ([Shadows], [ShadowMembers], [ShadowInstance]; 12-corelib.md);
    2. an Intrinsics.cs entry (an LLVM intrinsic or a runtime call);
    3. a CSLLVM0002 “not supported” error.

    A runtime call whose function has moved to C# is redirected by CodeGen/CoreLibRuntime.cs, so call sites keep naming the old csrt_* symbol.

  • C → C#. A corelib method marked [RuntimeExport("csrt_x", "trigger")] is emitted under the C name csrt_x when the program references trigger. For example, a boxed double’s ToString slot in csrt_Boxed_Double_MT calls csrt_string_from_f64. csrt declares weak fallbacks for these symbols so that programs which never reach that code still link.

  • C# → C. Corelib code reaches the runtime through ordinary BCL calls that lower to csrt_* (Console.Write, new string, …) and through a few CoreIntrinsics (FastAllocateString, StringChars, bit casts) that need no unsafe code.

Platforms

csrt is C11 + POSIX threads. What differs per OS is behind #ifdef __APPLE__, #ifdef _WIN32 and #ifdef __wasi__ (Windows: MinGW-w64 with the UCRT; csrt_pthread.h + win32.c implement the pthread subset csrt uses over SRW locks, condition variables and _beginthreadex, instead of linking winpthreads, so the threading code is shared. WASI: wasi-libc, one thread; wasi.c implements the pthread subset csrt uses):

Concern Linux (glibc) macOS (arm64) Windows (x64, MinGW-w64) WASI (wasm32, wasi-libc)
GC static roots writable PT_LOAD segments via dl_iterate_phdr, minus PT_GNU_RELRO (method tables, vtables, the GOT: read-only once relocated) writable LC_SEGMENT_64s of image 0 (_dyld_get_image_header) writable sections of the executable’s PE image (GetModuleHandle(NULL)) the data segment, __global_base to __data_end
GC thread-local roots the executable’s PT_TLS block (dlpi_tls_data) the thread’s TLV block: a __thread_vars descriptor’s thunk gives one variable’s address, minus its offset = block start; size = __thread_data + __thread_bss TEB.ThreadLocalStoragePointer[_tls_index]; size from the image’s TLS directory none (_Thread_local becomes ordinary globals without the threads proposal)
GC heap chunks mmap + trim to alignment the same VirtualAlloc: reserve twice the size, release, map at the aligned address aligned_alloc (linear memory only grows)
thread stack bounds __libc_stack_end, pthread_getattr_np pthread_get_stackaddr_np GetCurrentThreadStackLimits the linear-memory stack, up to __stack_high; values in wasm locals are spilled there by the compiler (RootSpilling)
stop-the-world SIGPWR/SIGXCPU, POSIX semaphore acks SIGUSR1/SIGXCPU, Mach semaphore acks (no unnamed POSIX semaphores) SuspendThread + GetThreadContext (waits until the thread is stopped; the whole CONTEXT, vector registers included, is scanned as roots), ResumeThread not needed (one thread)
timed waits CLOCK_MONOTONIC condvar, pthread_mutex_timedlock pthread_cond_timedwait_relative_np, trylock polling pthread_cond_timedwait_relative_np (SleepConditionVariableSRW takes a relative timeout; absolute ones are wall-clock), trylock polling sleep until the deadline; a wait nothing can end is reported as a deadlock
unwinding libgcc_s / .eh_frame libSystem’s libunwind, compact unwind + __eh_frame; same personality (csrt_personality) LLVM-MinGW’s libunwind on SEH tables (.pdata/.xdata): LLVM registers csrt_personality as each function’s SEH handler, and on Windows it forwards to _GCC_specific_handler with the Itanium personality, as libstdc++‘s __gxx_personality_seh0 does none: explicit propagation through csrt_pending_exception (ExceptionLowering)
unhandled exception abort(): SIGABRT, exit status 134 the same TerminateProcess with .NET’s exit code 0xE0434352, or 0xC0000005 for a NullReferenceException from a null dereference (.NET re-raises the access violation) abort() traps; wasmtime exits with status 134
standard streams as is as is binary mode: “\r\n” is written where .NET writes Environment.NewLine, a program’s own “\n” stays bare as is
command line /proc/self/cmdline _NSGetArgv the UCRT’s wide argv (_configure_wide_argv: MSVC wmain parsing of GetCommandLineW, like .NET’s host) argv from wasi-libc
clocks clock_gettime the same GetSystemTimePreciseAsFileTime; Stopwatch on QueryPerformanceCounter (its Frequency is QueryPerformanceFrequency, as in .NET) clock_gettime (WASI clocks)
P/Invoke probing foo.so, libfoo.so, foo, libfoo the same with .dylib foo.dll, foo (LoadLibraryExW); SetLastError captures GetLastError() libc/libm only (wasi-libc, linked statically); others throw DllNotFoundException
ICU (globalization) libicuuc.so.NN / libicui18n.so.NN, newest version first (dlopen) /usr/lib/libicucore.dylib icu.dll (Windows 10 1903+); no NLS fallback none: invariant globalization mode
user culture ICU default locale: LC_ALL, LC_MESSAGES, LANG; C/POSIX = invariant system settings (CFLocale) GetLocaleInfoEx / GetUserPreferredUILanguages the invariant culture

An uncaught exception on Windows: _Unwind_RaiseException raises an SEH exception that no frame handles, and MinGW’s top-level filter (_gnu_exception_handler) resumes it, so it returns _URC_END_OF_STACK as on Unix; csrt then runs the finally blocks (forced unwind) and reports it. The thread-pool trap (csrt_trap_call) needs a plain register-restoring jump there, because MinGW’s longjmp unwinds the stack through SEH (RtlUnwindEx) and it jumps out of a forced unwind. It is not __builtin_setjmp/__builtin_longjmp: on Windows x64 LLVM’s frame address is the SEH establisher frame (RBP minus the .seh_setframe offset), which __builtin_longjmp loads into RBP, so the code after the jump addressed its locals 128 bytes below the real frame (an access violation, or a garbage exception, whenever an iteration threw on a pool worker). eh.c carries its own csrt_trap_save/csrt_trap_restore pair in module assembly instead (callee-saved registers, RDI/RSI and XMM6-15 included). win32.c supplies C library functions the UCRT lacks (roundeven, which LLVM calls for Math.Round without SSE4.1). windows-shims/msvc_compat.c is not part of the runtime proper: it holds the MSVC runtime symbols that .NET’s Windows shim archives (zlib-ng, brotli, zstd from the NativeAOT pack, built with /GS and /guard:cf) reference, is compiled on demand, and is linked only into a program that links one of those shims (16-interop-io.md).

errno values, open flags and struct layouts that C# code needs are selected in the corelib at compile time from the target triple, not in C (16-interop-io.md).

WebAssembly (wasm32-wasip1)

The design is in ADR 0011. What a program sees:

  • Exceptions behave as on the native targets, filters and finally included. The compiler lowers them to explicit propagation, since WebAssembly has no unwinder. In programs with when filters every try with a catch links a record the first pass walks (dropped again in programs without).
  • Garbage collection is the same collector. References that the optimized code keeps in wasm locals are spilled into stack slots in linear memory, so the scan finds them. CSRT_GC_STRESS=N collects on every N-th allocation (any platform) to test this.
  • Threads: there is one. Thread.Start throws PlatformNotSupportedException (“Operation is not supported on this platform.”), as in .NET’s single-threaded WebAssembly builds. Environment.ProcessorCount is 1 and parallel loops run inline. Task.Run work, continuations and timers run on the main thread whenever it blocks (Wait, Result, async Main, Thread.Sleep, Thread.Yield). A wait that can never end (Monitor.Wait(), Thread.Sleep(Infinite), a task nothing will complete) prints a deadlock message and exits with status 134 instead of hanging. A busy-wait on a flag that only another thread would set still spins forever.
  • System: files in the directories the WASI runtime preopens (relative paths resolve against $PWD), environment variables, clocks, Random (WASI random_get), standard streams. Environment.ProcessId is 42 and MachineName is “localhost”. P/Invoke reaches only wasi-libc. Exit codes above 125 are rejected by wasmtime.
  • Running: wasmtime run --dir=. program.wasm for a program that only touches files under the current directory, or tests/wasm-run.sh program.wasm (the whole file system, the environment, and an 8 MiB wasm stack like .NET’s main thread).

Measurements (local x86-64 machine, wasmtime 36 including its JIT compilation; best of 3, wall ms):

benchmark native -O2 wasm -O2 native size (KiB, stripped, dynamic glibc) wasm size (KiB, static wasi-libc)
fib 92 132 11 35
binarytrees 336 437 28 49
fannkuchredux 394 487 28 51
nbody 904 1102 36 63

The module embeds what native executables load from libc at run time (wasi-libc: malloc, stdio, math). Hello world is about 65 KiB at -O2.

GC

The collector in src/runtime/gc.c is a conservative, non-moving, stop-the-world mark-sweep. Small objects live in 256 KiB size-classed chunks; large objects are tracked in a sorted table. Roots are the writable data segments, each thread’s stack (registers spilled by setjmp or, on Windows, GetThreadContext) and its TLS. The collecting thread’s stack is scanned from the frame where the collection was entered, not from the collector’s own frames, whose unwritten slots hold stale values of returned calls; the TLS block is scanned without the allocation caches, whose word pointers name whatever object starts the claimed bitmap word. Strings and arrays of primitives are not scanned (CSRT_MT_NO_REFERENCES). Allocation is thread-local (one claimed bitmap word per size class). After a collection, empty chunks beyond what the next allocation budget can fill give their pages back to the OS (madvise(MADV_DONTNEED), Linux), so a process shrinks after a burst; a released chunk is zero when it is handed out again. The full design, including the opt-in non-moving nursery and why the collector is conservative rather than using LLVM statepoints, is ADR 0004; the concurrent marker is ADR 0020. On wasm32 the shadow stack is ADR 0011.

Sweeping keeps chunks mapped, so without help the heap stays at its peak. In a program that starts threads (a server), a helper thread checks the allocation rate every 500 ms; once it falls under 1 MiB per period after a collection, it gives back to the OS every page of slot memory that holds no allocated slot (madvise(MADV_DONTNEED) on Linux, MADV_FREE_REUSABLE on macOS, decommit and recommit on Windows), and glibc’s free memory with malloc_trim. Under load the rate keeps it from trimming, so no allocation pays a page fault for it; after a burst (TechEmpower’s 10,000-row cache fill at start-up) the idle process shrinks to about its live heap.

Finalizers

A class of the program that declares ~T() (or, from IL, overrides Finalize) allocates its instances with csrt_alloc_finalizable, which registers the object with the collector; the compiler passes a thunk that runs the finalizers of the class chain, most derived first. After marking, the registered objects nobody reached move, in registration order, to a queue, and the queue is marked (the objects and everything they reach survive this collection). A finalizer thread, started at the first registration, runs them; GC.WaitForPendingFinalizers waits for it (on WebAssembly, with no threads, it runs what is pending itself). GC.SuppressFinalize and GC.ReRegisterForFinalize edit the registry; an exception escaping a finalizer is unhandled and ends the process like any other. Nothing runs at exit, as in .NET. Details and limits: ADR 0021.

Objective-C reference tracking

ObjectiveCMarshal (corelib ObjectiveCMarshal.cs, macOS only) keeps a table of tracked objects in gc.c, outside the managed heap like the finalizer registry. A class with [ObjectiveCTrackedType] (inherited) and a finalizer carries CSRT_MT_TRACKED_REFERENCE; GetOrCreateReferenceTrackingMemory gives such an object two words of native-owned tagged memory and CreateReferenceTrackingHandle adds a handle to it (a weak slot that tracks resurrection). After marking, each collection calls the registered begin/end callback around one pass: for every object with a handle that nothing else reached it calls isReferenced(taggedMemory), and marks the object (and what it reaches) when the answer is non-zero. An object that enters the finalizer queue is announced to trackedObjectEnteredFinalization(taggedMemory) first; the tagged memory is freed once the object is gone for good. The callbacks run with the world stopped on the collecting thread and must not call managed code (real CoreCLR aborts when they do). SetMessageSendCallback fills a per-kind override table that the P/Invoke stubs of libobjc’s objc_msgSend, _fpret, _stret, Super and Super_stret consult before every call, and SetMessageSendPendingException leaves an exception on the thread that the stub throws after the call. Programs that never call Initialize have none of this in the binary.

Weak references and ephemerons

WeakReference, WeakReference<T> and ConditionalWeakTable<TKey, TValue> (corelib WeakReferences.cs) sit on a table of weak slots in gc.c, kept outside the managed heap so the conservative scan never sees the targets. After marking, a slot whose target wasn’t reached is cleared. A weak reference that tracks resurrection (WeakReference(target, true), GCHandleType.WeakTrackResurrection) is cleared only once finalization has run and the object is gone for good, so it stays alive across a finalizer that resurrects its target; weak GCHandles are slots of the same table. A ConditionalWeakTable entry is an ephemeron: its value is marked only while its key is reachable some other way, to a fixed point, so a value referenced only by the table lives exactly as long as its key. The corelib’s own types declare no finalizers, so each slot names its owner (the WeakReference, the table) and the collector frees the slot when the owner dies — when .NET’s finalizer would release the handle. Whether an unreferenced target is collected at a given GC.Collect() is up to the (conservative) collector, as it is up to .NET’s.