Skip to content
← All posts
· Delta1 Labs Nebula.NETObfuscation

Turning a method into one big switch

How control-flow flattening rewrites a method's basic-block graph into a single while(true) dispatch loop driven by a state variable — shown with real C#, the dispatcher IL, why it defeats a naive decompiler, and the honest performance cost.

An analyst opens your decompiled method and sees exactly what you wrote: a loop, an if inside it, an early return. The shape of the logic is right there, because branches and loops survive compilation almost perfectly — that shape is most of what makes decompiled code readable. Now imagine they open the same method and see no loop at all. Just a while (true) wrapped around a switch on some integer, with six numbered cases that each end by setting that integer to a different value. The loop is still in there. It is just no longer visible.

That transformation is control-flow flattening, and it is the most direct attack on the one thing renaming and string encryption leave intact: the structure.

What a decompiler reads for free

Here is a small method with everything an analyst likes — a loop and a branch:

int SumEven(int[] xs)
{
    int sum = 0;
    for (int i = 0; i < xs.Length; i++)
    {
        if ((xs[i] & 1) == 0)
            sum += xs[i];
    }
    return sum;
}

The compiler turns this into a handful of basic blocks — straight-line runs of IL with a single entry and a single exit — connected by branch edges. The control-flow graph is small and honest:

  • B0 entry: sum = 0; i = 0; then fall into B1
  • B1 loop test: i < xs.Length ? go to B2 : go to B5
  • B2 if test: (xs[i] & 1) == 0 ? go to B3 : go to B4
  • B3 body: sum += xs[i]; then B4
  • B4 step: i++; then back to B1
  • B5 exit: return sum;

A decompiler walks those edges, recognises the back-edge from B4 to B1 as a loop and the fork at B2 as an if, and reconstructs your source almost verbatim. The graph is the readability. So the job is to make the graph say nothing.

The idea: hide every edge behind a dispatcher

Flattening keeps all six blocks but cuts every edge between them. Each block no longer jumps to its successor directly. Instead it writes the number of the next block into a state local and jumps back to a single dispatcher — a switch (state) at the top of a while (true) loop. The dispatcher is now the only thing that decides what runs next, and the real order of the blocks lives in the data flowing through state, not in the IL’s branch structure.

Decompiled back to C#, SumEven comes out like this:

int SumEven(int[] xs)
{
    int sum = 0, i = 0;
    int state = 0;
    while (true)
    {
        switch (state)
        {
            case 0:                               // B0 entry
                sum = 0; i = 0;
                state = 1;
                break;
            case 1:                               // B1 loop test
                state = (i < xs.Length) ? 2 : 5;
                break;
            case 2:                               // B2 if test
                state = ((xs[i] & 1) == 0) ? 3 : 4;
                break;
            case 3:                               // B3 body
                sum += xs[i];
                state = 4;
                break;
            case 4:                               // B4 step
                i++;
                state = 1;
                break;
            case 5:                               // B5 exit
                return sum;
        }
    }
}

Read it and the loop is gone. There is no for, no back-edge a tool can point at, no nesting that mirrors the source. Every block is a flat, equal case; the fact that B4 flows back to B1 — the whole reason this is a loop — is now just the assignment state = 1 buried in case 4, indistinguishable from any other state transition.

Original graph Flattened dispatch loop B0 entry B1 test B2 if B3 body B4 step B5 exit back-edge switch (state) case 0 case 1 case 2 case 3 case 4 case 5 state := next; jump back
The real edges on the left become a single fan-out from the dispatcher. Every block's successor is now a value written into state, not a branch in the IL.

The IL shape

At the IL level the dispatcher is a switch opcode over the state local, and every block ends with ldc.i4 / stloc to set the next state followed by an unconditional br back to the dispatcher. Representative IL, trimmed to the shape that matters:

.locals init (int32 sum, int32 i, int32 state)

IL_0000: ldc.i4.0
IL_0001: stloc.2            // state = 0
IL_0002: br IL_0060         // jump straight to the dispatcher

// --- case 0 (B0 entry) ---
IL_0007: ldc.i4.0
IL_0008: stloc.0            // sum = 0
IL_0009: ldc.i4.0
IL_000a: stloc.1            // i = 0
IL_000b: ldc.i4.1
IL_000c: stloc.2            // state = 1
IL_000d: br IL_0060         // back to dispatcher

// --- case 4 (B4 step) ---
IL_0040: ldloc.1
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.1            // i++
IL_0044: ldc.i4.1
IL_0045: stloc.2            // state = 1   <-- the entire "loop" is this line
IL_0046: br IL_0060

// --- case 5 (B5 exit) ---
IL_0058: ldloc.0
IL_0059: ret                // return sum

// --- dispatcher ---
IL_0060: ldloc.2            // load state
IL_0061: switch (IL_0007, IL_0020, IL_0030, IL_0038, IL_0040, IL_0058)
IL_0068: br IL_0060         // default: never reached

The one instruction that used to be a loop — the branch from the end of the step block back to the test — is now IL_0045: stloc.2 with the constant 1. There is no br from B4 to B1 anywhere in the IL. The only back-edge left is the dispatcher’s own br IL_0060, and it is shared by every single block, so it tells an analyst nothing about which block follows which.

Why a naive decompiler loses

A decompiler reconstructs high-level C# by matching patterns in the graph: a back-edge becomes a loop, a fork with a join becomes an if. After flattening, the graph has exactly one fork (the switch) and one back-edge (the dispatcher’s br), reused by everything. There is no per-loop back-edge to find and no if-shaped diamond to collapse. So the decompiler does the only faithful thing it can: it prints the giant switch verbatim. The analyst gets a correct but structureless transcript and has to re-run the state machine in their head to recover the loop you started with.

You can make that harder still by encoding the state values. Instead of 0, 1, 2, … in source order, assign opaque, scattered constants — and set the next state through a small arithmetic expression rather than a literal, so state = 1 becomes something like state = key ^ 0x6A3F. Now even the numbers in the case labels carry no ordering information, and reading the transitions means evaluating the arithmetic by hand for every block.

Applying it in Nebula

Flattening is a per-method transform, and in Nebula it lives under the control-flow section of your project config. Scope it deliberately — these are illustrative option names, not a copy-paste of internal keys:

{
  "renaming": { "mode": "dictionary" },
  "encryptStrings": true,
  "controlFlow": {
    "flatten": true,
    "stateEncoding": "opaque",
    "scope": ["MyApp.Licensing.*", "MyApp.Core.KeyCheck"]
  }
}

Then run the obfuscator over your built assembly:

nebula protect ./bin/Release/net8.0/MyApp.dll \
  --config nebula.config.json \
  --out ./protected/

Two choices matter. scope keeps flattening on the handful of methods that are actually worth protecting — your license verification, a key-derivation routine, a critical business rule — and off everything else. And pairing it with encryptStrings matters because flattening hides structure but not content: a visible error string or magic constant re-anchors an analyst instantly, undoing much of what the flattening cost you. Flattening is a Pro-tier control-flow transform; combine it with the string and constant protection in the same tier for a method that gives up neither its shape nor its literals.

The honest costs

Flattening is not free, and it does not do things it cannot do.

  • It adds a branch per block. Every original fall-through is now a stloc plus a br plus the dispatcher switch. A method that ran as straight-line code now takes an indirect dispatch on every block boundary.
  • It defeats branch prediction. The CPU was good at predicting your loop’s back-edge. The dispatcher’s single switch is taken from a different case every iteration, so the predictor mostly misses. In a hot loop that is a real, measurable slowdown — which is exactly why you keep flattening out of hot loops and on the sensitive methods instead.
  • Methods get bigger, which spends the JIT’s inlining budget and pollutes the instruction cache. A method that was inlined before may stop being inlined after.
  • It encrypts nothing. The IL for each block is still plain IL; a reader who works through the state machine recovers the exact operations. Flattening raises the cost of reading, it does not lock the door.
  • A determined analyst can undo it. Deobfuscation tooling can treat the method as a state machine, recover the transition for each case, and rebuild the original graph — especially if the state values are plain literals in source order. Opaque state encoding slows this down; it does not make it impossible.

Takeaway

Control-flow flattening trades a clean, readable graph for a flat dispatch loop whose structure lives in data, not in branches. It is the right tool when the thing you are protecting is the logic — a licensing check, a protected algorithm — and you can afford a few indirect branches to hide it. It is the wrong tool for a tight numeric loop, for a whole assembly at once, or as a substitute for encrypting the strings and constants that would otherwise give the method away. Scope it to the methods that matter, encode the state, keep the literals protected too, and measure your hottest path before and after. Done that way, flattening turns a five-minute decompile into a state machine an analyst has to reverse by hand.

Try Nebula.NET

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