Skip to content
← All posts
· Delta1 Labs GlassDecompilationIL

How Glass recovers stack-allocated buffers

A `Span<byte> buf = stackalloc byte[N]` lowers to a size calculation, the localloc IL instruction, and a Span constructor call. Here is how Glass reads that trio back into stackalloc syntax — constant and variable length, the conditional stack-or-heap pattern, and the loop hazard — instead of raw pointer arithmetic.

A method you are reading allocates a scratch buffer, fills it, hashes it, and returns — no new byte[], no array on the heap, no garbage. The source said stackalloc. But a careless decompiler shows you a localloc, a raw pointer, and a constructor call to Span<byte> with a void* argument. The clean one-liner you wrote is now three lines of unmanaged plumbing. Putting it back together is a small, exact piece of pattern recognition.

The real question

stackalloc is sugar over exactly one IL instruction: localloc. That instruction pops a byte count and pushes a pointer to that many freshly reserved bytes in the current method’s stack frame. Everything else C# does around it — computing the size, wrapping the pointer in a Span<T>, deciding whether to zero the memory — is scaffolding the compiler bolts on. So the question a decompiler must answer is not “where is the array” (there is none) but “this method calls localloc; what stackalloc expression, with what element type and what length, produced it?”

Constant length, Span-wrapped

Start with the modern, safe form — no unsafe block required:

public static int Checksum(ReadOnlySpan<byte> data)
{
    Span<int> scratch = stackalloc int[64];
    foreach (byte b in data) scratch[b & 63]++;
    int total = 0;
    for (int i = 0; i < 64; i++) total += scratch[i];
    return total;
}

stackalloc int[64] is 64 elements of 4 bytes — 256 bytes. The compiler folds the size to a constant and emits:

ldc.i4     256                 // 64 * sizeof(int), folded
conv.u                         // to native uint
localloc                       // reserve 256 bytes, push void*
ldc.i4.s   64                  // element count for the Span length
newobj     instance void valuetype [System.Runtime]System.Span`1<int32>::.ctor(void*, int32)
stloc.0                        // Span<int> V_0

Two numbers appear, and they are not the same number. The localloc operand is the byte count (256). The integer handed to the Span<int> constructor is the element count (64). That split is the whole signal. The constructor’s generic argument is int32, so the element type is int; its length argument is 64; and 64 * sizeof(int) is exactly the 256 that localloc reserved. The three facts agree, and Glass reconstructs stackalloc int[64] with the element count, not the byte count — showing the length the programmer wrote, not the size the CPU saw.

Sourcestackalloc int[64]→Lowered ILldc.i4 256 // byte count = 64 * sizeof(int)localloc // reserve bytes, push void*ldc.i4.s 64 // element countnewobj Span`1<int32>::.ctor(void*, int32)Glass cross-checks the two numberselement type = Span<int> generic arg = int32length = ctor arg (64) checked: 64 * 4 == localloc 256ReconstructedSpan<int> s = stackalloc int[64]
The localloc operand is a byte count; the Span constructor's length is an element count. Glass reads the element type and length from the Span and verifies them against the localloc size.

Variable length

When the length is a runtime value, the compiler can no longer fold the byte size, so it computes it — and it does so with an overflow check, because a large n could wrap the multiplication and reserve far less than the caller asked for:

Span<int> scratch = stackalloc int[n];
ldloc.0                        // n
conv.u
ldc.i4.4                       // sizeof(int)
mul.ovf.un                     // n * 4, overflow-checked
localloc
ldloc.0                        // n again, for the length
newobj     instance void valuetype [System.Runtime]System.Span`1<int32>::.ctor(void*, int32)

The shape is the same, with mul.ovf.un standing in for the folded constant. Glass recognizes the … * sizeof(T) pattern feeding localloc, recovers the element size, and — again — takes the length from the Span constructor’s second argument rather than re-deriving it from the multiplication. The result is stackalloc int[n], the variable intact.

Raw pointers, no Span

Before Span<T>, stackalloc produced a bare pointer and demanded an unsafe context:

unsafe
{
    int* p = stackalloc int[4];
    p[0] = 1; p[1] = 2;
}
ldc.i4.s   16                  // 4 * sizeof(int)
conv.u
localloc
stloc.0                        // int* V_0

There is no constructor to read here, so Glass recovers the element type from the pointer local’s type (int* → int) and the length by dividing the localloc byte size by sizeof(int) — 16 / 4 = 4 — yielding stackalloc int[4]. The pointer form and the Span form share the same localloc core; only the wrapper differs, and Glass keys off whichever one is present.

The conditional stack-or-heap pattern

A buffer that is usually small but occasionally large should not blow the stack. The idiomatic guard is a conditional expression whose two branches both convert to Span<T> — one stack, one heap:

Span<byte> buffer = length <= 256
    ? stackalloc byte[length]
    : new byte[length];

This is legal because stackalloc byte[length] has type Span<byte> and new byte[length] converts implicitly to Span<byte>. The IL branches on the comparison: the true path runs the localloc/Span..ctor sequence; the false path emits newarr [System.Runtime]System.Byte and the implicit array-to-Span conversion. Both land in the same Span<byte> local.

ldarg.0
ldc.i4     256
bgt.s      HEAP
// STACK path
ldarg.0
conv.u
localloc
ldarg.0
newobj     instance void valuetype [System.Runtime]System.Span`1<uint8>::.ctor(void*, int32)
br.s       DONE
HEAP:
ldarg.0
newarr     [System.Runtime]System.Byte
call       valuetype [System.Runtime]System.Span`1<uint8> [System.Runtime]System.Span`1<uint8>::op_Implicit(uint8[])
DONE:
stloc.0

Glass matches the full diamond — a comparison, a localloc-backed Span on one arm and a newarr-backed Span on the other, merging into one local — and renders it back as the ternary, not as an if/else with two separate assignments. Recovering the expression matters: the whole point of the idiom is that buffer is assigned once and used uniformly afterward, and the decompiled source should read that way.

Zeroing, and the loop hazard

Two honest details change how this code behaves, and both live outside the stackalloc expression.

First, zeroing. localloc zeroes the bytes it reserves when the method header’s InitLocals flag is set, which is the default. Mark the method [SkipLocalsInit] and the flag clears: the localloc bytes then hold whatever was on the stack, and code that read the buffer before writing it becomes non-deterministic. Nothing in the stackalloc expression records this — it is a method-header bit — so Glass surfaces it as the reconstructed [SkipLocalsInit] attribute, which is the only place the difference shows.

Second, the loop hazard. localloc memory is reclaimed only when the method returns, never at the end of a block or a loop iteration. A stackalloc inside a loop therefore reserves fresh stack every iteration and frees none of it until the method exits — a fast path to a StackOverflowException. The compiler does not hoist it or reuse the slot; it emits one localloc per iteration exactly as written. Glass decompiles faithfully, so a stackalloc you find inside a loop in recovered code is a real red flag worth reading closely, not a decompiler artifact.

How to use it

Point Glass at the assembly and read the method. The scratch buffer comes back as a stackalloc one-liner, the conditional as a ternary:

glass decompile Hashing.dll --type Hashing --member Checksum
glass decompile Hashing.dll --type Hashing --member Checksum --il   # see the localloc

The IL view is where the mechanism is visible: localloc is the ground truth, and the two numbers around it — the byte count it consumes and the length the Span constructor receives — are what Glass reconciles. Seeing them next to the recovered stackalloc is the fastest way to trust the length. When you export the type to a buildable project, Glass emits the stackalloc form (and the unsafe modifier for the raw-pointer case), so the round-tripped source compiles to the same localloc.

When it breaks

The recovery leans on the Span<T> wrapper telling the truth about the length. A hand-written or obfuscated assembly can construct a Span whose length disagrees with the localloc size; when the two numbers do not reconcile, Glass trusts the localloc byte count for the real allocation and flags the mismatch rather than inventing a clean stackalloc. The raw-pointer form is more fragile still: if the pointer local is reused for an unrelated address, the localloc-to-stackalloc link is only as good as the local’s single assignment. In both cases the fallback is honest — the localloc and the arithmetic are shown as they are — it simply is not the sugar.

Takeaway

stackalloc is one IL instruction wearing a Span costume. Recovering it means reading localloc as the allocation, taking the element type and length from the Span<T> constructor (or the pointer local), and cross-checking them against the reserved byte size — then recognizing the ternary when a conditional guards the stack against large inputs. Glass does all of it, so a zero-allocation hot path reads back as the stackalloc you wrote, not as pointer arithmetic. Glass is a free .NET decompiler; see Glass and the docs.

Try Nebula.NET

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