Skip to content

[AUTOMATED] feat(p1): dwarfstructs — import DWARF aggregate size and fields (DIV-85) - #330

Merged
mahaloz merged 2 commits into
mainfrom
feat/dwarfstructs
Aug 22, 2026
Merged

mahaloz merged 2 commits into
mainfrom
feat/dwarfstructs

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

The defect

analyzers/dwarf/mod.rs::intern_aggregate resolved every
DW_TAG_structure_type / union_type / class_type to get_type_struct(name) —
a named, empty, zero-size shell. It never read DW_AT_byte_size and never
walked a single DW_TAG_member. The module header stated the scope openly
("Type recovery is name/signature-level") and the call site's comment called it
sufficient ("A named opaque struct is enough for a pointer-to-struct to render").

It is sufficient for exactly that one case. A width of zero is not a
conservative answer — the ABI classifier acts on it.
x86-64 parameter-storage
assignment reads the size, so:

typedef struct { int a; int b; } P8;
int take_struct(P8 p, int k) { return p.a + p.b + k; }
P8  ret_struct(unsigned int x) { P8 s; s.a = x+1; s.b = x*7; return s; }
long take_nest(Nest *n) { return n->tag + n->inner.a + n->inner.b + n->tail; }
before after
take_struct int take_struct(unsigned long p,int k) + a hand-rolled >> 0x20 int take_struct(P8 p,int k) { return p.b + p.a + k; }
ret_struct P8 *ret_struct(P8 *rethidden,unsigned int x) … (int)rethidden * 7 P8 ret_struct(unsigned int x)
take_nest *(int *)((long)n + 4) (n->inner).a
take_bits (*(unsigned char *)b & 7) + (*(unsigned char *)b >> 3) + … b->lo + b->mid + b->hi

On the survey's phantom-rethidden caveat: I DID reproduce it, on the exact
witness quoted in the task, with the prebuilt origin/main binary. An 8-byte
struct return is a register return on this ABI; a zero-size return type is
classified as a hidden-return-buffer call, so a phantom first parameter appears,
the real one shifts, and the body does arithmetic on the phantom. It disappears
with --option dwarf off, which pins the cause on this pass. My guess at why the
survey saw unsigned long ret_struct(int a0) instead: their build had gcc emit
the function as a nameless out-of-line concrete instance
(DW_AT_abstract_origin, no DW_AT_name), which the DWARF pass skips entirely
— an adjacent, pre-existing gap noted below.

What ships

Option dwarfstructs (on|off, analysis tier, default-ON, DIV-85), gated
through the same load-time env bridge as typedepth
(p0_knowledge/kuna_dwarfstructs.rs + KUNA_DWARFSTRUCTS; the layout is
installed at load file, upstream of every option command).

analyzers/dwarf/kuna_dwarfstructs.rs reads DW_AT_byte_size, walks the
DW_TAG_member children, places each at its DW_AT_data_member_location
verbatim, and recurses each member type through the same DIE switch. Offsets
go in through a new raw seam (TypeFactory::set_fields_struct_raw /
set_fields_union_raw, the structural analog of get_type_enum_sized) rather
than assign_raw_fields_struct, whose C packing rules skip a field whose offset
is already set and would therefore also size the structure at 0.

DW_TAG_variant_part / DW_TAG_variant / DW_AT_discr are deliberately not
read — a Rust enum recovers its width and no fields.

The collision trap: confirmed, and load-bearing

The factory interns by (name, hash(name)) and find_add refuses a second,
different definition of a name it holds. That was invisible while every aggregate
was a sizeless shell (two shells compare equal); it goes live the moment fields
exist. I verified the Rust claim on a fresh witness: a five-function rustc -g
binary carries four distinct Some DIEs of sizes 16, 24, 16 and 12
(core::option::Option<usize>, Option<(NonNull<u8>, Layout)>,
Option<&[Placeholder]>, Option<rw::Pair>).

Aggregates are therefore interned parent-qualified (reusing kuna_cppproto's
ancestry walk) and, when that name is still held by a different-sized aggregate,
under a size-suffixed variant. Verified by ablation: with the disambiguation
clamped off, the fixture's second struct Same degrades its whole parameter to
int read_same_big(void *s); with it, Same (4 bytes) and Same_16 both keep
their members.

Self-reference (struct node { struct node *next; }) is handled by interning the
shell before walking the members plus a new TypeWalk::begin_aggregate claim
that refuses the re-entrant populate. Documented LOSS: kuna's interned types are
immutable, so completing one mints a new Rc and the pointer the inner frame
captured still refers to the pre-completion shell — n->next renders and names
its type, n->next->val does not chain (the same model the wire
decode_composite path lives with).

Three defects the measurement found before they shipped

  1. Union collapse. Every union member sits at offset 0, so the struct-side
    dedup-on-offset reduced a union to its FIRST member — u->f and u->c[2]
    silently became reads of u->i. Fixed; a dedicated e2e assertion now pins it.
  2. Bitfield container geometry. Giving each bitfield the whole storage unit
    as its container reports byte_offset == 0 for a member the compiler reaches
    through a PTRSUB at +3, so checkBitFieldMember did not skip that PTRSUB
    and printed p.b on a pointer — invalid C. Each bitfield now gets the
    smallest byte span covering it, which is what the access geometry agrees with.
  3. A pre-existing engine defect, contained not fixed (reported, see below).

An engine defect this change is the first thing to reach

BitFieldPullTransform (p5_types/bitfield/pull.rs) diverges when several pulls
share one extraction chain: the second record's op_destroy_recursive walks a
mod_op whose operands the first record's walk already unset, and
Funcdata::op_destroy_recursive asserts on the cleared slot
(op_destroy_recursive: null input (C++ UB)).

Reproducer, two lines of C, on main today via the Ghidra-wire <bitfield>
decode as well — it is not specific to this pass:

struct S { int head; unsigned f1:4, f2:12, f3:16; };
unsigned g(struct S *s){ return s->f1 + s->f2 + s->f3; }   /* panics */

I tried the obvious fix (tolerate the cleared slot; skip already-dead ops; bound
the worklist) and it only converts the assertion into a non-terminating rule
pool
— so the fix belongs in that transform and I reverted my engine edit
rather than ship a hang. Containment instead: a "bitfield" occupying whole
aligned bytes of a natural width is not one (on little-endian unsigned c:16 at
bit 16 of a 4-byte unit is the two bytes at +2) and goes in as a plain field,
which keeps the shapes this pass produces inside what the transform handles. A
nine-shape bitfield stress corpus decompiles clean, and decompilation failed is
0 → 0 across the whole measurement corpus.

Measurement

The gates cannot see this change — both parity corpora are <bytechunk> XML
that never reaches the analyzer tier — so the A/B below is the deliverable.

Breadth — whole-binary decompile-all, off vs on, 27 targets / 3764
functions
(decbench-dataset zlib/bzip2/gzip/coreutils-fmt/diffutils/libexpat/
openssh O0 + zlib/bzip2 O2, every repo -g fixture including the four C++ ones, a
Rust -g binary, and purpose-built C witnesses):

metric off on delta
functions whose body changes — 891 / 3764 23.7%
cast-and-offset derefs *(T *)((long)x + N) 10147 1662 −84%
->field accesses 6 11319 +11313
void * 1456 1189 −18%
decompilation failed 0 0 0
undefined<n> 14 22 +8
functions with a duplicated local decl 1320 1326 +6

Line counts fall on the bigger targets (ssh-keygen 38009 → 37722, bzip2-O0
6860 → 6730, gzip 6593 → 6544) because a named field replaces a cast expression.

Representative (zlib gz_look, deflate_stored, the C++ cppproto fixture):

-    *(unsigned int *)((long)state + 0x28) = *(unsigned int *)((long)state + 0x2c);
-    if (inflateInit2_((z_stream_s *)((long)state + 0x80),0x1f,"1.2.13",0x70)) {
+    state->size = state->want;
+    if (inflateInit2_(&state->strm,0x1f,"1.2.13",0x70)) {
-    *(unsigned char *)(*(long *)((long)s + 0x28) + -4 + *(long *)((long)s + 0x10)) = (unsigned char)len;
+    s->pending_buf[s->pending - 4] = (unsigned char)len;
-  char v3 [24];  Shape::Shape((Shape *)v3,argc);
-  v1 = (*(void *)**(unsigned long **)s)(s,scale);
+  Shape v3;      Shape::Shape(&v3,argc);
+  v1 = (**s->_vptr.Shape)(s,scale);

The wrongness axis, reported as measured rather than as zero. undefined<n>
+8 and duplicated-declaration functions +6 (of 3764; the pathology is
pre-existing on 1320 of them). Both come from one place: a local that is now a
real aggregate with a union member gets per-use union resolution, and the
declaration emitter prints one declaration per resolved width. That is the
existing dedupvardecls/union-resolution seam, not a new one — 6 functions
against 891 improved.

Controls. The stripped copy of zlib minigzip is 0 changed lines
(so the decbench scored corpus, which is stripped, is a structural zero here —
verified, not assumed, exactly as for DIV-63). The four -g fixtures with no
aggregates (dwarf_globals, stacklocal, dwarf_enums, dwarf_stripped) and
three of the four C++ fixtures are 0 changed lines.

Speed — the layout walk runs once per binary inside load file, so LOAD is
the primary metric. Interleaved off/on, MINIMUM of N pairs on a box shared with
concurrent agents. An early n=15 read of +2.87% (gzip) and +3.58% (bzip2) was
contention; both vanish at higher N:

functions gzip-O0 (LOAD) n=25      off=    311 ms  on=    310 ms    -0.32%
functions zlib-minigzip-O0 n=15    off=    424 ms  on=    417 ms    -1.65%
functions ssh-keygen-O0 n=7        off=    276 ms  on=    278 ms    +0.72%
decompile fmt-O0 main n=15         off=    430 ms  on=    433 ms    +0.70%
decompile-all bzip2-O0 n=7         off=  23453 ms  on=  23466 ms    +0.06%
decompile-all zlib-minigzip-O0 n=5 off=   4697 ms  on=   4732 ms    +0.75%
decompile-all gzip-O0 n=5          off=   2665 ms  on=   2657 ms    -0.30%
decompile-all fixture n=10         off=    203 ms  on=    194 ms    -4.43%

Worst delta +0.75%, budget 5%.

Default-ON argument

Both parity corpora are structurally blind to this change (0/675 is true but
vacuous), so the case rests on the A/B: 891 functions improved, every counted
quality pattern moving the right way, zero new decompilation failures, 0 lines on
the stripped control, worst speed delta +0.75%, and a wrongness axis of +6
functions on a pathology that already affects 1320. A zero-size aggregate is not
a conservative answer — it is a wrong one the ABI classifier acts on — so off
is the reproduction, not the safe default. --option dwarfstructs off restores
the name-only mapping byte for byte.

Adjacent gaps observed, NOT fixed here

  • DW_AT_abstract_origin subprograms lose their prototype. When gcc inlines a
    function somewhere it emits a named abstract instance plus a nameless
    out-of-line concrete instance; the name-only arm skips the latter (no
    DW_AT_name) and kuna_cppproto follows only DW_AT_specification for a
    subprogram. Four functions in my first witness lost their signature this way,
    identically off and on. Pre-existing, orthogonal, worth its own PR.
  • A by-value aggregate parameter that rustc passes indirectly now gets its
    DWARF type while the body still reads the register as a pointer, leaving one
    unassigned local (rw::f_some_pair). 5 of 540 functions changed on the Rust
    witness; the type is right and the body is no worse than the u64 it replaced.

Tests

  • decompiler/crates/kuna-console/tests/verify_dwarfstructs.rs — 9 two-pass
    e2e assertions
    over a new -g -O1 two-translation-unit fixture
    dwarfstructs_x86_64 (both sources vendored): by-value struct parameter,
    phantom small-struct sret, the REAL 24-byte sret surviving, union, a union
    keeping EVERY member, nested struct, bitfield, self-referential node
    terminating, and two same-named different-sized aggregates both surviving.
  • kuna_dwarfstructs.rs env-gate unit test; TypeWalk aggregate-claim unit test.
  • verify_typedepth.rs pins dwarfstructs off so it keeps measuring its own
    axis (that arm renames the anonymous fallback and interns a name-colliding
    aggregate as code_4 with fields — both strict improvements on what those
    assertions pin, and both covered by verify_dwarfstructs.rs).
  • No stage XML: the datatest path cannot reach the analysis tier.

Gates (run locally — CI skips make rust-test on a same-repo branch)

$ make test
datatests: 675/675 assertions passed
exit: 0

=== baseline parity ===
PARITY OK

$ make test-stages
datatests: 501/501 assertions passed
exit: 0

=== baseline parity ===
PARITY OK

$ make rust-test
cd /home/mahaloz/github/kuna-wt-dwarfstructs/decompiler && cargo test --workspace --no-fail-fast
...
   Running tests/options_md_fresh.rs (target/debug/deps/options_md_fresh-0e700da2674e1bef)
test options_md_matches_the_generator_byte_for_byte ... ok
...
# 319 test suites: 4724 passed, 0 failed, 38 ignored -- green

$ make check-spec
check-spec OK (lenient mode)
$ python3 tools/check_spec.py --strict
check-spec OK (strict mode)

$ ./decompiler/target/release/kuna catalog --check
catalog OK: documents exactly the registered kuna options

No baseline was re-pinned.

🤖 Generated with Claude Code

https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9

mahaloz and others added 2 commits August 22, 2026 17:02
…fields (DIV-85)

The DWARF type mapper interned every DW_TAG_structure_type/union_type/
class_type as a named, EMPTY, zero-size shell: it never read DW_AT_byte_size
and never walked a DW_TAG_member. That is enough for `struct foo *p` to
render and nothing else, and a zero width is not a conservative answer --
x86-64 parameter-storage assignment reads the size, so a by-value struct
parameter degraded to the raw register it arrives in and an 8-byte struct
return (a REGISTER return on this ABI) was classified as a hidden-return-
buffer call, growing a phantom `rethidden` parameter the body then did
arithmetic on.

The new arm reads DW_AT_byte_size, walks the DW_TAG_member children, places
each at its DW_AT_data_member_location verbatim (bitfields off DW_AT_bit_size
with either the DWARF 4/5 DW_AT_data_bit_offset or the DWARF 2/3
byte_size+bit_offset spelling), and recurses each member type through the same
DIE switch. Offsets go in through a new raw field-setting seam
(TypeFactory::set_fields_struct_raw / set_fields_union_raw) rather than the C
packing rules, which would re-derive them and size the structure at 0.

Two hazards come with populating fields. The type factory refuses a second,
different definition of a name it holds -- invisible while every aggregate was
a sizeless shell -- so aggregates are interned parent-qualified and, on a
size clash, under a size-suffixed name (rustc names every enum payload struct
bare: a five-function Rust witness carries four distinct `Some` DIEs of sizes
16/24/16/12). And a self-referential struct reaches its own DIE mid-populate,
so the shell is interned before the members are walked and TypeWalk refuses
the re-entrant population. DW_TAG_variant_part/variant/DW_AT_discr are
deliberately not read.

Behind `--option dwarfstructs on|off` (analysis tier, default-ON, DIV-85),
gated through the same load-time env bridge as `typedepth`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9
…ds use the access geometry

Three defects found by measurement after the first commit, all in the new arm.

1. Union collapse. Every union member sits at offset 0, and the struct-side
   dedup-on-offset therefore reduced a union to its FIRST member: `u->f` and
   `u->c[2]` silently became reads of `u->i`. Union fields now keep declaration
   order and are not deduplicated. Covered by two new fixture readers and a new
   e2e assertion.

2. Bitfield container geometry. Giving each bitfield the whole storage unit as
   its container reports `byte_offset == 0` for a member the compiler reaches
   through a PTRSUB at +3, so the printer's `checkBitFieldMember` did not skip
   that PTRSUB and emitted `p.b` on a POINTER -- invalid C. Each bitfield now
   gets the smallest byte span that covers it, which is the geometry the access
   agrees with.

3. A bitfield that occupies whole aligned bytes of a natural width is not a
   bitfield: on little-endian `unsigned c:16` at bit 16 of a 4-byte unit IS the
   two bytes at +2, and it now goes in as a plain field of that width. That is
   exact, and it is also containment for a pre-existing engine defect this pass
   is the first thing to reach: BitFieldPullTransform diverges when several
   pulls share one extraction chain (the second record's op_destroy_recursive
   walks a mod_op whose operands the first walk unset, and the port asserts on
   the cleared slot). `struct { int head; unsigned f1:4, f2:12, f3:16; }` with
   all three read reproduces it. Tolerating the cleared slot only turns the
   assertion into a non-terminating rule pool, so the fix belongs in that
   transform; the byte-exact rule keeps this pass inside what it handles.

Also pins `dwarfstructs off` inside verify_typedepth so that file keeps
measuring its own axis, and records the final measurements in the DIV-85 row:
891 of 3764 functions change across 27 targets, cast-and-offset dereferences
10147 -> 1662, `decompilation failed` 0 -> 0, worst speed delta +0.75%.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant