# Reversing an obfuscated stack trace


You protect a desktop app with rename obfuscation, ship it, and a week later a customer's crash report lands in your inbox:

```
System.ArgumentOutOfRangeException: No tax rate configured (Parameter 'region')
   at A.n.a(String)
   at A.n.b(Decimal, String)
   at A.n.c(Invoice)
```

Three frames, zero information. You renamed every private symbol in your assembly precisely so this is what an attacker sees — but it is also what *you* see, and you have a bug to triage. The good news: the obfuscation that erased these names is reversible by you, because the renamer wrote down exactly what it did. This post is about that map, and the mechanical step from `A.n.a` back to `InvoiceService.RateFor`.

## What a stack trace actually contains

Start with the original, un-obfuscated class:

```csharp
namespace Acme.Billing;

public sealed class InvoiceService
{
    public decimal ComputeTotal(Invoice invoice) =>
        ApplyTax(invoice.Subtotal, invoice.Region);

    private decimal ApplyTax(decimal amount, string region) =>
        amount + amount * RateFor(region);

    private decimal RateFor(string region) => region switch
    {
        "EU" => 0.20m,
        "US" => 0.00m,
        _ => throw new ArgumentOutOfRangeException(
                 nameof(region), region, "No tax rate configured"),
    };
}
```

When `RateFor` throws, the CLR walks the call stack and records one entry per managed frame. A frame is not a string — it is a **method handle** (a metadata token into the assembly's method table) plus the IL offset where control was. `Exception.StackTrace` is produced lazily: `StackTrace.ToString()` resolves each handle back to a `MethodBase` and formats it. The method name, its declaring type, and its parameter types all come from **metadata** — the `#Strings` heap the compiler wrote into the assembly. The `in …:line 20` suffix comes from a *separate* source: the PDB's sequence points, which map an IL offset to a source file and line. No PDB loaded, no line numbers — but the names still resolve, because they live in the DLL, not the PDB.

So the un-obfuscated trace reads:

```
   at Acme.Billing.InvoiceService.RateFor(String region) in InvoiceService.cs:line 16
   at Acme.Billing.InvoiceService.ApplyTax(Decimal amount, String region) in InvoiceService.cs:line 9
   at Acme.Billing.InvoiceService.ComputeTotal(Invoice invoice) in InvoiceService.cs:line 6
```

## Why the names come back renamed

Rename obfuscation rewrites the `#Strings` heap. `InvoiceService` becomes `n`, its namespace collapses to `A`, and `RateFor`, `ApplyTax`, `ComputeTotal` become `a`, `b`, `c`. Parameter names are metadata too (the `Param` table), so `region` is dropped and only the type survives. The method *tokens* are unchanged — the call stack is identical at runtime — but when `ToString()` resolves a token to a name, the name it reads is now the short one. That is why the frame says `A.n.a(String)`: nothing is corrupted, the metadata simply says something different than it used to.

The framework types are untouched. `String`, `Decimal` and `ArgumentOutOfRangeException` still render under their real names, because you only renamed symbols *you* own. That detail matters for reversal: the framework parts of a signature are a fixed anchor.

## The map

Because Nebula performs the rename, it knows every before/after pair, and it writes them to a **renaming map** at obfuscation time — one record per renamed type and member. The format is illustrative, but the shape is what counts: each type line gives the original fully-qualified name and its obfuscated name; each member line underneath gives the **original signature** — return type, name, and the full ordered parameter type list — and the obfuscated short name it received.

```
Acme.Billing.InvoiceService -> A.n:
    System.Decimal ComputeTotal(Acme.Billing.Invoice) -> c
    System.Decimal ApplyTax(System.Decimal,System.String) -> b
    System.Decimal RateFor(System.String) -> a
    System.Decimal RateFor(System.String,System.Boolean) -> a
```

Look at the last two lines. Two different methods — `RateFor(string)` and an overload `RateFor(string, bool)` — both renamed to `a`. That is legal: a .NET method table row is unique by name *and* signature, so two `a` methods coexist happily as long as their parameter lists differ. A map keyed only by short name would collide here. The signature is what keeps them apart, which is why the map stores it in full and why reversal has to match on it.

<figure class="my-8">
<svg viewBox="0 0 760 300" aria-label="Pipeline reversing an obfuscated frame: the frame is parsed into type, method and argument types, matched against the renaming map by obfuscated name plus signature, and rewritten as the original frame" xmlns="http://www.w3.org/2000/svg" role="img">
<rect x="16" y="40" width="200" height="90" rx="8" fill="#eef2ff" stroke="#6366f1"/>
<text x="116" y="66" text-anchor="middle" fill="#6366f1" font-size="13" font-weight="bold">Obfuscated frame</text>
<text x="116" y="92" text-anchor="middle" fill="#0891b2" font-size="13" font-family="monospace">at A.n.a(String)</text>
<text x="116" y="114" text-anchor="middle" fill="#64748b" font-size="11">type A.n · method a · (String)</text>
<rect x="280" y="24" width="200" height="122" rx="8" fill="#1e293b" stroke="#0891b2"/>
<text x="380" y="48" text-anchor="middle" fill="#ffffff" font-size="13" font-weight="bold">Renaming map</text>
<text x="380" y="72" text-anchor="middle" fill="#ffffff" font-size="11">key = obf type + obf name</text>
<text x="380" y="90" text-anchor="middle" fill="#ffffff" font-size="11">+ signature (arity, types)</text>
<text x="380" y="118" text-anchor="middle" fill="#10b981" font-size="11" font-family="monospace">a(String) → RateFor</text>
<text x="380" y="134" text-anchor="middle" fill="#64748b" font-size="11">a(String,Boolean) → other</text>
<rect x="544" y="40" width="200" height="90" rx="8" fill="#ecfdf5" stroke="#10b981"/>
<text x="644" y="66" text-anchor="middle" fill="#10b981" font-size="13" font-weight="bold">Original frame</text>
<text x="644" y="92" text-anchor="middle" fill="#0891b2" font-size="12" font-family="monospace">InvoiceService</text>
<text x="644" y="110" text-anchor="middle" fill="#0891b2" font-size="12" font-family="monospace">.RateFor(String)</text>
<line x1="216" y1="85" x2="278" y2="85" stroke="#6366f1" stroke-width="2" marker-end="url(#ar)"/>
<line x1="482" y1="85" x2="542" y2="85" stroke="#10b981" stroke-width="2" marker-end="url(#ar)"/>
<text x="247" y="78" text-anchor="middle" fill="#64748b" font-size="10">look up</text>
<text x="512" y="78" text-anchor="middle" fill="#64748b" font-size="10">rewrite</text>
<text x="380" y="180" text-anchor="middle" fill="#64748b" font-size="11">Framework types (String, Decimal) are unrenamed — the fixed anchor that disambiguates overloads.</text>
<defs><marker id="ar" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 Z" fill="#64748b"/></marker></defs>
</svg>
<figcaption class="text-sm text-muted mt-2">Each obfuscated frame is parsed, matched against the map by obfuscated type, name and signature, and rewritten with the original name — the inverse of the rename the obfuscator recorded.</figcaption>
</figure>

## Reversing a frame

Reversal is the inverse lookup: parse each frame into *(obfuscated type, obfuscated method, argument types)*, find the matching record, and substitute the original name. The only subtlety is the one the map anticipated — when a short name is ambiguous, disambiguate by signature.

```csharp
using System.Text;
using System.Text.RegularExpressions;

public sealed class Retracer
{
    private readonly record struct Member(string OriginalName, string[] ParamTypes);

    // obfuscated type -> original type
    private readonly Dictionary<string, string> _types = new();
    // (obfuscated type, obfuscated method) -> original candidates
    private readonly Dictionary<(string Type, string Method), List<Member>> _members = new();

    private static readonly Regex TypeLine =
        new(@"^(?<orig>\S+) -> (?<obf>[^\s:]+):$");
    private static readonly Regex MemberLine =
        new(@"^\s+\S+ (?<name>[^\s(]+)\((?<args>[^)]*)\) -> (?<obf>\S+)$");
    private static readonly Regex Frame =
        new(@"^(?<lead>\s*at )(?<type>[\w.`<>]+)\.(?<method>[\w`<>]+)\((?<args>[^)]*)\)(?<tail>.*)$");

    public void LoadMap(IEnumerable<string> lines)
    {
        string? obfType = null;
        foreach (var line in lines)
        {
            var t = TypeLine.Match(line);
            if (t.Success) { obfType = t.Groups["obf"].Value; _types[obfType] = t.Groups["orig"].Value; continue; }

            var m = MemberLine.Match(line);
            if (!m.Success || obfType is null) continue;
            var ps = m.Groups["args"].Value;
            var types = ps.Length == 0 ? Array.Empty<string>() : ps.Split(',');
            var key = (obfType, m.Groups["obf"].Value);
            (_members.TryGetValue(key, out var list) ? list : _members[key] = new())
                .Add(new Member(m.Groups["name"].Value, types));
        }
    }

    public string Reverse(string stackTrace)
    {
        var sb = new StringBuilder();
        foreach (var raw in stackTrace.Split('\n'))
            sb.AppendLine(ReverseFrame(raw.TrimEnd('\r')));
        return sb.ToString();
    }

    private string ReverseFrame(string line)
    {
        var f = Frame.Match(line);
        if (!f.Success) return line;                               // not a frame
        var obfType = f.Groups["type"].Value;
        if (!_types.TryGetValue(obfType, out var origType)) return line;   // a framework frame
        if (!_members.TryGetValue((obfType, f.Groups["method"].Value), out var cands)) return line;

        var arity = f.Groups["args"].Value.Length == 0 ? 0 : f.Groups["args"].Value.Split(',').Length;
        var hit = cands.Count == 1 ? cands[0]
                : cands.FirstOrDefault(c => c.ParamTypes.Length == arity);
        if (hit.OriginalName is null) return line;                 // ambiguous beyond arity

        var sig = string.Join(", ", hit.ParamTypes.Select(ShortName));
        return $"{f.Groups["lead"].Value}{origType}.{hit.OriginalName}({sig}){f.Groups["tail"].Value}";
    }

    private static string ShortName(string fq)
    {
        var dot = fq.LastIndexOf('.');
        return dot < 0 ? fq : fq[(dot + 1)..];
    }
}
```

Feed the three obfuscated frames through `Reverse` with the map loaded, and `A.n.a(String)` becomes `Acme.Billing.InvoiceService.RateFor(String)` — the original call chain, restored from a trace you could not otherwise read.

Two representation details the regex has to tolerate. **Overloads** are handled above by arity, and the map keeps the full parameter list for the rarer case where two overloads share a name *and* arity — then you match type-by-type (mapping each original app type forward through `_types` so it lines up with the renamed type the frame shows). **Generics** carry their arity as a backtick suffix in metadata: a generic method renders as `` a`1 `` and a generic type as `` n`2 ``, with the type arguments shown in brackets like `a[System.Int32]`. The map records the same backtick arity, so the keys line up as long as the parser does not strip the `` ` ``.

## When it breaks

Retracing is only as complete as the frames the runtime recorded, and several things remove frames *before* the map ever sees them:

- **Inlining.** The JIT inlines small methods, and an inlined method has no frame of its own — its body executes inside the caller. `[MethodImpl(MethodImplOptions.AggressiveInlining)]` forces this. The map can still name every frame present; it cannot conjure a frame the JIT folded away. A Release build inlines far more aggressively than Debug, so the same bug can produce a shorter trace in production.
- **Tail calls and other optimizations.** A tail-call-optimized frame is replaced, not stacked, so the caller can be missing. Release codegen also reorders and elides, which is why a production trace sometimes skips a method you *know* was on the path.
- **Async and iterators.** An `async` method's body is compiled into a state machine, and the frame you see is `MoveNext` on a compiler-generated display class such as `<SendAsync>d__4`. Obfuscation renames that display class too, so a raw async frame reads `A.q.MoveNext()`. Reversing it needs the display-class mapping — the record that ties the renamed state-machine type back to the `SendAsync` method it was generated for — not just the method map. A good map emits those entries; without them, `MoveNext` is a dead end.
- **No PDB.** The map restores *names*; it cannot restore *line numbers*, because those never lived in the DLL. If the trace arrived without `:line N`, retracing gives you `InvoiceService.RateFor(String)` with no line — still a world better than `A.n.a`, but ship symbols you can match against the build if you want lines back.

None of these are failures of the map. They are facts about what a stack trace is: a record of the frames that physically existed at throw time, named from metadata. The map faithfully inverts the renaming; it cannot invent information the runtime discarded.

## Takeaway

Rename obfuscation is reversible *for the party that performed it* because the renamer is a function with a recorded inverse — the renaming map, keyed by original name and full signature so overloads never collide. Keep the map Nebula emits for each release, archived next to that build's symbols, and an incoming `at A.n.a(String)` is a mechanical lookup away from `InvoiceService.RateFor`. Nebula's retrace tooling is this lookup, automated and overload-aware, so you ship an assembly an attacker cannot read while keeping crash reports you can. See the [Nebula.NET](https://delta1labs.com/products/nebula) overview, or the [retrace guide](https://delta1labs.com/docs/nebula/) for the Pro workflow.

