DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

How Glass recovers the unmanaged constraint

where T : unmanaged looks like a first-class constraint in C#. You write it, the compiler accepts it, and inside the method you can take &v, sizeof(T), or stackalloc T[n] as if T were a blittable primitive. So it is natural to assume the metadata has an "unmanaged" constraint kind sitting next to class and struct. It does not. There is no flag for it. The compiler lowers unmanaged to the same value-type bit that struct sets, then hangs two extra markers off the generic parameter to say "and it was actually unmanaged." Miss those markers and you decompile unmanaged as struct — code that still compiles but quietly drops a guarantee the author relied on. This post shows the encoding and how Glass.NET rebuilds the keyword.

The source looks like its own constraint

Here is a method that only makes sense under unmanaged — it writes T as raw bytes, which requires a blittable, pointer-free value type:

public static class Raw
{
    public static unsafe void Write<T>(Span<byte> dst, T v) where T : unmanaged
    {
        if (dst.Length < sizeof(T))
            throw new ArgumentException("destination too small");
        fixed (byte* p = dst)
            *(T*)p = v;
    }
}
Enter fullscreen mode Exit fullscreen mode

sizeof(T) and *(T*)p are legal only because T : unmanaged promises T contains no managed references. Change the constraint to struct and this file stops compiling. Yet in metadata the constraint on T starts life looking almost identical to struct.

What the compiler really emits

Here is the generic parameter as Glass shows it in the IL view. Two things carry the meaning, and neither is a flag named "unmanaged":

.method public hidebysig static void Write<valuetype .ctor
    (class [System.Runtime]System.ValueType modreq(
        [System.Runtime]System.Runtime.InteropServices.UnmanagedType)) T>
    (valuetype [System.Runtime]System.Span`1<uint8> dst, !!T v) cil managed
{
    .param type T
    .custom instance void System.Runtime.CompilerServices.IsUnmanagedAttribute::.ctor() = ( 01 00 00 00 )
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Read the generic-parameter clause carefully. valuetype .ctor is the ordinary value-type constraint — the NotNullableValueTypeConstraint bit plus the implied public parameterless constructor. That is exactly what where T : struct produces; on its own it says nothing more than "a non-nullable value type."

The discriminator is the constraint entry itself: class System.ValueType modreq(...UnmanagedType). The compiler lists System.ValueType as the type constraint — same as struct — but attaches a required custom modifier, modreq(System.Runtime.InteropServices.UnmanagedType), to it. Then .param type T carries a second marker, the IsUnmanagedAttribute. The ( 01 00 00 00 ) blob is just the attribute prolog with no arguments.

Compare the same method written with where T : struct:

.method public hidebysig static void WriteStruct<valuetype .ctor
    (class [System.Runtime]System.ValueType) T>
    (!!T v) cil managed
Enter fullscreen mode Exit fullscreen mode

Same valuetype .ctor, same System.ValueType constraint — but no modreq, and no IsUnmanagedAttribute on the parameter. The value-type bit is identical in both. The modreq and the marker attribute are the only difference between unmanaged and struct in the binary. A decompiler that stops at the value-type bit sees two things that look the same and emits struct for both.


Both struct and unmanaged set the value-type bit; only unmanaged adds modreq(UnmanagedType) and IsUnmanaged, which is the discriminator Glass reads




The value-type bit is shared by both constraints; the modreq(UnmanagedType) on the System.ValueType constraint and the IsUnmanaged marker are what distinguish unmanaged, and are what Glass reads to choose the keyword.

The embedded marker attribute

IsUnmanagedAttribute raises a second question: where is it defined? It lives in System.Runtime.CompilerServices, but older target frameworks do not ship it. Rather than depend on the framework, Roslyn synthesizes the attribute and embeds a private copy directly in your module — the same mechanism it uses for IsReadOnlyAttribute (on readonly struct / in parameters) and IsByRefLikeAttribute (on ref struct). The embedded type is itself tagged with Microsoft.CodeAnalysis.EmbeddedAttribute and made non-public:

.class private auto ansi sealed beforefieldinit
    System.Runtime.CompilerServices.IsUnmanagedAttribute
    extends [System.Runtime]System.Attribute
{
    .custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = ( 01 00 00 00 )
    .custom instance void [System.Runtime]System.Diagnostics.CodeAnalysis...
}
Enter fullscreen mode Exit fullscreen mode

This type is pure plumbing. You never wrote it, and re-emitting its definition — plus the [IsUnmanaged] usage on the parameter — would be noise that does not compile back to the original source. Glass recognizes the EmbeddedAttribute marker, treats IsUnmanagedAttribute (and its siblings IsReadOnlyAttribute, IsByRefLikeAttribute, EmbeddedAttribute itself) as compiler-synthesized, and hides them: it consumes the marker to recover unmanaged but prints neither the embedded class nor the attribute usage. This is the same policy covered for ref struct in the ref-fields and ref-struct walkthrough.

How Glass applies it

For each generic parameter, Glass resolves the constraint in order:

  1. Read GenericParameterAttributes. If NotNullableValueTypeConstraint is set, the parameter is at least struct.
  2. Inspect the type constraints. If the System.ValueType constraint carries modreq(System.Runtime.InteropServices.UnmanagedType) and the parameter carries IsUnmanagedAttribute, upgrade the rendering from struct to unmanaged.
  3. Suppress the synthesized markers from the attribute list, and suppress System.ValueType from the explicit constraint list (it is implied by the keyword, exactly as it is for struct).

The recovered signature reads back as the source:

public static class Raw
{
    public static unsafe void Write<T>(Span<byte> dst, T v) where T : unmanaged
    {
        if (dst.Length < sizeof(T))
            throw new ArgumentException("destination too small");
        fixed (byte* p = dst)
            *(T*)p = v;
    }
}
Enter fullscreen mode Exit fullscreen mode

No [IsUnmanaged], no embedded attribute class, no bare System.ValueType constraint — just where T : unmanaged, which is the only spelling under which the sizeof(T) and *(T*)p in the body are legal.

When it breaks

Every limit here follows from the markers being the only record of intent:

  • Stripped markers fall back to struct. If an obfuscator removes the modreq or the IsUnmanagedAttribute, or strips the embedded attribute definition, only the value-type bit remains. Glass emits where T : struct. That still compiles; it is a slightly weaker constraint that now also admits managed value types the original rejected. You lose a compile-time guarantee, not program behaviour. Glass will not guess unmanaged where nothing marks it.
  • Non-Roslyn or pre-7.3 output. unmanaged is a C# 7.3+ construct, and the lowering described here is Roslyn's. A different compiler, or hand-written IL, may set the value-type bit without the modreq/marker pair; Glass reads it as struct. The recovered source therefore targets a C# version new enough to accept whatever keyword it emits.
  • The constraint is compile-time only. unmanaged constrains who may instantiate Write<T>; at runtime T is already a concrete blittable type and the body is ordinary pointer code. Glass reconstructs the constraint from the metadata the compiler left behind — it is not re-deriving it from the method body, so if that metadata is gone, the body alone cannot prove unmanaged.

Reading it yourself

Open an assembly in Glass, find a generic method or type with a value-type constraint, and switch between the C# and IL views. In IL you will see valuetype .ctor plus a System.ValueType constraint; look for the modreq(UnmanagedType) hanging off that constraint and the IsUnmanagedAttribute on the .param type. In C# you will see where T : unmanaged where both markers are present and where T : struct where only the bit is. Then strip the marker in a scratch build and watch Glass fall back to struct — the clearest way to see that unmanaged is encoded as struct plus two side-channel markers, not as a constraint kind of its own. The same embedded-attribute recognition also hides the readonly/ref struct plumbing discussed alongside Glass's handling of native integers.

Glass.NET is a free .NET decompiler for code you have the right to inspect — your own assemblies, your dependencies, and third-party binaries you are licensed to analyse. Reading the modreq and the synthesized markers alongside the value-type bit is what turns a generic that merely looks like struct back into the unmanaged constraint its author actually wrote.

Top comments (0)