DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

How a decompiler reads defensive struct copies

A struct field that never changes, no matter how many times you call a method that was supposed to change it. The field is readonly, the method does ++_n, and the counter stays at zero forever. No exception, no warning at the call site — just a value that will not move. The IL explains it in four instructions, and once you can read them, a whole class of silent performance bugs becomes visible.

The real question

C# lets you mark a struct field readonly. That promise has to hold even when you call a member that could mutate the struct. The compiler cannot know, in general, whether _counter.Next() writes to this — so for a non-readonly member it assumes the worst and refuses to let the call touch the real field. Instead it copies the struct to a scratch local and calls the member there. Your readonly field is safe; the mutation lands on a copy that is discarded a moment later.

That copy is invisible in source. The question for a decompiler is the reverse of the compiler's: given IL that loads a struct by value, stashes it, and calls a method on the stash, is that a copy the programmer wrote — or one the compiler inserted to guard a readonly location? Render it wrong and you either invent a local that was never in the source, or you hide a copy the reader needs to see.

What the compiler emits

Here is the canonical trap. A small mutable struct, held in a readonly field:

public struct Counter
{
    private int _n;
    public int Next() => ++_n;   // mutates this
}

public sealed class Box
{
    private readonly Counter _counter;

    public int Peek() => _counter.Next();
}
Enter fullscreen mode Exit fullscreen mode

Next() is not marked readonly, so from the compiler's view it might mutate the struct. _counter is a readonly field, so the compiler is not allowed to mutate it. The two constraints collide, and the compiler resolves them by copying. The IL for Peek():

.method public hidebysig instance int32 Peek () cil managed
{
  .locals init (valuetype Counter V_0)
  ldarg.0
  ldfld     valuetype Counter Box::_counter
  stloc.0
  ldloca.s  V_0
  call      instance int32 Counter::Next()
  ret
}
Enter fullscreen mode Exit fullscreen mode

Read it instruction by instruction. ldfld loads the value of _counter onto the stack — a bytewise copy of the struct, not its address. stloc.0 drops that copy into a fresh local V_0. ldloca.s V_0 takes the address of the copy, and call runs Next() against it. Next() increments V_0._n; V_0 is thrown away at ret. The field in Box is never addressed and never changes.

Contrast that with what the compiler emits if the field is not readonly:

ldarg.0
ldflda    valuetype Counter Box::_counter
call      instance int32 Counter::Next()
Enter fullscreen mode Exit fullscreen mode

One instruction shorter, and decisive. ldflda loads the address of the real field, so Next() mutates it in place. No local, no copy. The single difference — ldfld + stloc + ldloca versus a bare ldflda — is the entire signature of a defensive copy.






The only difference between a guarded call and a direct one: a value-load through a temporary versus a single address-load.

What Glass has to decide

A naive decompiler reads the four-instruction sequence literally and prints what it sees:

public int Peek()
{
    Counter V_0 = _counter;
    return V_0.Next();
}
Enter fullscreen mode Exit fullscreen mode

That is faithful to the IL and wrong as C#. The local V_0 was never in the source; it is an artifact of the compiler guarding a readonly field. Worse, a reader now thinks the author deliberately copied the struct, when in fact they wrote _counter.Next() and were surprised by the result.

Glass folds the copy away by matching its signature. The pattern is tight and unambiguous: a struct value loaded from a readonly location (ldfld on a field whose row carries InitOnly, or ldarg of an in parameter), stored into a compiler-generated, single-assignment, single-use local, then immediately re-addressed with ldloca for exactly one member call. When all of those hold, the local is not a variable — it is a copy — and Glass elides it, rendering the call on its real source:

public int Peek() => _counter.Next();
Enter fullscreen mode Exit fullscreen mode

The distinction from a genuine copy is real, not cosmetic. If the source actually said var c = _counter; return c.Next();, the local c is used in a way the pattern does not match — it is named in the PDB if symbols are present, it may be read more than once, or its address is taken for more than a single call. Any of those breaks the signature, and Glass keeps the local. The fold only fires on the exact shape the compiler produces and nothing else.

The readonly member signal

There is a useful inversion here. C# 8 lets you mark an instance member readonly, promising it does not mutate this. When a member carries that promise, the compiler drops the defensive copy even on a readonly field — it emits ldflda and calls directly, because it now knows the call is safe. So the presence of a defensive copy in the IL is positive evidence that the member was not readonly at compile time.

That is worth surfacing when you are auditing a hot struct. If Peek() decompiles with the copy folded but you know _counter is readonly and large, the copy is still happening on every call — a memcpy of the whole struct you may not have intended. Glass shows you the clean source and preserves the IL view, so you can confirm the ldfld/ldloca pair is really there. Mark Next() as readonly, recompile, and the copy — and the pattern — disappears.

When it breaks

The fold is deliberately conservative, and there are shapes it will not touch. If the compiler reuses the same temp for two different calls, the local stops being single-use and Glass leaves it visible — collapsing it would change meaning. A struct copied for a reason other than a readonly guard (a by-value argument the callee is free to mutate, for instance) is a copy the reader should see, and the pattern does not match it because the destination is a parameter slot, not a one-shot scratch local. And in debug builds, extra nops and un-optimized temporaries can sit between the stloc and the ldloca; Glass matches across them, but heavily rewritten or obfuscated IL can defeat the match, in which case you drop to the IL view and read the ldfld/ldflda choice yourself.

Takeaway

A defensive copy is one of the few places where correct C# and buggy C# compile to nearly identical IL, separated by a single opcode. ldflda mutates your field; ldfld + a scratch local mutates a copy and discards it. Glass reads that distinction, folds the compiler's temporary back into a direct member call, and keeps the IL on hand so you can see the copy that the source hides — which is exactly what you need when a readonly struct quietly refuses to change. Glass is a free .NET decompiler; see Glass and the docs.

Top comments (0)