DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

How Glass reads raw block-copy opcodes

A method body copies a kilobyte of memory in a single instruction — no loop, no Array.Copy, no P/Invoke to memcpy. Three values go on the evaluation stack, one opcode consumes all three, and the block is moved. Another body fills a buffer with a single byte the same way. These are cpblk and initblk, the CIL block-memory opcodes, and no C# syntax emits either one. Point a decompiler at a body that contains them and the question is immediate: what readable C# stands in for an instruction the language cannot express? This post walks the exact semantics of both opcodes, their unaligned. and volatile. prefixes, and how Glass.NET maps them back to the Unsafe methods that are the real C# surface — and where it has to stop short and show the raw intrinsic.

The real question

C# never compiles any source construct to cpblk or initblk. The way those opcodes reach a managed program is System.Runtime.CompilerServices.Unsafe:

  • Unsafe.CopyBlock and Unsafe.CopyBlockUnaligned → cpblk
  • Unsafe.InitBlock and Unsafe.InitBlockUnaligned → initblk

But here is the subtlety that shapes the whole decompilation problem: the raw opcode does not appear at your call site. When you call Unsafe.CopyBlock(...), your method's IL carries a plain call to Unsafe::CopyBlock. The cpblk instruction lives inside the body of CopyBlock itself — a hand-written IL method in the runtime. So a decompiler meets a bare cpblk in three situations: decompiling the Unsafe methods' own bodies; decompiling assemblies emitted by ilasm, an IL rewriter, or a non-C# compiler that wrote the opcode directly; and reading older low-level code that predates Unsafe. In every one of those, Glass has a raw block opcode and no call wrapping it. The reconstruction target is the Unsafe call the opcode is the primitive for.

cpblk: copy a block

cpblk (byte sequence 0xFE 0x17) copies a run of bytes from one address to another. Its stack transition, from ECMA-335, is:

..., destaddr, srcaddr, size  ->  ...
Enter fullscreen mode Exit fullscreen mode

The three operands are pushed in that order, so at the point of the opcode the byte count is on top of the stack, the source address is beneath it, and the destination address is deepest. cpblk pops all three and copies size bytes from srcaddr to destaddr. It is a straight block move with no overlap handling — the behaviour is memcpy, not memmove, so overlapping regions are undefined. The addresses may be managed pointers (&), unmanaged pointers (*), or native ints; size is an unsigned int32.

The body of Unsafe.CopyBlock(ref byte destination, ref byte source, uint byteCount) is exactly that, nothing more:

ldarg.0      // destination
ldarg.1      // source
ldarg.2      // byteCount
cpblk        // 0xFE 0x17
ret
Enter fullscreen mode Exit fullscreen mode

Glass reads that shape — push dest, push src, push size, then cpblk, with each operand a simple argument or local — and reconstructs the call it is the primitive for:

Unsafe.CopyBlock(ref destination, ref source, byteCount);
Enter fullscreen mode Exit fullscreen mode

initblk: set a block

initblk (0xFE 0x18) fills a run of bytes with a single value. Its stack transition is:

..., destaddr, value, size  ->  ...
Enter fullscreen mode Exit fullscreen mode

Pushed destination-address, fill-value, byte-count — so the count is on top, the fill value (an unsigned int8) under it, and the destination deepest. initblk pops all three and writes the single byte value into size bytes starting at destaddr. This is the IL memset. The body of Unsafe.InitBlock(ref byte startAddress, byte value, uint byteCount) mirrors CopyBlock:

ldarg.0      // startAddress
ldarg.1      // value
ldarg.2      // byteCount
initblk      // 0xFE 0x18
ret
Enter fullscreen mode Exit fullscreen mode

and Glass renders it back as:

Unsafe.InitBlock(ref startAddress, value, byteCount);
Enter fullscreen mode Exit fullscreen mode

The two opcodes differ only in their middle operand — cpblk takes a source address, initblk takes a fill byte — and that single difference is what tells the two Unsafe methods apart.

cpblk and initblk pop three stack operands — they differ only in the middle one, a source address versus a fill byte. The unaligned. and volatile. prefixes sit immediately before the opcode and select the Unsafe variant.

The prefixes: unaligned. and volatile.

Both block opcodes accept the two memory-access prefixes, and they are what distinguish the Unsafe variants.

unaligned. (0xFE 0x12) carries a single-byte alignment operand — 1, 2, or 4 — and warns the JIT that the addresses may not be naturally aligned, so it must not assume alignment when it lowers the copy to platform instructions. This is the only difference between CopyBlockUnaligned and CopyBlock. The body of Unsafe.CopyBlockUnaligned is the CopyBlock body with one prefix added:

ldarg.0
ldarg.1
ldarg.2
unaligned. 1   // 0xFE 0x12, alignment = 1
cpblk          // 0xFE 0x17
ret
Enter fullscreen mode Exit fullscreen mode

Glass reads the unaligned. prefix sitting in front of the cpblk and reconstructs the unaligned call rather than the plain one:

Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
Enter fullscreen mode Exit fullscreen mode

The same prefix in front of initblk recovers Unsafe.InitBlockUnaligned. The alignment operand itself is part of the prefix encoding, not a separate stack value, so it never shows as an argument — the presence of the prefix is the whole signal.

volatile. (0xFE 0x13) takes no operand and marks the access as volatile, imposing the ordering and non-elision guarantees of a volatile memory operation. There is no Unsafe method and no C# construct that produces a volatile block copy — it is hand-written IL territory. When Glass meets volatile. in front of a block opcode, it cannot print an honest Unsafe call that would reproduce it, so it surfaces the prefix as an annotation on the recovered call rather than silently dropping a semantic the author relied on:

ldarg.0
ldarg.1
ldarg.2
volatile.      // 0xFE 0x13
cpblk          // 0xFE 0x17
ret
Enter fullscreen mode Exit fullscreen mode
// volatile. cpblk — no C# surface; volatile semantics preserved only in IL
Unsafe.CopyBlock(ref destination, ref source, byteCount);
Enter fullscreen mode Exit fullscreen mode

A real example

Here is ordinary C# that reaches both opcodes — one filling a span with a byte, one copying between buffers — using the ref-based overloads so no unsafe block is needed:

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

static class Blocks
{
    // Zero (or fill) every byte of a span.
    public static void Fill(Span<byte> buffer, byte value) =>
        Unsafe.InitBlock(
            ref MemoryMarshal.GetReference(buffer),
            value,
            (uint)buffer.Length);

    // Copy the first `count` bytes of src into dst.
    public static void Copy(Span<byte> dst, ReadOnlySpan<byte> src, int count) =>
        Unsafe.CopyBlock(
            ref MemoryMarshal.GetReference(dst),
            ref MemoryMarshal.GetReference(src),
            (uint)count);
}
Enter fullscreen mode Exit fullscreen mode

In this assembly, the IL for Fill is not an initblk — it is a call:

ldarg.0
call       !!0& [System.Runtime]System.Runtime.InteropServices.MemoryMarshal::GetReference<uint8>(valuetype [System.Runtime]System.Span`1<!!0>)
ldarg.1
ldarg.0
call       instance int32 valuetype [System.Runtime]System.Span`1<uint8>::get_Length()
call       void [System.Runtime]System.Runtime.CompilerServices.Unsafe::InitBlock(uint8&, uint8, uint32)
ret
Enter fullscreen mode Exit fullscreen mode

That call decompiles back to Unsafe.InitBlock(...) trivially — it is already a method call in the metadata. The raw initblk is one level down, in the body of Unsafe.InitBlock itself. So the interesting decompilation happens when Glass opens a body that holds the opcode directly: the runtime's Unsafe methods, or any assembly whose author wrote the opcode by hand. There, the three-push-then-opcode shape is all Glass has, and it is enough.

When the recovery is a guess

The clean mapping holds while the three operands are simple expressions. The honest limits appear when they are not:

  • Arbitrary pointer math breaks the clean call. Unsafe.CopyBlock(ref dest, ref src, size) is honest only when destaddr and srcaddr are single ref/pointer expressions. When they are the result of unrelated arithmetic — an address built from a base plus a computed offset plus a reinterpret — there is no single ref sub-expression to hand the method. Glass then keeps the pointer expressions it recovered and prints the intrinsic over them, or, when even that would misstate the IL, annotates the instruction as a raw cpblk/initblk. It does not fabricate a ref that the IL never formed.
  • The call wrapper is already gone at the opcode. Because the opcode lives in the Unsafe body, not the call site, Glass cannot know from the opcode alone which public overload (void* vs ref byte) a distant caller used — the two bodies are identical. It reconstructs the ref-based form, which is the readable default, and notes the operand kinds it actually saw on the stack.
  • volatile. has no C# equivalent. A volatile block copy can only be expressed in IL. Glass preserves the fact as a comment on the recovered call; the reconstructed C#, recompiled, would emit a non-volatile cpblk and lose the guarantee. That is a true round-trip limit, not a rendering choice, and Glass flags it rather than hiding it.
  • Alignment is informational, not recoverable as code. The unaligned. operand (1/2/4) selects the *Unaligned method but the specific alignment value has no place in the C# call — CopyBlockUnaligned always lowers to unaligned. 1. Glass records a non-1 alignment it finds as a comment; the C# surface cannot carry it.

Reading it yourself

Open the assembly in Glass, select a method that does low-level buffer work, and switch between the C# and IL views. In IL you will see the bare skeleton — three pushes (destination, source-or-value, count), any unaligned./volatile. prefix, then cpblk or initblk. In C# you will see that collapse into a single Unsafe.CopyBlock, Unsafe.CopyBlockUnaligned, Unsafe.InitBlock or Unsafe.InitBlockUnaligned call, with the operands in the order the stack held them. Flip between the two on one method and the mapping stops being abstract: the middle stack slot is the whole difference between a copy and a fill, and the prefix in front of the opcode is the whole difference between the aligned and unaligned method.

Glass.NET is a free .NET decompiler for code you are entitled to inspect — your own assemblies, your dependencies, and third-party binaries you are licensed to analyse. Block-memory opcodes are a good test of a decompiler's honesty: the readable answer is an Unsafe call, but only when the operands actually form one, and the right move when they do not is to show the primitive rather than a tidy call that was never really there. See Glass and the docs.

Top comments (0)