Go heap (go_heap)

go_heap is the heap-aware reduction for Go processes. It reads the Go runtime’s own heap structures out of each .msl dump without symbols, pairs heap slots (not addresses) across N separately started runs, and runs the usual variance gates inside the paired slots. Go runtime metadata (module data, types, interface tables, reachability from the globals) labels and ranks the result, but never filters it. Freed slots are paired too: on gocryptfs, every master-key copy in the test corpus sits in a freed slot.

Go, Scudo, and Windows use the same block consensus engine. See Heap-aware reduction for an overview of the three methods.

1. Why Go heaps defeat positional consensus

MemDiver’s default reduction is positional. It stacks N dumps of N separately started runs, compares the byte at the same address in every dump, and keeps the bytes whose value changes from run to run. A key is new in every run, so its bytes vary, and code, constants and stable pointers do not. This only works when the same object sits at the same address in every dump.

Go processes break that assumption in two ways:

  1. Objects do not co-locate. Two Go processes started separately place their objects at different addresses. The heap grows from an arena hint, goroutines allocate through per-P caches, and the GC reuses free slots in an order that depends on timing. A positional comparison at address X then compares the key in dump 1 with an unrelated object in dump 2. The key’s “variance” is noise, and a slot that holds the key in only some dumps can fall below the variance floor.

  2. The interesting copies are in freed memory. Go does not clear memory when it frees it. A slot freed by the GC keeps its last bytes until another allocation reuses it. Short-lived buffers that held secrets therefore leave stale copies behind. In the gocryptfs test corpus, every ground-truth master-key address resolves to a freed 128-byte slot (see Measured results).

The idea of go_heap, in one paragraph. Parse each dump’s Go heap into spans and slots. Put slots in cross-dump correspondence: first whole spans, by a signature built from the span’s geometry, its slot states and the shape of its live words, then by content, then by a bounded slot shift. After that, anchor labels taken from the Go runtime metadata pair some of what is left, and a generic block consensus pairs the rest. Each paired slot row then has an exact per-byte variance across the N dumps, live and freed slots alike. The kept slots of one reference dump are laid end to end, and the positional reduce gates run on them, so a kept 128-byte slot shrinks to the bytes that really vary. The surviving regions are ranked by reachability from the program’s globals and written as candidates.json in the reference’s flat vas view, ready for brute-force.

Three panels. (a) The same 8-slot span sits at three different addresses in three dumps; lines connect slot 4 of each, a freed slot holding the key, because the span signature matches. A second pair of spans is matched with slot t of dump 0 linked to slot t+2 of dump 1, labelled at-shift 0,2. (b) One paired slot row drawn as a 3 by 16-word matrix, one row per dump; words at offsets 32 to 63 differ per dump, and the variance row below is zero except at those four words. (c) The pairing cascade: span, then anchor labels, then block fallback; then a reduce slab of the reference's kept slots separated by 64 zero bytes, where the gates keep only the key bytes, and a ranked output by tier.

How go_heap builds its matrix: (a) pair spans, (b) one N × slot-length matrix per paired slot row, (c) the cascade and the in-slot reduce.

2. Go heap primer (what MemDiver needs)

This is the part of the Go runtime’s memory allocator (runtime/mheap.go, mcentral.go, mbitmap.go, sizeclasses.go) that MemDiver reads. MemDiver supports 64-bit runtimes of Go 1.18 to 1.26 (newer minors are read with the newest layout) on amd64 and arm64.

Arenas and pages

The Go heap lives in arenas: 64 MiB regions of anonymous rw- memory (4 MiB on 64-bit Windows; heap_arena_bytes()). On amd64 the runtime asks the kernel for arenas at fixed hint addresses i<<40 | 0x00c0<<32 (arm64: i<<40 | 0x0040<<32, i ≤ 127), which is why a Go heap typically starts at 0xc000000000. An arena is cut into 8 KiB pages (PAGE_SIZE = 8192).

For each arena the runtime keeps a heapArena record. MemDiver reads two of its fields:

  • spans: one *mspan pointer per page of the arena (8192 entries for a 64 MiB arena). Every page of an in-use span points at that span’s record.

  • pageInUse: one bit per page, set on the first page of each in-use span. MemDiver uses it as a coverage check.

The offset of spans inside heapArena depends on the release. In go1.18 and go1.19 a 2 MiB bitmap field comes first (spans at +2097152). In go1.20 and go1.21 a 1 MiB bitmap and the noMorePtrs bitmap come first (spans at +1064960 on amd64). From go1.22 on, spans is at offset 0 and pageInUse follows it at +65536. MemDiver reads the offset from the generated layout data, never from a constant typed by hand.

Spans (runtime.mspan)

A span is a run of npages contiguous pages managed as a unit. Its descriptor, runtime.mspan, is not inside the arena. The runtime allocates it from a separate fixed-size allocator in other anonymous memory. The fields MemDiver decodes are listed below. Offsets are for the go1.22 to go1.25 layout; every layout is generated from DWARF.

field

offset (go1.22–1.25)

meaning

startAddr

+24

first byte of the span (page-aligned, inside an arena)

npages

+32

number of 8 KiB pages

freeindex

+48 (u16)

allocation cursor: every slot below it is allocated

nelems

+50 (u16)

number of slots

allocBits

+64 (pointer)

bitmap, one bit per slot (1 = allocated at the last sweep)

allocCount

+96 (u16)

allocated slots (validation only)

spanclass

+98 (u8)

size class and noscan bit (below)

state

+99 (u8)

0 dead (mSpanDead), 1 in use, 2 manual

elemsize

+104

slot size in bytes

limit

+112

end of the slots’ data

startAddr (+24) and npages (+32) are at the same offsets in every supported layout. The other offsets move between releases. For example, go1.18–1.20 use 8-byte freeindex/nelems at +48/+56 and allocBits at +72, and go1.21 shifts allocCount/spanclass/state/elemsize/limit by 8 bytes. MemDiver does not read gcmarkBits.

Span kinds. A small span (size class ≥ 1) holds nelems equal-size slots. A large span (size class 0) holds one object, and elemsize equals the span size. A manual span (state 2) holds goroutine stacks or GC work buffers. It has no object slots, and MemDiver never pairs it.

Size classes, span classes and noscan

Go rounds every small allocation up to one of 68 size classes: 0 (large), 8, 16, 24, 32, 48, 64, 80, 96, 112, 128, … up to 32768 bytes (MAX_SMALL_SIZE). Each class has a fixed span size (class_to_allocnpages). Size class 10 is 128 bytes in a one-page span. The spanclass byte packs the size class and one more bit:

spanclass = sizeclass << 1 | noscan        sizeclass = spanclass >> 1, noscan = spanclass & 1

noscan = 1 means the objects contain no pointers. The GC does not scan them, and from Go 1.22 they carry no pointer bitmap and no malloc header. Span class 21 is therefore size class 10 (128 bytes), noscan. This is the class of the gocryptfs master-key slots.

The spanclass byte 21 drawn as eight bits 00010101. Bits 7 to 1 are bracketed as spanclass shifted right by one, size class 10, which maps to 128 bytes per slot, one 8 KiB page and 64 slots. Bit 0 is bracketed as the noscan bit, meaning pointer-free objects with no pointer bitmap and no malloc header. A note says 20 is size class 10 scan and 21 is size class 10 noscan.

The span class byte: size class in bits 7–1, the noscan flag in bit 0.

Span geometry per release (SpanGeometry):

  • legacy (Go ≤ 1.21): nelems = span_bytes // elemsize.

  • allocheaders (1.22–1.25): scan spans with elemsize ≤ 512 reserve the last span_bytes/64 bytes for the pointer bitmap. Scan objects larger than 512 bytes start with an 8-byte malloc header, a *_type pointer.

  • greentea (1.26): additionally reserves 128 bytes of inline mark bits for every small span with 16 ≤ elemsize ≤ 512, scan and noscan alike.

limit is start + (N // e) * e up to Go 1.22 and start + nelems * e from 1.23 on, where N is the span size in bytes and e is elemsize. MemDiver accepts both.

Slots and their allocation state

Slot i of a small span starts at startAddr + i * elemsize. The runtime allocates by advancing freeindex through the span and skipping slots whose allocBits bit is set. A sweep replaces allocBits with the mark bits and resets freeindex. MemDiver’s rule (GoSpan.slot_state) follows from that:

manual span                           -> unknown
index < freeindex                     -> allocated
allocBits byte not captured           -> unknown
allocBits bit (index) == 1            -> allocated
allocBits bit (index) == 0            -> free

A free slot is memory the program let go of. Its bytes are still the last contents. Neither the runtime nor MemDiver clears them.

Freed spans and span-less pages

When a whole span is freed, its pages return to the page heap. The span record’s state becomes mSpanDead, but the runtime never clears the heapArena.spans entries. A resident arena page that no in-use span covers is therefore classified from its stale table entry (golang_pages.classify_pages):

reason

evidence

provably free?

freed_span

the entry points at a dead mspan that covered this page

yes

stale_entry

the entry points at an mspan reused for other pages

yes

no_span_entry

the entry is nil: the page never held a span

yes

no_span_table / entry_not_captured / record_not_captured / invalid_span

the evidence is missing

no (UNKNOWN)

Consecutive pages with the same reason merge into a GoPageRun (heap bin spanless_pages). A provably free run gets the FREE_DATA byte role: the stale payload of a freed span.

Panel a shows a heapArena spans table of six entries above six arena pages. Entries point up to mspan records A, B, D and E, which live in anonymous memory outside the arena. Pages 0 to 2 belong to live spans A and B. Page 3's entry points at dead mspan D (freed_span), page 4's entry is nil (no_span_entry), and page 5's entry points at a reused record E (stale_entry); these three are bracketed as span-less pages, provably free, FREE_DATA. A box lists the mspan fields read in the go1.22 layout. Panel b shows the first 16 slots of span A with freeindex 3: slots 0 to 2 are allocated because they are below freeindex (slot 1 even though its allocBits bit is 0), and the rest follow their allocBits bit. Freed slot 4 is expanded into 16 eight-byte words, with key bytes at offsets 32 to 63.

The Go heap as MemDiver parses it: arena pages, the per-arena spans table and the mspan records (a), and one span’s slots with their allocation state (b).

3. Parsing the Go heap without symbols

Release builds of Go programs are often stripped, and an .msl slice carries no symbol table for the target. MemDiver therefore finds the heap from the data alone (heap/allocators/golang.py, parse_go_heap).

  1. Arena candidates. Anonymous writable mappings are split into hinted arenas (at a Go arena hint), unhinted arenas (64 MiB-aligned) and scan memory (captured anonymous memory that is not a hinted arena, where the mspan records live). An unhinted arena is kept only if at least UNHINTED_ARENA_MIN_SPANS = 2 validated spans fall in it. Only 64-bit runtimes are read.

  2. Go version. MemDiver looks for the .go.buildinfo header ("\xff Go buildinf:") in the captured non-executable module mappings and decodes the version string, for example go1.22.2. The minor version picks the preferred layout profile.

  3. Candidate records. Every aligned word pair in scan memory that looks like startAddr, npages is a candidate. The first word must be page-aligned and inside an arena, and the second must satisfy 1 ≤ npages ≤ 2^20. The record starts 24 bytes earlier.

  4. Layout selection by validation. Each generated RuntimeProfile (go1.18–1.20, go1.21, go1.22–1.25, go1.26+) decodes every candidate. The profile that validates the most records wins, and a tie goes to the preferred profile. Validation (span_violations) checks placement (aligned start, whole span inside one arena), state ∈ {in use, manual}, sizeclass < 68, and, for a small span, elemsize == class_to_size, npages == class_to_allocnpages, nelems per the release’s geometry, limit per one of the two formulas, and allocCount, freeindex ≤ nelems. Large and manual spans have their own rules. A random word pair almost never passes all of these checks. That is what makes the scan safe without symbols.

  5. The spans table by a 3-vote rule. Every aligned word in scan memory that equals a validated mspan address votes for a table base: the word’s address minus 8 × (page index of the span start within its arena). Only the first page of a span votes, because repeated equal words are skipped. A base needs MIN_TABLE_VOTES = 3. The entries of an accepted table are then decoded, and every entry that points at a valid record yields a span (source="table"). This also recovers spans whose records the scan missed.

  6. Fallback through mheap_.arenas. If an arena’s table got fewer than 3 votes (on 5 of 20 gocryptfs dumps the second arena was missed this way, per CHANGELOG.md: its mspan records can sit in an anonymous mapping that the capture attributes to a module, which the scan never reads), MemDiver finds the runtime’s L2 arena index. That index is an array of *heapArena with one entry per arena index. MemDiver takes the word holding a located arena’s heapArena address and steps 8 × (index difference) from it to the missing arena’s heapArena. The table address is that plus the spans offset. A recovered table is kept only if its entries resolve to valid spans.

  7. Merge and slot states. Table spans and scanned spans are merged, and overlaps count as conflicts. Then allocBits ((nelems+7)//8 bytes) is read for every non-manual span. Span-less resident pages are classified as in section 2.

The result is a GoHeap. It holds the validated spans, the arenas, the Go version and profile, the located span tables, the span-less page runs, a coverage report (spans by source and kind, in_use_coverage, matched pageInUse bits, span-less pages by reason) and diagnostics. In the generic heap layout, each slot becomes one chunk (bin class_<sizeclass>, large or manual), and each span-less run becomes one more chunk. Layout confidence is 0.95 with located span tables, 0.75 from the scan alone, and 0 without spans.

Detection. probe_golang scores 0 and reads nothing unless an anonymous rw- mapping sits at a Go arena hint. Otherwise it combines three pieces of evidence: the hint (0.3), the buildinfo (0.6) and validated mspan records (1.0), as 1 − Π(1 − w). It is registered above ptmalloc2 because a cgo binary also maps glibc.

4. The Go metadata approach

The heap parser answers where the slots are and whether they are live. The Go runtime metadata answers what a slot is and how the program reaches it. MemDiver reads that metadata without symbols too (golang_moduledata.py, golang_objects.py, golang_reach.py, golang_semantics.py).

Three areas. Read-only module mappings hold the runtime.pcHeader with its magic, _type records with their field offsets, the abi.Name string a _type's Str offset points to, and an itab whose Type field points to the concrete _type. Writable module mappings hold runtime.firstmoduledata, whose word 0 points at the pcHeader and whose fields locate types, typelinks, itablinks and the GC masks, plus the .data and .bss words with one mask bit per word. Numbered steps: 1 find the magic, 2 find its address as an aligned writable word, 3 validate that the mask bit counts equal the section sizes in words, 4 read types and itabs, 5 walk from the masked words. The itab word of a global interface value points at the itab and has mask bit 0; its data word, mask bit 1, points into the Go heap at a live slot named main.gcm, which leads through field ks to a [32]uint8 slot with anchor label main.gcm->ks, tier 0. Another live slot, reached only from a goroutine stack, which is not a root, is tier 1, and a freed slot is tier 2.

The Go metadata walk: from the pclntab header to the module data, its types and itabs, and the reachability walk from the globals into the heap.

4.1 Finding runtime.firstmoduledata (Go ≥ 1.20)

Every Go binary has a module descriptor, runtime.firstmoduledata. It holds the bounds of the text, data, bss and types sections, the typelinks and itablinks slices, and the GC pointer masks of .data and .bss. Its first word points at the pclntab header (runtime.pcHeader), which starts with a magic number. The search therefore works in two hops:

for layout in layouts_to_try(go_version):              # generated, never guessed
  headers = 8-aligned VAs in captured read-only, non-exec module mappings whose bytes are
            u32 magic (0xfffffff1, Go 1.20+) | 00 00 | minLC in {1,2,4} | ptrSize 8
  for header in headers:
    for va in 8-aligned words == header in captured WRITABLE module mappings:
      decode the candidate struct with this release's moduledata layout
      accept iff  f.pcHeader == header
              and section bounds are ordered (text<etext, types<etypes, data<=edata, ...)
              and gcdatamask.nbits == (edata - data) / 8        # decisive:
              and gcbssmask.nbits  == (ebss  - bss)  / 8        # one mask bit per word

The GC-mask check is what makes the search reliable. A random word that happens to equal the header address almost never sits in a struct whose two bit-vector lengths match the data and bss sizes. For go1.22 on amd64 the fields are at data@208, bss@224, types@296, etypes@304, typelinks@352, itablinks@376, gcdatamask@536 and gcbssmask@552.

Support gates (golang_meta_layouts.py):

  • metadata needs Go ≥ 1.20 (MIN_METADATA_MINOR): the 0xfffffff1 header and the validated moduledata shape. A known version below 1.20, or one without a generated layout, gives a diagnostic. MemDiver never guesses a layout.

  • object typing needs Go ≥ 1.22 (MIN_TYPING_MINOR): from 1.22 the allocator records types next to the objects (allocation headers). Older heaps keep that information in heapArena.bitmap, which MemDiver does not read.

  • Only amd64 and arm64 are mapped.

4.2 Types and names

An address is a Go type (abi.Type, the runtime’s _type) if it is 8-aligned and inside [types, etypes). A _type record is 48 bytes: Size_@0, PtrBytes@8, TFlag@20, Kind_@23, GCData@32 and Str@40. Str is an int32 offset from types to an abi.Name, which is a flag byte, a uvarint length and the UTF-8 bytes. When TFlag & 0x02 (extra star) is set, the leading * is dropped. The kind is Kind_ & 0x1F. GCData gives the pointer mask (PtrBytes/8 bits). The reader also decodes struct fields (name, offset, type) and the element types of pointers, slices and arrays. typelinks lists every type as an offset from types.

4.3 Interface tables (itabs)

A non-empty Go interface value is two words: an itab pointer and a data pointer. The itab is a static record in read-only module data. Its inter (@0) points at the interface type (for example cipher.AEAD), its Type (@8) points at the concrete type (for example *aes.gcmAsm), and the method table follows. An empty interface (any) uses a _type pointer instead of an itab.

The heap layer recognises an itab by shape. A word w is an itab if it is 8-aligned, kind(*w) is interface, and *(w+8) is a type in the module. The heap layer does not iterate itablinks (it only counts them). The vol3 itab route below does use itablinks.

4.4 Typing the slots (Go ≥ 1.22)

ObjectTyper.slot_type gives each slot an allocator-recorded type when one exists:

slot

type_source

how

manual span

stack

no type

noscan span

noscan

no pointers; no name (no header, no bitmap)

large span

large_type

*_type at mspan + largeType (+152)

small scan, elemsize > 512

malloc_header

*_type in the slot’s first 8 bytes; the value starts at +8

small scan, ≤ 512

heap_bits

pointer bits from the span-end bitmap; no name

named by an edge

iface / eface / field

inferred during the reachability walk

A freed noscan slot (like the 128-byte gocryptfs key slots) can therefore never be named by MemDiver. It has no header and no pointers, and nothing live points at it.

4.5 Reachability from the globals: roots, walk, tiers

The roots are exactly the words the GC would scan in the module: every word of .data and .bss whose bit is set in gcdatamask / gcbssmask. A breadth-first walk (walk_from_globals) then runs as follows:

for each root word (section, word_va, value, previous word):
    reach(value, edge=(section, offset), named = iface_type(previous word))
while queue:
    slot = pop()
    pointer words = slot type's pointer offsets          # header / largeType / heap bits
                    or EVERY word if the mask is unknown ("conservative")
                    (none for noscan)
    for each pointer word into an arena:
        named = iface_type(previous word)                # (itab|type, data) names the target
             or field_type(parent type, offset)          # struct field / array element
        reach(word, edge=(slot, offset, hop), named)
reach(v): v is in an arena, the slot at v is in a non-manual span, not yet visited
          -> record the first edge (a shortest path), queue it

The walk is budgeted (MAX_REACH_SLOTS = 1 000 000, MAX_REACH_BYTES = 1 GiB) and reports truncation. Goroutine stacks are not roots. Their frames would need the pclntab stack maps, so a slot referenced only from a stack reads reachable = false. Manual spans are never entered.

Anchor label. GoReachability.anchor walks the first-reaching edge chain upward to the nearest named slot and appends the hops. Examples: main.gcm->ks, cryptocore.CryptoCore->AEADCipher, or, when nothing on the path is typed, bss+0x1a0->+0x18. A slot typed by its own allocator record is its own anchor. A slot named only by the edge that reached it is labelled from its parent’s side. In go_heap a slot carries an anchor only if it is reachable.

4.6 What the metadata is used for, and what it is not used for

used for

not used for

chunk attributes in heap analysis: type_name, type_source, pointer_offsets, reachable, anchor

removing any byte or slot from the candidates

go_heap step 2: anchor labels pair slots that span pairing left

overriding span pairing (a label never wins a conflict)

go_heap ranking tiers: 0 reachable live, 1 other live, 2 freed

deciding whether a slot is kept

the automatic method choice: a reference without readable module data stays positional

the heap parse itself (spans and slot states need no metadata)

the vol3 itab route reuses the same moduledata and name logic (stdlib port)

In short: metadata gives labels and ranking, never filtering. The reason lies in the main target. The master key MemDiver is after on gocryptfs is in a freed, untyped, unreachable slot. Any rule like “keep only reachable or typed slots” would drop it.

4.7 The itab route for gocryptfs (memdiver.gocryptfs.GocryptfsKeys)

The metadata also supports a second, complementary route that needs no cross-dump comparison at all. It follows live interface values to the keys behind them.

The gocryptfs key lifecycle. gocryptfs unwraps a 32-byte master key from gocryptfs.conf with the password. It never encrypts with the master key directly. HKDF-SHA256 (salt = 32 zero bytes) derives two keys from it:

  • the content key, with info "AES-GCM file content encryption" (or "XChaCha20-Poly1305 file content encryption"), held live behind CryptoCore.AEADCipher, a cipher.AEAD (*aes.gcmAsm, *chacha20poly1305.xchacha20poly1305, …);

  • the EME filename key, with info "EME filename encryption", held live behind EMECipher as a cipher.Block (*aes.aesCipherGCM, …).

AES keys are stored as their expanded 240-byte AES-256 key schedule.

Where the master key ends up is a matter of evidence, and the evidence has limits. What the repository pins (tests that run only when the corpus is present) is that on the v2b/v2c gocryptfs daemons (test captures) every ground-truth master-key copy sits in a freed 128-byte noscan slot (span class 21), at slot offset 32. The docs and the code say “every copy”, which refers to the observed ground-truth copies. That the slot is a freed crypto/sha256.digest of the HKDF’s HMAC is an inference from the layout: 32 bytes of constant state precede the key, and a 113-byte digest rounds up to the 128-byte class. Neither the parser (it cannot name a freed noscan slot) nor any test establishes that type name, and nothing in the repository proves that no live copy exists anywhere.

The master key, unwrapped from gocryptfs.conf, feeds HKDF-SHA256 with a zero salt, which derives the content key and the EME filename key. The content key is live behind CryptoCore.AEADCipher as a cipher.AEAD, and the EME key is live behind EMECipher as a cipher.Block, both as 240-byte AES-256 schedules. A dashed line leads from the master key to a freed box: stale master-key copies in 128-byte noscan slots, span class 21, key at offset 32, with the note that the digest-buffer identification is inferred. The itab route box points to the two live derived keys and is crossed out towards the freed master-key copies. The reduce route box (go_heap or positional search-reduce, then brute force with the gocryptfs-gcm oracle with candidate_is master) points to the freed copies.

The gocryptfs keys and which route finds which: the itab route reaches the two live derived keys, and the reduce route reaches the master key’s freed copies.

The plugin (vol3plugins/memdiver/gocryptfs.py, engine gocryptfs_engine.py, locator go_itab.py). It is stdlib-only and runs inside vol on an .msl slice or a Linux image with an ISF. It is a separate, symbol-free port of the heap layer’s moduledata and name logic, with its own rules:

1 pcHeader: magic 0xfffffff1 (Go 1.20+) or 0xfffffff0 (Go 1.18/1.19), 8-aligned, read-only memory
2 firstmoduledata: aligned writable word == pcHeader VA; accept if section bounds are ordered,
  types < etypes, typelinks/itablinks slices are sane, and a sample of itabs has inter and
  _type inside [types, etypes)          # itab sampling, NOT the heap layer's GC-mask check
3 type names: Str -> abi.Name; tflag & 2 strips "*"
4 wanted static itabs (from itablinks):
     cipher.AEAD  + concrete contains "xchacha20poly1305" -> content key (xchacha)
     cipher.AEAD  + concrete contains "gcm"               -> content key (aes-gcm)
     cipher.Block + concrete names "aes"                  -> EME filename key
5 interface values: every 8-aligned WRITABLE word equal to a wanted itab whose next word
  (data) is a readable pointer          # raw word scan, no liveness or heap typing
6 key: xchacha -> the 32 bytes at data; AES -> a 240-byte AES-256 schedule searched exactly at
  the targets of the object's first 8 pointer words, then in a 512-byte window at data, then in
  256-byte windows at those targets and one level deeper (POINTER_DEPTH = 2);
  an XOR-recurrence prefilter, then an exact re-expansion of all 240 bytes (4 encodings)
7 dedupe by key; prove every key against every --vault

The verdicts oracle:gocryptfs-eme-names (the vault root’s names decrypt under EME with enough evidence) and oracle:gocryptfs-content (block 0 of a content file opens) are verdict labels of the plugin, not oracles in MemDiver’s oracle registry. The registered oracle kind is gocryptfs-gcm (oracles/formats/gocryptfs_gcm.py). Its candidate_is is master (default: HKDF, then open block 0), content, eme or derived. The plugin has no master-key path: only the two derived keys are live behind interfaces. The master key comes from the reduce route, which is go_heap or positional search-reduce followed by brute force with a master-key oracle.

heap metadata reader

vol3 go_itab locator

Go versions

≥ 1.20 (typing ≥ 1.22)

≥ 1.18 (both pcHeader magics)

moduledata validation

GC-mask bit counts = section words

ordered bounds + sampled itabs inside [types, etypes)

finds interface values

in live, typed heap slots (GoSemantics.interface_values)

raw scan of writable words for wanted itab addresses

needs a parsed Go heap

yes

no

The library twin of the plugin is go_semantics_in_context(ctx).interface_values("cipher.AEAD", "*aes.gcmAsm"). See the plugin’s usage for options and output.

5. Building the reduced heap consensus matrix

build_goheap_consensus (engine/goheap_block_consensus.py) builds the consensus. search_reduce_go_heap (app/goheap_reduce.py) turns it into candidates.

5.1 Per-dump scan

For each dump:

open the source (a LOCKED encrypted dump is refused before any slot is read)
heap = go_heap_in_context(ctx)                # the cached parse of section 3
if no spans: diagnostic "no validated Go heap span"; contribute nothing
semantics = go_semantics_in_context(ctx)      # optional; typed only if the walk ran
for every NON-MANUAL span, every slot:
    state unknown           -> unknown_slots++, left out
    bytes not all captured  -> uncaptured_slots++, left out (never paired on partial bytes)
    slot = (va, user bytes, state live|freed, reachable, anchor (if reachable), type_name)

The user extent skips the 8-byte malloc header where one exists, and a large span’s object ends at limit. Live and freed slots both enter. Only the slots of parsed spans are paired. Span-less page runs (FREE_DATA) are not slots and do not take part in go_heap. They matter for a positional run’s user_data heap policy. If any dump has no validated Go heap, the consensus is empty and the producer refuses with goheap.wrong_allocator.

5.2 Step 1: span pairing (primary)

pair_go_spans (engine/go_span_pairing.py) works on whole spans.

Signature. For each non-manual span, in slot order:

pattern = []
for slot in span:
    not allocated   -> "-"
    live, unreadable -> "?"
    live, readable   -> "|".join(word shape per 8-byte word):
                         "0" zero word, "1" other word,
                         "mod:<module-relative key>" for a pointer into a file-backed mapping
content += live bytes with every word that points into any mapping zeroed
signature = blake2b-6( f"{spanclass}/{npages}/" + "/".join(pattern) )

Freed-slot bytes never enter the signature or the content key, only the - token. Pointers into modules compare module-relative, so ASLR does not change the signature.

Cascade.

  1. Signature pairs: signatures that occur exactly once in every dump pair their spans.

  2. Content pairs: a signature present in every dump but repeated somewhere is split by the pointer-masked live content. Content keys that are unique everywhere pair, and the rest is counted as ambiguous_spans_skipped.

  3. Shift pairs: the remaining spans are grouped by geometry (spanclass, npages, object_count, object_size). A span whose slots moved by a few positions (allocation order differs slightly between runs) is compared with every candidate at every shift s ∈ [−4, 4] (DEFAULT_SHIFT_WINDOW). Slot t of A is compared with slot t+s of B:

    score = (#both live − #known and different states)
          + (#equal module keys − #unequal module keys)
          + #equal non-zero pointer-masked words          # free slots' words included
    

    An edge needs the forward and backward best to agree on the target and the shift, score ≥ MIN_SHIFT_SCORE = 8, and a lead of ≥ MIN_SHIFT_MARGIN = 4 over the runner-up. Ties are never accepted. With more than two dumps the shifts must be consistent pairwise. Offsets are normalised so the smallest is 0, and the row path carries @shift=o0,o1,.... (A pointer-evidence gate can veto a shift pair, but it needs pointer-propagated objects. go_heap passes none, so the gate never fires here. It does in the positional object-pairing extension that also calls pair_go_spans.)

Rows. Every slot row of a paired span becomes one row, go:span:<path>, free slots included. For a shift pair, row p takes slot p + offset[d] of dump d.

5.3 Step 2: anchor labels (secondary)

Only over slots that step 1 left unclaimed:

  1. Among unclaimed slots with an anchor, the (anchor, size) keys that are unique in every dump form label tuples.

  2. Tuples whose spans are all unclaimed and share one geometry vote for (span starts, normalised slot shifts). The most-voted combination wins first, and each span is used once. Every slot row of those spans is paired: go:anchor_span:<hash>#p, freed slots included. One live label therefore pulls its freed neighbours in.

  3. Tuples whose slots are still unclaimed become single-slot rows, go:anchor:<hash>:s<size>.

A row is refused if any dump’s slot is unreadable or already claimed. The order of precedence is span > anchor_span > anchor > block. A label never overrides span pairing: a slot or span that step 1 paired in any dump is not a candidate, so a disagreeing label loses. (The user guide reports that letting labels win conflicts lost the gocryptfs master key at N = 20.) Without readable metadata this step pairs nothing, and the run reports goheap.untyped.

5.4 Step 3: block fallback

Every slot that is still unclaimed becomes a block with signature go:sc<spanclass>:s<size> and goes through the shared engine’s align_and_assemble(..., content_alignment=True). Signature-unique blocks pair, and then pointer-masked content separates content_invariant, dynamic_residue and dynamic candidates. See Block consensus engine.

5.5 The matrix: per-byte variance rows

There is no single matrix object. The consensus is a list of rows (GoSlotRow). Row r has one slot per dump (user_vas[d]) and length = min slot size. Each row is conceptually an N × length byte matrix:

B_r[d, i] = byte i of dump d's slot           d = 0..N-1, i = 0..length-1
var_r[i]  = population variance over d of B_r[d, i]     (float32)

Rows from steps 1 and 2 store mean_variance = mean_i var_r[i] with content_class = "signature_unique". Fallback rows reuse the block engine’s variance vector. The full “reduced heap consensus matrix” is the stack of these rows, Σ_r length_r columns by N dumps. It is reduced because only the slots of parsed spans, paired one-to-one, take part.

Verdicts come from the shared rule (engine/heap_block_verdicts.py). Every slot of the reference gets one:

verdict

kept?

paired row, mean_variance > 0 → signature_unique

yes

paired row, mean_variance == 0 → signature_unique_invariant

no

dynamic_residue

yes

content_invariant

no

unpaired, masked content found only in this dump → dynamic_candidate

yes

signature missing from some dump → missing

not judged

repeated content → content_shared; no bytes → empty

no

5.6 The in-slot reduce

The Scudo and Windows methods emit a kept block whole. go_heap does not. Span pairing is a true slot correspondence, so each kept slot carries a per-byte variance, and the positional reduce gates can run inside the slots (reduce_kept_slots):

kept = reference verdicts with kept == True, sorted by VA
slab = 64 zero bytes; for each kept slot: its bytes padded to a multiple of 16, then 64 zero bytes
var  = per-byte row variance at each slot's bytes (0 in the separators)
       an unpaired dynamic candidate gets UNPAIRED_VARIANCE = 1e6 per byte:
       it has no cross-dump variance, so the variance gate must not judge it
       (entropy, density and minimum-region gates still do)
regions = reduce_search_space(var, slab, N, order="rank", heap_policy="off")
          # N-scaled defaults: floor default_floor_for_n(N) (0 for N <= 5, 500 at 10,
          # 1500 at 20, 2000 at 30-40, 2500 from 50, linear between);
          # entropy window 32 bytes / 4.5 bits; block-density gate (32-byte blocks,
          # step 8, density 0.5); minimum region 16 bytes
for each region: clip it to every slot it overlaps -> KeptSlice(sub-range, score, tier,
                 pairing, slot_va, slot_state, reachable, type_name)
sort by (tier, -score, VA)     # tier 0 reachable live, 1 other live, 2 freed

The separators keep a region from spanning two slots, and a region that starts in a separator is clipped. With fewer than three dumps, the reduce skips its variance and density gates. The gates are not tunable for this method.

Reachability ranks, it never filters. A freed slot is tier 2 and lists after every live slot, but it is never dropped. The gocryptfs master key is found precisely because of this rule.

5.7 Translation to the reference and output

Every slice is checked against the bytes the consensus judged (heap_block_reduce.translate_regions) and written in the reference’s flat vas view. This is the file brute-force --candidates ... --dump <reference> reads unchanged. A reference with a short captured run is not refused (every gocryptfs capture has one, a partial page past the Go heap). A region that reaches that run is left out and counted as skipped.behind_truncated_run, because brute force’s flat read drifts from there on.

candidates.json carries source = "search-reduce:goheap", method = "go_heap", consensus.method = "goheap_slot_pairing", the pairing report go_heap (span pairing counts, anchor pairing counts, rows by pairing, skipped rows), reduce (slots, slot bytes, floor, stage counts), funnel, not_judged, skipped, totals, diagnostics, and the regions in rank order. Each region has rank, score, pairing, slot_va, slot_state, reachable and, when known, type_name.

6. Worked example (synthetic, from the tests)

The synthetic fixture of tests/test_go_span_pairing.py and tests/test_goheap_block_consensus.py uses the following values:

  • N = 3 processes. Process i has its arena at 0xc000000000 + i·0x100000 and its module at 0x5550_0000_0000 + i·0x10_0000_0000, so nothing co-locates.

  • One-page spans of span class 21 (10 << 1 | 1): 128-byte noscan slots, nelems = 8192 / 128 = 64.

  • A per-run 32-byte key at slot 4, offset 32. Slot 4 is freed in every process.

The steps:

  1. Each process parses to the same span: class 21, 1 page, the same live/free pattern, and the same word shapes in the live slots. The signature is identical and unique in each dump, so the span pairs at step 1.

  2. All 64 slot rows of that span become span rows, freed slots included, and 0 rows go to the block fallback (rows.span == 64, rows.block == 0).

  3. Slot 4’s row is a 3 × 128 matrix. Its variance is 0 at bytes 0–31 and 64–127 and > 0 at every byte 32–63, exactly as the test asserts.

  4. Verdicts: the key row has mean_variance > 0 and is kept. Rows with zero variance are signature_unique_invariant and dropped.

  5. Reduce: the floor for N = 3 is 0, so the variance gate (var ≥ floor) passes every byte, and the entropy gate does the cutting. The 32 key bytes pass it (the test key has 32 distinct bytes) and the 16-byte minimum, and most of the constant rest of the slot does not. The region covering slot + 32 comes out as one KeptSlice with (pairing, slot_state, tier) == ("span", "freed", 2). Running the fixture gives slot bytes 26–69 (44 bytes: the key plus 6 constant bytes on each side that the 32-byte entropy window takes in). The test pins only that no slice of the slot starts before slot + 16.

  6. For two kept slots of 48 and 32 bytes, the slab is 64 + 48 + 64 + 32 + 64 = 272 bytes, as the test pins.

With metadata (tests/test_heap_golang_metadata.py, a go1.22.2 fixture): a global holds an interface value (cipher.AEAD itab, data) whose data points at a main.gcm slot. Its field ks points at a [32]uint8 slot, which therefore gets type_name == "[32]uint8", anchor == "main.gcm->ks", reachable is True and pointer_offsets == []. Three runs of that fixture through go_heap (tests/test_goheap_reduce.py) put the key region of the reachable live slot first (rank == 1, pairing == "span"). The anchor step is tested separately, with labels set by hand on the span-pairing fixture (tests/test_goheap_block_consensus.py): four labels unique in every dump give {"label_pairs": 4, "anchor_spans": 1}.

7. Using it

go_heap reads native .msl dumps (the parser needs their region table and VAS map). The first dump is the reference in a pipeline run.

CLI, pipeline run.

memdiver pipeline run run_*/memslicer.msl --output-dir out --oracle oracle.py --method go_heap
memdiver pipeline suggest-method run_*/memslicer.msl     # what --method auto would pick, and why

CLI, collect session (the reduction alone):

memdiver consensus-begin --state go.json --allocator go_heap
for d in run_*/memslicer.msl; do memdiver consensus-add --state go.json "$d"; done
memdiver search-reduce --state go.json --reference-dump run_0/memslicer.msl -o cand.json

--size together with --allocator go_heap is refused, and brute-force --state on a go_heap session is refused (goheap.plugin_unsupported).

MCP. search_reduce_go_heap(dump_paths, reference_path, output_dir, key_sizes=None (→ 32), key_file, passphrase, kem_key_file, allocator="auto"|"golang", mixed_ok=False, force_memory=None), plus pipeline_run(method="go_heap") and suggest_pipeline_method.

REST. POST /api/pipeline/run with method: "go_heap" and/or go_heap: {"allocator": "auto" | "golang"} (GoHeapParams). The response reports method_effective, method_source and method_reason. POST /api/pipeline/method-suggestion previews the choice. The reducer has no standalone REST endpoint. The web UI offers the method in its method selector.

Library. services exposes the pipeline.search_reduce_go_heap capability (memdiver.app.goheap_reduce.search_reduce_go_heap).

Automatic choice (app/pipeline_method.py). An explicit method always wins. Any positional-only option (N-sweep, explicit escalation, region filter, reduce knobs including heap_policy, plugin) makes auto resolve to positional. Otherwise, with at least two dumps that are native .msl, the reference is fully parsed (about 0.5 s per gocryptfs dump, which is why only the reference is). The result is go_heap only if the reference has validated spans and readable module data, and every other dump is an .msl of the same OS with an anonymous mapping at a Go arena hint. Otherwise a reference with validated spans gives positional; one without them goes on to the scudo check (Choosing a method). A Go reference without readable metadata stays positional (“has a Go heap but its runtime metadata (module data) could not be read”). An explicit --method go_heap still runs on such dumps, untyped (goheap.untyped).

Refusals and diagnostics.

code

when

goheap.wrong_allocator

a dump has no validated Go heap span, or allocator is not auto/golang

goheap.unsupported_option

an N-sweep, escalation, region filter or reduce knob was given

goheap.plugin_unsupported

a Volatility 3 plugin was explicitly requested (the plugin needs variance along the reference’s address space); emit=false / --no-emit is accepted and does not force positional

goheap.too_few_dumps, dump_not_found, duplicate_dumps, not_msl, reference_not_in_dumps, invalid_key_sizes

the shared heap-block input checks

goheap.untyped (info)

no metadata: no anchors, no reachable tier

goheap.uncaptured_slots, goheap.not_judged, goheap.candidates_skipped, goheap.candidates_empty

what was left out and why

The golang allocator in positional runs. Independently of go_heap, the Go parser is a regular allocator (golang). It is reduce_ready and user_data_ready, and it is part of the user_data heap policy: live and unknown slots keep their user extent as USER_DATA, freed slots and provably free span-less pages become FREE_DATA (kept, flagged freed), and unproven span-less pages stay USER_DATA. A positional run over Go dumps can therefore pick user_data automatically. go_heap itself always runs its reduce with heap_policy="off", because every byte in its slab is already a slot’s user byte. See the Go runtime heap section of the user guide.

Volatility 3. memdiver.gocryptfs.GocryptfsKeys (the itab route, section 4.7) runs on an .msl slice or on a Linux image:

vol -p "$P" -f run_0001/memslicer.msl memdiver.gocryptfs.GocryptfsKeys --vault run_0001/cipher

Its validation check (in tests/test_vol3plugins_corpus_gate.py, run only when the corpus is present; see VALIDATION) is: on the public captures v2b and v2c, one run without --pid with all four daemons’ vaults gives exactly 8 proven rows, the EME key and the content key of each daemon, each proven by its own vault, byte-equal to the test’s own HKDF-SHA256 of the sidecar master key, with the same proven rows under vol 2.27.0 and 2.28.2.

8. Measured results and where each number comes from

The numbers come from two different gocryptfs corpora, which the sources do not always say:

  • the dataset runs (gocryptfs built with Go 1.22.1, amd64, non-PIE; N-run cohorts), measured once and reported in prose;

  • the public v2b/v2c captures (stripped go1.22.2 daemons), pinned by tests that need MEMDIVER_SECRETS_CORPUS.

Pinned by tests (re-run whenever the corpus is present):

fact

test

v2b/v2c daemons parse as go1.22.2 with the go1.22-1.25 profile; every ground-truth master-key address is in a free slot of size 128, span class 21, key at offset 32; in-use coverage ≥ 0.95; every pageInUse start matched

tests/test_heap_golang_corpus.py

gocryptfs daemons detect as golang; ssh sessions stay ptmalloc2 (golang score 0)

tests/test_heap_golang_corpus.py

positional + propagation + span pairing ranks the master-key copies 5 and 6 on v2b and 11 and 12 on v2c (spans pair only under a slot shift of 2), member-order independent

tests/test_go_span_pairing_corpus.py

GocryptfsKeys on v2b/v2c: 8 proven rows, same under vol 2.27.0 and 2.28.2 (section 7)

tests/test_vol3plugins_corpus_gate.py

Measured once, documented in prose only (no committed test or script re-runs them). This table is their only complete record (run times, ranks and the escalation figures appear nowhere else); the user guide and CHANGELOG.md quote only headline figures from it and link here.

result

corpus

go_heap through the pipeline (exhaustive brute force, gocryptfs vault oracle), N = 3, 5, 10, 20, references 0–4: the reference’s own master key verified in 18/18 runs, from 20–55 KB of candidates (N = 20: 19.7–46.7 KB), in 9–12 s (N ≤ 5), 21–23 s (N = 10), 44–47 s (N = 20); key rank 100–242 at N ≤ 5 and 19–27 at N ≥ 10 (freed slots rank behind the live tiers)

Go 1.22.1 dataset

positional on the same runs kept the key for only 3/5 references at N = 10 and at N = 20 (70–570 KB); the other two only through escalation (“floor was too high”, 69–101 s)

Go 1.22.1 dataset

letting anchor labels win conflicts lost the master key at N = 20

Go 1.22.1 dataset

the itab route on the library side (interface_values, not the vol3 plugin): module found in 20/20 dumps; 25 % of live slots named and 91 % reachable (90–96 % per dump); exactly one live hit per cipher per dump holding that dump’s derived key, 20/20, no false hits

20 Go 1.22.1 dumps

wireguard-go: module found in 140/140 dumps; 866 previously span-less key copies now in freed_span (806) / stale_entry (60) page runs

Go 1.25 arm64

The go_heap and positional figures are whole-method results (span pairing, anchors and fallback together). They are not a measurement of span pairing alone.

9. Limits and open issues

  • Go 1.26 randomised heap base. Go 1.26 randomises the heap base by default, so its arenas usually match no arena hint. probe_golang and has_go_arena_hint both require a hint mapping. Such a dump therefore scores 0 in allocator detection, and auto never routes the cohort to go_heap: the reference probe stops at the missing hint. The parser itself accepts unhinted 64 MiB-aligned arenas with at least two validated spans, so an explicit --method go_heap may still work, but no real Go 1.26 capture tests this.

  • Goroutine stacks are not roots. A key referenced only from a stack frame reads unreachable and drops to tier 1. This affects ranking, not recall.

  • Freed keys rank last. Tier 2 comes after every live slot. The measured ranks (100–242 at N ≤ 5) assume an exhaustive brute force over the candidates.

  • Span-less pages are not paired. FREE_DATA page runs carry stale payload, but go_heap pairs only slots of parsed spans. Such copies are reached by a positional run (where user_data keeps them), not by go_heap.

  • No tunables, no plugin, no escalation, no N-sweep. The variance lives in a slab of paired slots, not along the reference’s address space. build_goheap_consensus(shift_window=...) exists, but no surface sets it (default 4).

  • Unreadable state or bytes. Slots whose allocation state is unknown (missing allocBits byte) or whose bytes are not fully captured are left out and counted. They are never paired on partial bytes.

  • Version gates differ by component. The heap parser reads Go 1.18–1.26, the metadata reader needs ≥ 1.20, typing and reachability need ≥ 1.22, and the vol3 itab locator accepts ≥ 1.18. Only 64-bit amd64/arm64 runtimes are read.

  • The master-key type name is inferred. See section 4.7. The repository establishes the freed state, class, size and offset, not the type.

10. Source map

concern

code

tests

runtime facts, slot state, validation, buildinfo

heap/allocators/golang_runtime.py, golang_profiles.py, golang_layouts_data.py (generated by tools/go_runtime_layouts/)

tests/test_go_runtime_layouts.py

heap parse, span-table vote, detection, layout

heap/allocators/golang.py

tests/test_heap_golang.py, tests/test_heap_golang_corpus.py

span-less pages, mheap_.arenas recovery

heap/allocators/golang_pages.py

tests/test_heap_golang_pages.py

moduledata, types, itabs

heap/allocators/golang_moduledata.py, golang_meta_layouts.py

tests/test_heap_golang_metadata.py

slot typing, interface values

heap/allocators/golang_objects.py

tests/test_heap_golang_metadata.py

reachability, anchor labels

heap/allocators/golang_reach.py, golang_semantics.py

tests/test_heap_golang_metadata.py

span pairing, slot shift

engine/go_span_pairing.py, engine/go_span_shift.py

tests/test_go_span_pairing.py, tests/test_go_span_shift.py, tests/test_go_span_pairing_corpus.py

go_heap consensus, in-slot reduce, tiers

engine/goheap_block_consensus.py

tests/test_goheap_block_consensus.py

shared verdicts, block engine

engine/heap_block_verdicts.py, engine/heap_block_consensus.py

see Block consensus engine

producer, refusals, output

app/goheap_reduce.py

tests/test_goheap_reduce.py

automatic method choice

app/pipeline_method.py

tests/test_pipeline_method_auto.py

golang in heap policy / user_data

app/_pipeline_heap.py, heap/builtin.py

itab route (vol3)

vol3plugins/memdiver/go_itab.py, gocryptfs_engine.py, gocryptfs.py

tests/test_vol3plugins_go_itab.py, tests/test_vol3plugins_corpus_gate.py (v2b/v2c validation check)

gocryptfs oracle

oracles/formats/gocryptfs_gcm.py