Skip to content

Decision Code Generation Views

matthew edited this page Sep 6, 2026 · 1 revision

Decision: code generation views

The spike record for epic #574 (phase P0, #575), preserved as written (2026-09). The prototypes it describes were deliberately throwaway and were never merged; what shipped is four decoder plugins, described on Plugins. Three of its conclusions were adopted: that a Kotlin/ASM sidecar and a bundled JVM are unnecessary, the shape of the CodeListing contract, and the re-scoping of the ahead-of-time phase. Its ahead-of-time findings remain live work in #586.

Spike #575 — code generation views: findings

Throwaway prototypes for epic #574. Not intended to merge. Everything below was run on this machine (macOS 26.6, x64 Mac Pro, .NET 10.0.100 SDK, Zulu OpenJDK 21.0.8, rustc 1.95.0).

Axis Prototype Verdict
Static / JVM jvm/ — pure TS .class decoder ✅ Proven at scale
Static / WASM wasm/ — pure TS module decoder ✅ Proven
Static / .NET dotnet/ilsidecar — ICSharpCode.Decompiler ✅ Proven, all three claims
Runtime (JIT) jit/capture.ts, jit/hsdis-probe.ts ✅ .NET proven · ⚠️ JVM unavailable
AOT aot/check-aot.ts ⚠️ Epic partly wrong — see below

1. JVM bytecode — pure TypeScript, validated at scale

jvm/class-decoder.ts + jvm/opcodes.ts (~700 lines total, no dependencies) decodes class files into CodeListing. Validated against javap -c -p on (method, offset, mnemonic) sequences — chosen because any error in an instruction length desynchronises every offset after it, so matching a whole method's offsets is real proof.

files=1252 methods=10678 failedMethods=0 erroredFiles=0
ALL METHODS MATCHED

That is 1,252 real java.base classes from the JDK. It covers tableswitch/lookupswitch (the 4-byte-padded variable-length pair), wide prefixes, invokedynamic/lambdas, exception tables, two-slot long/double constant-pool entries, and backward branches.

Conclusion: #196's Kotlin/ASM sidecar plus bundled JVM is definitively unnecessary. The packaging weight that caused the original deferral is gone.

One naming detail worth carrying forward: javap renders a wide-prefixed opcode as iinc_w, not as wide + operands. Three methods in the first corpus run diverged on exactly that and nothing else — offsets matched throughout. Aligning the naming took four lines.

LineNumberTable is read and gives the JVM source mapping (question 3).

2. WebAssembly — pure TypeScript

wasm/wasm-decoder.ts (~470 lines, no dependencies) decodes the section table, export names, function bodies, locals, and the MVP opcode space. Run against a real Rust wasm32-unknown-unknown release build:

func[0] "arithmetic"
  ; file 0x9d..0xa7 (10 bytes)
        0x009E: local.get 1
        0x00A0: local.get 0
        0x00A2: i32.mul
        0x00A3: i32.const 7
        0x00A5: i32.add

Cross-checked semantically: WebAssembly.validate passes, and instantiating the module gives arithmetic(3,4) = 19, dense(2) = 102, floats(2) = 6 — matching what the listing reads.

Confirmed: sniffFormat reports {"kind":"unknown"} for .wasm today, so these files currently land in the binary view with nothing to show.

Surprise: WASM function bodies address by file offset, not method-relative offset. It groups with native code, not with JVM/IL. Three addressing modes still suffice.

3. .NET IL — ICSharpCode.Decompiler sidecar

dotnet/ilsidecar speaks newline-delimited JSON over stdio (the long-running shape #195 specified). All three claims the epic made hold:

IL per method. Decoded via a table reflected out of System.Reflection.Emit.OpCodes, so neither mnemonics nor operand sizes are hand-rolled.

C# decompilation, free. Same library, one extra op:

public static int Loop(int n) {
    int num = 0;
    for (int i = 0; i < n; i++) { num += ((i % 3 == 0) ? i : (-i)); }
    return num;
}

PDB source mapping works. 16 sequence points on a 44-instruction method, and they track the C# structure exactly — L18 the if, L20/L24 the two branches, L16 the loop increment. Every branch target lands on a real instruction offset.

fileRange is byte-exact. For Arithmetic the sidecar reported start=593, length=6; the bytes at offset 593 of the DLL are 02 03 5A 1D 58 2A = ldarg.0 ldarg.1 mul ldc.i4.7 add ret. RVA→file translation goes through the containing section, then past the method header (tiny = 1 byte, fat = 12).

4. Runtime axis — JIT assembly

.NET works on a completely stock SDK. No checked runtime, no custom build:

; Assembly listing for method P:Add(int,int):int (FullOpts)
G_M000_IG02:                ;; offset=0x0000
       mov      eax, edi
       imul     eax, esi
       add      eax, 7

Tier is user-visible and must be a UI control. The same method, same binary:

Setting Tier Code size
default Tier0 32 bytes
DOTNET_TieredCompilation=0 FullOpts 9 bytes

Ship this without a tier toggle and users will screenshot cold Tier0 code and file performance bugs. DOTNET_JitDisasmSummary=1 additionally gives a clean per-method inventory ([Tier0, IL size=6, code size=32]) that would make a good "what actually got JITted" list.

JVM JIT assembly is unavailable. jit/hsdis-probe.ts checks both ways — library on disk, and asking the JVM outright. On the local Zulu 21: available: false — no hsdis shared library found. Detect and degrade; the probe's suggested wording is "JIT assembly unavailable — this JDK ships no hsdis plugin. Bytecode is still shown."

5. AOT axis — the epic is half wrong here

The epic claimed AOT output is "near zero" cost because the existing Capstone path already handles it. Ran the repo's own sniffFormat / disassemblyArchitecture / codeOffset over real published output:

Build Sniffed Capstone codeOffset
plain IL pe x86 managed ❌ null 0x8e6
ReadyToRun pe **unknown** managed ❌ null 0x200
NativeAOT macho x64 ✅ x64 ❌ null

NativeAOT works — and Capstone really does decode it (verified through the actual disassembler package: 22 instructions decoded, resolving into real code like mov r15d, ebx; shr r15d, 3).

ReadyToRun does not work, for two independent reasons:

  1. R2R images still carry a CLR header, so sniffPe sets managed: true and disassemblyArchitecture() returns null — native disassembly is switched off.
  2. Its PE machine field reads 0xC020, which the sniffer maps to 'unknown'. That is not corruption: .NET XORs the machine field with an OS-specific override for non-Windows R2R targets. 0xC020 ^ 0x4644 (Apple) = 0x8664 = AMD64, exactly. Linux is 0x7B79, FreeBSD 0xADC4, NetBSD 0x1993, SunOS 0x1992.

So P7 is not free. It needs: un-XOR the machine override, and a rule that a managed PE which is also R2R should still offer native disassembly. Both small, but they are real work that the epic assumed away.

Also found: codeOffset() returns null for Mach-O (it only handles ELF and PE), so NativeAOT binaries disassemble but the "jump to code" button does nothing. A gap in existing behaviour, not just for this epic.

Reproduced the known Capstone GC hazard. A throwaway script that did not hold a strong reference to the instance crashed with cs_close → RuntimeError: memory access out of bounds, exactly as the main-process comment warns. The strong-reference mitigation in BinaryDisassembler is still required.


The CodeListing contract

Draft in code-listing.ts. It survived all four axes, with two changes forced by evidence:

type ListingAddressing = 'file-offset' | 'method-relative' | 'runtime-address';
type ListingRowKind    = 'instruction' | 'label' | 'comment';

interface ListingRow {
  kind?: ListingRowKind;
  address?: number;      // ← became optional
  fileOffset?: number;   // ← separate from address, and essential
  bytes?: readonly number[];
  mnemonic: string;
  operands: string;
  comment?: string;
  sourceLine?: number;
}

Change 1 — address had to become optional. The .NET JIT emits an offset per instruction group (G_M000_IG02: ;; offset=0x0000), never per instruction. Requiring an address would have meant inventing one. This is the single clearest vindication of not forcing everything through DecodedInstruction.

Change 2 — rows needed a kind. JIT output interleaves group labels (which carry the only offsets) with instructions (which carry none). Modelling labels as rows keeps sections flat, which matters for the panel (see question 2).

Keeping fileOffset separate from address was the right call, and it is load-bearing rather than decorative: it is what makes binary-view cross-highlight possible for IL and bytecode, whose address is method-relative and therefore not unique across sections.

Where it strains

  1. address is not unique under method-relative. Every method starts at 0. Any lookup keyed on address alone is ambiguous; it must key on fileOffset, or on (sectionId, address).
  2. JIT rows have neither fileOffset nor address. Cross-highlight is impossible for them by construction — the bytes exist in no file. The panel must degrade, not fail.
  3. Address rendering base is per-language. ildasm and native use hex; javap uses decimal. The contract stores numbers and the renderer must choose — I got this wrong first time and printed decimal addresses beside hex branch targets, which read as corruption.
  4. origin earns its place. buffer (unsaved edits visible) vs file (sidecar, cannot see them) vs process is a real distinction the UI must surface — see question 5.

The seven questions

1. Does CodeListing unify all three without lying? Where does it strain? Yes, after making address optional and adding kind. Strains listed above — none fatal, all mechanical. The honest summary: the contract works because it refuses to pretend JIT rows have addresses or that method-relative offsets are file offsets.

2. Does the Monaco panel's offset-keyed reveal survive sectioning, or need replacing? Survives, with a targeted change — no replacement needed. binary-disasm-panel.ts keeps a flat lines: LineInstruction[] where index = line − 1, and lineForOffset / applyHighlight both match on startOffset. Two changes:

  • the line map must become sparse ((LineInstruction | null)[]) because section headings and note lines map to no instruction;
  • lookups must key on fileOffset, not address — under method-relative, startOffset is not unique across methods, so the current findIndex would land on the first method every time.

The flushPendingReveal / onDidLayoutChange machinery is orthogonal to sectioning and needs no change. (It is also still necessary — revealLineInCenter on a zero-height editor is silently dropped.)

3. Source → method → instruction mapping?

  • .NET: yes, via portable PDB sequence points. Demonstrated end to end.
  • JVM: LineNumberTable, read by the decoder. It requires -g (or at least -g:lines). javac includes line numbers by default, but Gradle/Maven release configurations sometimes strip them — so the UI needs the same "no mapping available" state as the no-PDB case.

4. How does the runtime axis get the program run? Reuse a run configuration and overlay environment variables — the prototype's captureJitDisasm does exactly this and it is the right shape, because the workspace already owns run configurations. Two unsolved problems, deliberately left for P6:

  • A program that never terminates. The prototype uses a 30-second timeout, which is a placeholder, not an answer. JIT output streams, so the real design should stream and let the user stop it.
  • A program needing stdin. Not addressed at all. Terminal-backed runs already exist in the repo (#337) and are probably the answer — route JIT capture through a real terminal-backed run rather than a captive spawnSync.

5. Unsaved edits — is a path-based read acceptable for the .NET sidecar? The split is real: the JVM and WASM decoders take bytes, preserving the existing invariant that unsaved hex edits decode correctly. The .NET sidecar takes a path and cannot see them. This is why ListingOrigin distinguishes buffer from file. Recommendation: accept the path read, and have the panel show an explicit "showing the file on disk — unsaved edits not reflected" banner whenever origin.kind === 'file' and the document is dirty. Silently showing stale IL would be worse than either alternative.

6. Is a Tier0/FullOpts toggle enough? A toggle is necessary but not sufficient on its own. Tiering also means a method may never appear if it was never called, or appear only as Tier0 if it never got hot. The listing must therefore be able to say "this method was not JIT-compiled during the run" as a first-class state, and DOTNET_JitDisasmSummary gives exactly the inventory needed to distinguish "not compiled" from "compiled but not dumped".

7. Where does the source-first entry point live? The two views differ and should not be forced together:

  • Binary view: add a value to BinaryPanelKind ('disassembly' | 'inspector' | 'agent'). It is a clean additive seam — one union member plus one entry in PANEL_KINDS.
  • Code view: not the same pattern. code-view.ts composes PanelLayout + Panel with per-panel components and per-panel state services (CodeAgents, terminal state); there is no generic panel-kind registry. So the "Generated code" panel is a new Panel in code-view with its own small state service mirroring CodeAgents.

Recommendation on the phase breakdown

The P1–P8 sketch holds, with three amendments:

  1. P7 (AOT) is not near-free — re-scope it. It needs the machine-override un-XOR and a managed-but-R2R rule. Consider folding it into P4 (.NET), since both are .NET PE work, and adding the Mach-O codeOffset gap to it.
  2. P2 (JVM) is smaller than planned and P3 (WASM) is comparable to it. Both are dependency-free pure-TS decoders validated against oracles. They could reasonably be one phase.
  3. P6 (runtime) is the riskiest phase and should not be last-but-two. The two open questions (non-terminating programs, stdin) are design problems, not implementation ones, and they interact with terminal-backed runs (#337). Schedule it earlier or spike it separately.

Suggested revision: P1 contract + panel · P2 pure-TS decoders (JVM + WASM) · P3 .NET sidecar + AOT · P4 source-first entry point · P5 runtime axis · P6 polish. Six phases instead of eight.

Not done

Out of scope and untouched: production code, tests, packaging, hsdis acquisition or build, Python .pyc, eBPF, and any actual UI. The .NET sidecar has no process-lifetime management (#195's "reused per session, torn down cleanly" is carried forward to P3, not demonstrated here).

Clone this wiki locally