Skip to content
← All posts
· Delta1 Labs MetadataNebula

Metadata heap compaction and token renumbering: shrinking a .NET assembly after obfuscation

Renaming leaves dead strings and blobs behind in the #Strings and #Blob heaps. How Nebula compacts the metadata heaps and renumbers tokens — with real metadata layout, IL, config, and before/after measurements.

Rename a few thousand members and you have shortened every identifier in your assembly — CalculateInvoiceTotal became a, _pendingReconciliationQueue became b. You would expect the file to shrink. Open the two builds in a hex viewer and it often has not: the original long names are still sitting there in the #Strings heap, orphaned but never removed. Obfuscation changed which strings the metadata tables point at; it did not reclaim the strings they used to point at.

This post is about the pass that finishes the job — metadata heap compaction and token renumbering. It is the least glamorous transform Nebula runs and, on a large assembly, one of the most measurable: it is the difference between a rename that only hides names and one that also deletes them.

Where the names actually live

A .NET assembly’s metadata is a set of tables (TypeDef, MethodDef, Field, …) plus four heaps the tables index into:

  • #Strings — null-terminated UTF-8 identifier names: type names, method names, field names, namespaces.
  • #US — the user-string heap, holding the UTF-16 string literals your code loads with ldstr.
  • #Blob — signatures, custom-attribute arguments, constant values, marshalling descriptors.
  • #GUID — module version IDs and friends.

A row in MethodDef does not store its name; it stores a #Strings offset. The name "CalculateInvoiceTotal" lives once in the heap and every token that needs it carries the integer offset where it begins.

Renaming repoints a metadata offset and orphans the old stringMethodDef rowRVA | ImplFlags |Name → offset 0x1A40#Strings heap0x1A40 "CalculateInvoiceTotal\0" (orphan)0x2F10 "a\0" (appended)beforeafter rename:Name → 0x2F10Name → offset 0x2F10after compaction0x0004 "a\0" — orphan removed, heap rebuilt, token renumbered

Renaming rewrites the Name field to a new offset. The naive way to get that offset is to append "a\0" to the end of #Strings and point there. Fast, correct — and it never touches the old bytes. After a full rename pass the heap holds every original identifier plus every short replacement. The file can even grow.

What compaction does

Compaction treats the heaps as a garbage-collected arena. The steps:

  1. Mark. Walk every table column that is a heap reference — TypeDef.Name, TypeDef.Namespace, MethodDef.Name, Field.Signature, every ldstr into #US, every custom-attribute #Blob — and record which offsets are actually reachable.
  2. Sweep and rebuild. Allocate fresh heaps containing only the reachable entries, de-duplicated so two identical signatures share one blob.
  3. Renumber. Every heap offset in every table is rewritten to its new position. Tokens into the tables themselves are re-packed too, because empty TypeRef/MemberRef rows left by merged or removed references can be dropped.

Step 3 is why this cannot be a peephole fix. A metadata token like 0x06000012 (a MethodDef, row 0x12) is referenced from IL (call 0x06000012), from other tables, and from the #Blob signatures. Renumber one table and you must fix every call, ldtoken, newobj and ldstr that crosses it. Nebula does this as a single coherent remap: it builds an old-token → new-token map, rewrites the tables, then rewrites every method body’s IL operands against the same map.

// IL before — operand is a raw metadata token
IL_000a:  ldstr      0x70000A1C      // "CalculateInvoiceTotal failed for order "
IL_000f:  call       0x0A000037      // MemberRef into a #Blob signature

// IL after compaction — same instructions, renumbered operands
IL_000a:  ldstr      0x70000044
IL_000f:  call       0x0A00000B

The instructions are byte-for-byte identical in shape; only the operands move. Get the remap wrong by one row and the assembly throws BadImageFormatException at load, which is exactly why you do not hand-roll this and why Nebula verifies the rebuilt image before writing it.

It is also a hardening pass, not only a size pass

Compaction is usually sold as size, but the security angle is the orphaned #Strings bytes themselves. A rename that only repoints offsets leaves CalculateInvoiceTotal, _pendingReconciliationQueue and every other original name physically present in the file. They no longer resolve through metadata — a decompiler shows a, b, c — but a trivial strings-style scan over the raw bytes recovers your entire original vocabulary:

$ strings Acme.Billing.dll | grep -i invoice
CalculateInvoiceTotal
InvoiceReconciliationService
_pendingInvoiceBatch

That is a real leak. Your method names often describe your domain as clearly as the code does. Compaction deletes the orphans, so the scan comes back empty and the only names in the file are the meaningless short ones the rename produced. The same applies to #US: literals you encrypted and replaced still linger in the user-string heap until the heap is rebuilt.

Turning it on

Compaction runs after rename, string encryption and resource processing, because it must see the final set of live references. In nebula.config.json it is a stage under the output, on by default when you rename but configurable:

{
  "schemaVersion": 1,
  "inputs": [ "bin/Release/net8.0/Acme.Billing.dll" ],
  "outputDirectory": "protected",

  "rename": { "enabled": true },
  "stringEncryption": { "enabled": true },

  "metadata": {
    "compactHeaps": true,
    "dedupeBlobs": true,
    "removeOrphanStrings": true,
    "renumberTokens": true
  }
}

Then the usual invocation:

nebula protect --config nebula.config.json --out protected

The one setting worth understanding is renumberTokens. Leaving tokens as they were (only rebuilding heaps) is the conservative choice if something downstream pins a specific token — for example a tool that reads your assembly by hard-coded MethodDef row. That is rare. Keep it true unless you have a concrete reason, because renumbering is what lets empty table rows be dropped.

When to hold back

Compaction is safe for ordinary assemblies, but two cases deserve a metadata.preserve list. First, an assembly loaded by mdToken across a boundary — some profiling or instrumentation hosts cache tokens. Second, anything doing Module.ResolveMethod(int metadataToken) on itself with a literal token baked in source. Both are unusual; when they apply, pin the affected members:

"metadata": {
  "compactHeaps": true,
  "renumberTokens": true,
  "preserve": [ "Acme.Billing.Diagnostics.TokenProbe.*" ]
}

Named members keep their original tokens; everything else is renumbered and compacted around them.

What it actually saves

Numbers depend entirely on how name-heavy your assembly was, which is to say how much renaming removed. A representative result on a mid-size business assembly — ~4,200 methods, heavy domain vocabulary, strings encrypted — looks like this:

                           #Strings     #US      #Blob     File
rename only (no compaction)  412 KB   188 KB    96 KB    1.84 MB
+ heap compaction             34 KB     2 KB    71 KB    1.27 MB
                             ───────   ──────   ──────   ───────
                              -92%      -99%     -26%     -31%

The #Strings collapse is the orphaned original identifiers going away. The #US collapse is the pre-encryption literals going away. #Blob shrinks less and only from de-duplication, because signatures were all live. A 31% file reduction is typical for a rename-heavy assembly; a small utility with few members will see almost nothing, because there were few orphans to collect.

Startup moves too, though less than size suggests. The runtime memory-maps metadata and reads it lazily, so a smaller #Strings heap mostly helps cold start and working set rather than steady-state throughput. Treat the size win as the headline and the startup win as a bonus — and, as always, measure your own assembly rather than trusting a table.

Verify it worked

Two checks, both quick. First, confirm the orphans are gone with the same scan that exposed them:

$ strings protected/Acme.Billing.dll | grep -i invoice
$    # (no output — the original names are no longer in the file)

Second, open the protected assembly in Glass.NET and look at the metadata view: the #Strings heap should contain only short rename output and framework names, the #US heap should be near-empty if you encrypted strings, and token navigation should resolve cleanly — a renumbering bug shows up immediately as a broken reference. Glass reads the heaps directly, so it is the honest way to confirm compaction did what the config asked without shipping first.

The short version

Renaming changes what metadata points at; compaction reclaims what it used to point at. Skip it and you ship an assembly whose original names are hidden from a decompiler but trivially recoverable with strings, carrying hundreds of kilobytes of dead heap. Run it and the orphans are deleted, blobs de-duplicated, tokens re-packed, and the file is both smaller and genuinely scrubbed of the vocabulary you meant to hide. It is on by default when you rename for exactly that reason — leave it on, pin the rare self-referential token, and verify in Glass before you ship.

See Nebula.NET for the full transform pipeline and the nebula.config.json reference, and metadata tables explained for the structures compaction operates on.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.