DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

How checked arithmetic decompiles in C#

A checked or unchecked keyword is one of the few C# constructs that leaves no direct fingerprint in metadata. There is no attribute, no flag, no scope record that says "overflow checking was on here." The information survives in a completely different form: it is smeared across the individual arithmetic instructions, each of which comes in a checking and a non-checking variant. Reconstructing the keyword means reading those instructions back and working out the smallest block of source that would have produced exactly that pattern — and getting it wrong changes what the program does. This post walks the lowering in both directions and shows what Glass.NET rebuilds.

What the source looks like

Overflow checking controls one thing: what happens when an integer operation produces a result too large for its type. Under unchecked (the C# default) the result wraps around silently. Under checked the runtime throws OverflowException. The keyword can scope a block or a single expression:

using System;

static class Money
{
    public static int Total(int a, int b)
    {
        checked
        {
            return a + b;
        }
    }

    public static byte ToByte(int n) => checked((byte)n);

    public static int Fast(int a, int b) => unchecked(a * b);
}
Enter fullscreen mode Exit fullscreen mode

Three methods, three decisions. Total adds with overflow checking on. ToByte narrows an int to a byte with a range check. Fast multiplies with checking explicitly off. Nothing about these intentions is stored as such — each becomes a choice of opcode.

What the compiler really emits

Here are the three method bodies as Glass shows them in the IL view. Watch the suffixes.

.method public hidebysig static int32 Total (int32 a, int32 b) cil managed
{
    IL_0000: ldarg.0
    IL_0001: ldarg.1
    IL_0002: add.ovf
    IL_0003: ret
}

.method public hidebysig static uint8 ToByte (int32 n) cil managed
{
    IL_0000: ldarg.0
    IL_0001: conv.ovf.u1
    IL_0002: ret
}

.method public hidebysig static int32 Fast (int32 a, int32 b) cil managed
{
    IL_0000: ldarg.0
    IL_0001: ldarg.1
    IL_0002: mul
    IL_0003: ret
}
Enter fullscreen mode Exit fullscreen mode

The entire difference between checked and unchecked is three characters of opcode mnemonic. add.ovf is add with a trap on overflow. conv.ovf.u1 is the range-checking narrowing conversion to unsigned 8-bit; its unchecked twin is the bare conv.u1, which truncates. mul is the plain multiply with no trap. The compiler made one checking decision per instruction and threw the block structure away.

The conversion opcodes are a family

Narrowing conversions are where overflow checking matters most, because every assignment to a smaller integer type is a potential loss. The CLR gives each target type a matched pair:

conv.u1       // int -> byte, truncating      (unchecked)
conv.ovf.u1   // int -> byte, range-checked    (checked)
conv.i2       // int -> short, truncating      (unchecked)
conv.ovf.i2   // int -> short, range-checked    (checked)
conv.ovf.i4.un // uint -> int, range-checked, source treated as unsigned
Enter fullscreen mode Exit fullscreen mode

The .un suffix on the last one is the second axis: it tells the conversion to treat its source as unsigned when deciding whether the value fits. That is how checked((int)someUInt) is distinguished from checked((int)someInt) — same target, different interpretation of the bits already on the stack. A decompiler has to carry both the .ovf and the .un flags through, because dropping either one silently changes the conversion's semantics.

The asymmetry: where checked does nothing

Not every arithmetic operation has an overflow variant, and this is the part naive reconstruction gets wrong. There is no div.ovf and no rem.ovf. Integer division has exactly one overflow case — int.MinValue / -1, whose true result is 2147483648 and does not fit in an int — and ECMA-335 makes that case throw unconditionally, in checked and unchecked contexts alike. Since the behaviour is identical either way, the compiler emits plain div whether or not you wrote checked.

The practical consequence for decompilation: a div instruction carries no overflow-context information. If a method contains checked { return a / b; }, the IL is indistinguishable from unchecked { return a / b; }, and Glass will not fabricate a checked region around a bare div. It reconstructs context only from instructions that actually encode it.

The pipeline, end to end


How a checked block compiles to per-instruction overflow opcodes and how Glass.NET rebuilds the smallest checked region


1 · Source block
checked {
return a + b;
}

2 · Per-instruction
ldarg.0 / ldarg.1
add.ovf
block boundary erased

3 · Opcode set
.ovf present → trap
plain → wrap
div → no signal



Glass.NET reconstructs
checked { return a + b; }
smallest region covering every .ovf instruction, no larger

The compiler expands one keyword into a set of opcode choices; the decompiler reads the set and infers the narrowest keyword that reproduces it.

What a naive decompiler shows — and what Glass shows

A decompiler that ignores overflow suffixes produces source that compiles and reads cleanly but behaves differently. Drop the .ovf from conv.ovf.u1 and you have turned a conversion that throws on out-of-range input into one that silently truncates:

// suffix ignored — compiles, reads fine, WRONG behaviour
public static byte ToByte(int n) => (byte)n;   // truncates 300 to 44
Enter fullscreen mode Exit fullscreen mode

That is the dangerous failure mode: the bug is invisible on the page. Glass carries the checking flag through and renders the keyword that restores the exact semantics. It also scopes the block minimally — it does not wrap the whole method in checked when only one instruction carries .ovf:

static class Money
{
    public static int Total(int a, int b) => checked(a + b);

    public static byte ToByte(int n) => checked((byte)n);

    public static int Fast(int a, int b) => a * b;
}
Enter fullscreen mode Exit fullscreen mode

Note Fast loses its explicit unchecked: because unchecked is the language default, a * b and unchecked(a * b) compile to the identical mul, so Glass renders the shorter form that produces the same IL. It adds the keyword only where the opcode choice would otherwise be lost.

The one thing IL cannot tell you

If the project was built with <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>, the default context flips for the whole assembly. A bare a + b then compiles to add.ovf with no keyword in sight — byte-for-byte identical to an explicit checked(a + b) in a normal project. Glass reconstructs under the standard default-unchecked assumption, so it will show checked where the opcodes demand it. It cannot recover a build-wide flag that left no trace, and it does not guess at one.

Reading it yourself

Open the assembly in Glass, select a method, and switch between the C# and IL views. Line up each checked(...) region in the source against the .ovf suffixes in the IL, and find the div that carries no suffix at all. Then try a narrowing cast both ways in a scratch assembly and watch conv.u1 become conv.ovf.u1 the moment you add the keyword — it is the clearest way to see that overflow checking is an instruction-level decision, not a block the metadata remembers.

Glass.NET is a free .NET decompiler for inspecting code you have the right to inspect — your own assemblies, your dependencies, and third-party binaries you are licensed to analyse. Preserving semantics-carrying details like the .ovf suffix is the difference between a decompilation you can trust and one that reads right but runs wrong.

Top comments (0)