ADR 0012 — Stack traces: per-call-site landing pads, names and lines from Roslyn’s own PDB
- Status: Accepted (2026-10-23), implemented.
Context
Exception.StackTrace and Exception.ToString() print the frames an exception passed through:
System.InvalidOperationException: Not sufficient funds for this withdrawal
at Classes.BankAccount.MakeWithdrawal(Decimal amount, DateTime date, String note) in /src/BankAccount.cs:line 61
at Program.<Main>$(String[] args) in /src/Program.cs:line 27
Real programs print them: every remaining wrong-output difference in the first real-world
compatibility runs (18-compatibility.md) was a missing stack trace. Until
now csharpc printed the type, the message and the inner exceptions only, and warned (CSLLVM0006).
What .NET prints, measured against .NET 11 RC2 (the oracle):
- The frame list runs from the throw point to the catching frame.
throw;keeps the frames (the rethrowing frame is not listed again),throw e;starts over even for an exception thrown before,ExceptionDispatchInfo.Throw()appends--- End of stack trace from previous location ---and continues. An await of a faulted task rethrows the exception the same way, butStackTrace.ToStringleaves the marker out after an async method’s frame (a state machine’sMoveNext, or a runtime-async method): an exception that went throughInner←Middle←Outerlists those frames in order, while one aTaskCompletionSourcecaptured in an ordinary method shows the marker before the awaiting frame. - Hidden frames (
StackTrace.ShowInStackTrace): methods marked[StackTraceHidden], methods of a type marked so (its own methods only: not its nested, closure or state-machine types), and[MethodImpl(AggressiveInlining)]methods are not listed — except as the trace’s last frame. A marker that follows a hidden frame isn’t printed either. - Frames .NET’s precompiled framework code inlined: .NET runs the shared framework from its ReadyToRun
code, so a framework method that code inlined into another has no frame of its own: the trace goes
from the inlinee’s callee to the method it was inlined into (the method compiled, however deep the
inlining:
File.OpenText→StreamReader.ValidateArgsAndOpenPath→OSFileStreamStrategy..ctor, without theFileStreamconstructors,FileStreamHelpers.ChooseStrategy*andUnixFileStreamStrategy..ctorbetween them). The compiler reads each framework assembly’s inlining table (CodeGen/ReadyToRunInlines.cs: the image’s cross-module inline section, 119, or InliningInfo2, 114, as the runtime reads them for the profiler), matches CoreLib’s frames from the slice and the corelib to System.Private.CoreLib’s methods by their text, and emits the (inlinee, inliner) pairs of the program’s frames; the runtime leaves out a frame when it and the frames above it up to some frame were all inlined into that frame’s method (trace_physicalinsrc/runtime/eh.c, walking from the outermost frame inward). Inlining across assemblies is not read, and a generic method the JIT instantiates over a value type at run time (not precompiled, so not inlined) is treated as precompiled. Likewise for implicit tail calls: optimized framework code turns a call in tail position into a jump (File.ReadAllText(String path)forwarding toReadAllText(path, Encoding.UTF8)leaves no frame), so a call site of framework IL that iscall/callvirtthenret, outside protected regions, in a method without localloc or exposed local addresses, to a callee whose arguments all fit in registers (SysV x64) gets a frame entry flaggedTRACE_TAILCALL; the runtime leaves that frame out unless the callee was inlined into it. - Each frame is
Namespace.Type.Method[T](Int32 x, String& s): nested types joined with., generic types asList`1, generic methods with their parameter names, parameter types asSystem.Type.Name(Int32,Decimal,Nullable`1,Int32[,],Int32&for ref/out/in,Int32*). Constructors are..ctor, accessorsget_X, operatorsop_Addition, explicit implementationsSystem.IDisposable.Dispose, top-level statementsProgram.<Main>$(String[] args), iteratorsProgram.Numbers(Int32 count)+MoveNext(), async methods their own name. - Compiler-generated methods carry Roslyn’s metadata names:
Program.<>c.<Main>b__7_0()for a lambda without captures,Program.<>c__DisplayClass7_0.<Main>b__8()in a closure class,Program.<Main>g__Local|7_9()for a local function,<<Main>$>g__L2|0_27(<>c__DisplayClass0_0&)for one capturing through a struct. The ordinals come from Roslyn’s closure conversion (lambdas of a scope first, then those of nested scopes, closure classes per scope); they are easy to get subtly wrong by imitation. - The location
in <path>:line Ncomes from the PDB: the document path as the build saw it (#linepaths resolved against the file, PathMap applied) and the start line of the sequence point that contains the IL offset — the statement start, but per declarator, perforclause, per switch-expression arm, the closing brace for ausingblock’s implicit Dispose, and so on. Library frames (the BCL ships without PDBs) have no location. - Quirks of CoreCLR’s funclets: an exception that leaves a
finallyblock (or a using’s Dispose) run on the normal path lists the method twice — once for the finally funclet, once for the method’s own frame, at its first sequence point in Debug code and at the try block’s first statement in optimized code. During unwinding (the finally runs because of another exception) it appears once. Catch blocks never duplicate. - Inlining.
dotnet runbuilds Debug, and the JIT’s first tier never inlines, so every user method has a frame. csharpc compiles every configuration at -O2, where LLVM inlines aggressively; an inlined frame that vanished from the trace would be a silent difference.
The trace must be exact for user code on all five CI targets — Linux x86-64/arm64, macOS arm64, Windows x64 (SEH unwinding through libunwind) and wasm32-wasi, which has no unwinder at all (ADR 0011) — and must cost nothing in programs that never look at a trace (the roadmap’s standing goal: faster and smaller than .NET in every area).
Decision
Recording: a landing pad per call site, read by the personality’s search phase
In a program that records stack traces, every call that may throw in a function of the program’s
own code becomes an invoke with a landing pad of its own (FunctionCodeGen.StackTraces.cs), whose
first catch clause is the site’s descriptor — a constant the compiler emits per site: one 64-bit word
(a tag in bits 63–48, the frame’s flags, its method index) and, for a frame with a location, the file
and line (16 bytes, else 8; code compiled from IL without a PDB has one descriptor per method):
site.12: %lp = landingpad { ptr, i32 } catch ptr @csharpc.trace.site.12 <the enclosing try's clauses>
br label %continue ; resume / csrt_begin_catch + dispatch / coroutine fault
csrt_personality tells a descriptor from a method table by its tag (not a canonical address, so no
method table starts with it). During the search phase it appends every descriptor
it meets to the exception (a new trace field) and goes on looking for a handler. The search phase
walks exactly the frames from the throw point to the catching frame — .NET’s frame list, by
construction — and frames without descriptors (the C runtime, the corelib) are skipped, as .NET
skips frames of code it doesn’t list. Record-only pads have no cleanup, so the cleanup phase passes
through those frames without stopping: recording costs a few instructions per frame in a walk the
unwinder does anyway.
- Inlining keeps frames. When LLVM inlines a function, the inlined landing pads get the caller’s
clauses appended, so an inlined frame’s descriptor is followed by its caller’s: recorded under
its own name and line, in the right order. The invokes themselves are all that restricts the
optimizer (tail-call and accumulator-recursion elimination don’t apply to invokes, which is also
what keeps recursive frames). LLVM deletes landing pads that only
resume— catch clauses and all — so record-only pads call an emptyasm sideeffect ""(no code; never executed anyway). A handler in an inlined method splits its frame’s clauses: the first search stops at the handler, having recorded the frames up to the handler’s method, and a rethrow from the handler searches the same physical frame again (same CFA). The trace keeps the outermost site recorded in that frame (TraceData.frame_last), and the second search records the sites past it — the inlined callers — instead of none (sample 1393; before,throw;from an inlinedcatchat -O2 lost every caller inlined into the same function). - No frame twice. csharpc’s own propagation re-raises (finally blocks, handlers whose type or
filter doesn’t match,
throw;), and a new search would walk frames already recorded. The trace keeps the highest frame (CFA) recorded, and the search records only frames above it. An await, an iterator’s MoveNext andExceptionDispatchInfo.Throw()continue elsewhere on the stack and reset it (csrt_trace_new_stack). - Rethrow semantics:
throw e(csrt_throw_object) clears the frames; csharpc’s internal propagation and awaits (csrt_rethrow) keep them;throw;gets no descriptor (its frame is in the trace already);ExceptionDispatchInfo.Capturecopies the frames andThrow()restores them plus the marker. - Finally funclets. A call that can make an exception leave a finally block gets a cleanup pad
that, if a per-finally flag says the block was entered on the normal path, inserts the parent
frame (method start in Debug, try’s first statement in Release) after its own entry
(
csrt_trace_finally); the flag is set in the normal-path trampolines (ThroughFinally) and cleared on the exceptional entry (Dispatch). - wasm32 has no unwinder and no personality:
ExceptionLoweringturns every invoke into a call plus a branch to its landing-pad block on a pending exception, so there the pad code itself records (csrt_trace_frame). Same IR, same frames. - Windows reaches the same personality through libunwind’s SEH adapter.
Formatting happens only when StackTrace or ToString() is called (csrt_exception_get_stack_trace
in eh.c): " at " + method + " in " + file + ":line " + N, joined with Environment.NewLine,
with StackTrace.ToString’s two filters, from flags the compiler puts in each descriptor
(StackTraceInfo.FrameFlags): a hidden frame is skipped unless it is the last one, and the
“previous location” marker is printed only after a listed frame that is not async. An await of a
faulted task (csrt_task_throw_if_faulted → csrt_trace_await) appends the marker, as .NET’s
ExceptionDispatchInfo rethrow does, so an exception a TaskCompletionSource captured in an ordinary
method reads ... FromCompletionSource() / --- End of stack trace ... --- / Main() while await chains
read as one trace. Each await starts from the frames the exception had when it faulted the task (their
count is kept in the task’s flags), so awaiting a task twice doesn’t list the first await’s frames again.
Names and lines: from the program as .NET builds it
CodeGen/StackTraces.cs emits the user’s sources once with Roslyn — without csharpc’s corelib or
its rewrites, with the configuration’s optimization setting, the SDK’s source resolver and PathMap —
and reads the portable PDB back with System.Reflection.Metadata:
- Lines. For each call site, the smallest sequence point containing the operation being lowered
(mapped back through csharpc’s method-group rewrite) gives the document and line. This is the
rule the CLR applies to IL offsets, so multi-line statements,
forheaders, switch arms and#linecome out right without re-deriving Roslyn’s sequence-point rules. The implicit Dispose ofusingis placed at its scope’s closing brace, where Roslyn puts that sequence point. - Names of compiler-generated methods are the metadata names of the PE’s methods: a lambda or
local function is the generated method whose first sequence point is the outermost one inside its
syntax (a state machine’s MoveNext maps to its kickoff method). Declaring types, generic
parameters and parameter types are decoded from metadata into
Type.Nameform. - Ordinary methods are formatted from their Roslyn symbols with the same rules.
Each site’s descriptor indexes the method and file tables the compiler emits; main registers them
(csrt_trace_init) before user code runs. The frame names are stored '\0'-terminated one after the
other and DEFLATE-compressed (System.IO.Compression at compile time); the runtime inflates them the
first time it formats a trace (a bounds-checked RFC 1951 decoder in eh.c): a program recording whole
IL libraries has thousands of frames, ~1.2 MB of text that compresses about 8:1.
Methods compiled from IL: names from metadata, lines where .NET finds a PDB
Every method csharpc lowers from IL — the program given as IL (csharpc app.dll), referenced and NuGet
libraries, framework assemblies taken as IL (ADR 0013) — is a frame too, except the precompiled corelib
(ADR 0015), which stands in for .NET’s own library code (next section). The name follows
StackTrace.ToString over the assembly’s metadata: the declaring type’s full name with + printed as
., generic definitions (Box`1.Nested`1.Go(T value, U u)), method generic parameters
(Generic[T](T value, Int32& x)), parameter types as Type.Name and unnamed parameters as the bare type
(<Local>g__Inner|7_0(<>c__DisplayClass7_0&)). A method of a [CompilerGenerated] type implementing
IAsyncStateMachine or IEnumerator prints as the method whose StateMachine attribute names that
type — iterators with +MoveNext() — decided from the attributes, not the PDB, as the runtime does:
csc leaves [CompilerGenerated] off an async lambda’s state machine (its <>c class has it), so .NET
prints that frame as Program.<>c.<<Main>b__0_0>d.MoveNext(), and so does csharpc (source programs
take the same rule from the PE they emit). [MethodImpl(MethodImplOptions.Async)] methods
(runtime-async) are async frames under their own name.
Lines come from the assembly’s portable PDB as .NET’s StackTraceSymbols would find it: embedded, or
beside the file .NET loads. dotnet build copies the PDB of a <Reference>d or project-referenced
assembly into the output (and csc writes the program’s beside it), but not a NuGet package’s unless
CopyDebugSymbolFilesFromPackages is set: an assembly under the global packages folder gets lines only
then (DebugSymbolSettings.PackagePdbs). The shared framework ships without PDBs. Frames that print the
same text but differ in flags (an async method’s kickoff stub and its MoveNext) are separate table
entries, since sites — keyed on the entry, the document and the line — share descriptors.
Pay for play
A program records traces only when it can observe one (StackTraceInfo.FindObservation): it reads
Exception.StackTrace, or turns an exception into text — ToString(), interpolation, string
concatenation, or passing it as object (Console.WriteLine(e)). Everything else compiles exactly
as before: no pads, no table, no PDB emit. --stack-traces turns recording on regardless (for
unhandled-exception reports on stderr).
What doesn’t match, and says so
- Frames inside .NET’s library (
System.ThrowHelper...,System.Linq.Enumerable...) depend on how .NET implements each member, and csharpc’s corelib implements them differently. For common throwing members the corelib reproduces .NET 11’s frames: the throw site names them,throw CoreIntrinsics.LibraryFrames(new KeyNotFoundException(...), "System.Collections.Generic.Dictionary2.get_Item(TKey key)“), which presets them as the start of the trace (csrt_trace_preset; nothing at all in programs that don't record traces), and awhenfilter adds them to an exception already in flight (AppendLibraryFrames, for File's text readers, whose frames are per public member and per OS). Covered today:Dictionary/SortedDictionaryindexers,Dictionary.Add,Listindexer,RemoveAtandInsert,List's enumerator (also throughIEnumerable),First,LastandSingle,Stack.Pop,Queue.Dequeue,string.Substring(both overloads, past the end),ArgumentNullException.ThrowIfNull,ArgumentException.ThrowIfNullOrEmpty(empty),ArgumentOutOfRangeException.ThrowIfNegative,Array.Copy(.NET on Windows also listsArray.Copyitself, which isn't reproduced),Task.Wait()andTask.Result (the AggregateException's frames,csrt_task_throw_aggregate_if_faulted_traced),Socket.ConnectAsyncfailures (the ValueTask overloads'AwaitableSocketAsyncEventArgs.ThrowException/GetResultframes; the Task overloads addValueTaskSourceAsTask's callback and a marker — a frame list line---is the marker,asyncmarks an async frame), and on UnixFile.OpenText/ReadAllText/ReadAllLines(withFileNotFoundException'sFile name: ’…’line). An exception that faults a task instead of being thrown keeps its preset frames for the await that rethrows it, without a marker. Elsewhere an exception thrown by or passing through BCL code shows the program's frames (and those of IL-compiled code) only. Known gaps, all behindCSLLVM0006: the parse family (int.Parse,double.Parse,Convert.ToInt32,Guid.Parse,Enum.Parse,DateTime.Parse: their frames depend on the public overload and the throw is deep in shared parsing code),string.Format,Task.WaitAll,Task.Run(.NET lists the thread pool's dispatch frames and two markers),TcpClient.ConnectAsyncandSocket.ConnectAsync(string, int)(csharpc connects on a pool thread),Socket.Connect(DoConnect), directory enumeration and file opening other than the members above, and every frame an exception passes through on its way out of a library member that called back into the program (List.ForEach , LINQ iterators,Lazy,List.Sort ). Reproducing a frame where csharpc's call structure differs would need awhenfilter on the hot path (code in every program), so these stay explicit differences. WarningCSLLVM0006is reported wherever a program turns an exception into text or readsStackTrace`, so the difference is never silent. - Static field initializers and static constructors run from csharpc’s own class-init function:
their
..cctorframe is missing (.NET also shows a BCL frame there). - Frames of record members the compiler synthesizes are not recorded.
- If the program cannot be emitted by Roslyn as-is, lines fall back to statement starts and lambda
frames are named
<lambda>(), with aCSLLVM0006warning. - Optimized .NET code (
-c Release) can lose frames when the JIT’s later tiers inline hot methods; csharpc lists every frame, which is what Tier-0 code (and every short program) shows.
Consequences
Measured on x86-64 Linux (shared 4-vCPU VPS), -O2, benchmark programs compiled with and without
--stack-traces (none of them observes a trace, so by default they compile exactly as before):
| without | with --stack-traces |
|
|---|---|---|
binary size, programs that already throw (throw microbenchmark, listsort, strbuild) |
41.2 / 85.6 / 53.3 KiB | 45.4 / 89.7 / 57.6 KiB (+4 KiB) |
binary size, programs without exceptions (binarytrees, nbody, fib) |
28.1 / 36.5 / 11.1 KiB | 36.6 / 45.1 / 36.1 KiB (the unwinder and formatter come in) |
| CPU time, 11 benchmarks | — | unchanged (±3 %, noise) except fib: 42 → 83 ms |
| throw + catch through 10 frames | 1.3 µs (1 frame: LLVM turned the recursion into a loop) | 4.7–5.3 µs (.NET 11 JIT: 4.9 µs) |
| throw + catch through 1 frame | 1.4 µs | 2.4 µs (.NET 11 JIT: 2.4 µs) |
| compile time | — | +0.5–0.9 s for the Roslyn emit of the user’s sources |
fibis the cost of keeping frames: its recursive calls stay calls (an invoke is never turned into a loop by accumulator-recursion elimination), as in .NET, whose JIT runs the same program in 117 ms. Only programs that observe stack traces pay it.- Programs that observe stack traces print the same text as .NET for their own frames. The five
compatibility programs whose only difference was the missing trace pass; the two that remain print
BCL-internal frames (
ArgumentOutOfRangeException.ThrowNegative[T],Array.CopyImpl,SafeFileHandle.Open, …). - Recording the frames of IL-compiled code (2026-11-01): TechEmpower’s Platform entry (
csharpc Platform.dll, which prints an exception when the database is unreachable, so it records traces) against a closed PostgreSQL port now prints the JIT’s trace exactly (the socket frames, 10 Npgsql frames, the program’s two). It pays for the frames of all its Npgsql, ASP.NET Core and framework IL: first -O2 executable 17,405,512 → 19,355,584 bytes (+11.2 % overmain774b977). Compressing the frame names (−0.67 MB), 8-byte descriptors for frames without a location (−0.07 MB) and the empty-asm pad anchor instead of a volatile store (−0.16 MB of.text) bring it to 18,330,832 (+5.3 %). What is left is the per-call-site recording itself:.gcc_except_table+420 KB (an LSDA for every traced function and every inlined copy of one, whose pads carry the inlined frames),.text+197 KB (the pads),.rodata+178 KB (12.2 k frame names compressed to 142 KB, 8.5 k descriptors),.data+75 KB (the indirect type-info slot x86-64 PIC LSDAs use per descriptor),.eh_frame+59 KB. Build time unchanged (224 vs 207 s). Programs that don’t observe traces are unchanged (tests/size.sh:.textequal or smaller,.eh_frame+24–48 B for two out-of-line corelib throw helpers). dotnet run app.cs(the oracle for the differential tests) sometimes runs a cached build whose PDB is stale; .NET then prints frames without lines. Recording a stack-trace sample therefore needs a fresh build (delete the app’s~/.local/share/dotnet/runfile/<name>-*directory first).
Alternatives considered
- Return-address backtraces + symbolization (what C++ and NativeAOT do): capture
_Unwind_Backtraceat the throw, map return addresses to methods and lines at format time. Zero code-size cost in user functions, but: line tables need the final addresses, so DWARF (.debug_line/.debug_infowith inlined-subroutine records) must be parsed at run time, or a table rebuilt after linking and patched into the binary — on ELF, Mach-O (whose DWARF stays in the object files unlessdsymutilruns) and PE alike; inlined frames need DWARF’s inline records; wasm32 has no unwinder to capture anything. Several hundred lines of per-format code for each platform, versus nothing platform-specific in the pad approach. - Disabling inlining in programs that observe traces: simple, but slows exactly the programs csharpc competes on and still needs the line tables above.
- A shadow stack (push method/line on entry and before each call): works everywhere, but costs every call on the normal path.
- Re-deriving Roslyn’s lambda ordinals and sequence points from syntax: no extra emit, but the closure-conversion ordering (scope tree order, which lowered temporaries open new scopes) is exactly the kind of imitation that is silently wrong in corner cases. Reading Roslyn’s own output is exact by construction.