# Obfuscating UnsafeAccessor without breaking it


Reflection over private members was always the slow, ugly way to reach into code you did not own: `GetField("_count", BindingFlags.NonPublic | BindingFlags.Instance)`, a `FieldInfo`, a boxed `GetValue`, and a lookup on every call. .NET 8 gave us a clean replacement — `[UnsafeAccessor]`, an `extern static` method the runtime binds directly to a private field, method or constructor, with the speed of a direct call and no reflection object in sight. It is a genuinely good feature. It also quietly reintroduces the one thing an obfuscator exists to remove: a member's name, written out as a literal string, sitting in your metadata.

## The question

Here is the shape of it. A type with private state, and an accessor that reaches in:

```csharp
public sealed class RateLimiter
{
    private int _remaining;
    private long ComputeWindow(long now) => now / _windowTicks;
    private readonly long _windowTicks = TimeSpan.FromMinutes(1).Ticks;
}

static class RateLimiterAccessors
{
    [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_remaining")]
    extern static ref int Remaining(RateLimiter r);

    [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "ComputeWindow")]
    extern static long ComputeWindow(RateLimiter r, long now);
}
```

Now you obfuscate the assembly, and renaming does its job: `_remaining` becomes `a`, `ComputeWindow` becomes `b`. The accessor methods have no body to rewrite — but their attributes still say `Name = "_remaining"` and `Name = "ComputeWindow"`. The assembly compiles. It loads. It starts. The first time `Remaining(limiter)` runs, the runtime looks for a field literally named `_remaining` on a type that no longer has one, and throws `MissingFieldException`. Nothing failed at build time; the string and the thing it named simply drifted apart. The real question is *why* a feature designed to replace reflection inherits reflection's fragility under renaming — and what an obfuscator has to do about it.

## How the runtime binds an accessor

Start from what the compiler emits. An `[UnsafeAccessor]` method is `extern` — it has no IL body. The whole contract lives in the custom attribute and the method's own signature. Decompiled, the field accessor looks like this:

```
.method private hidebysig static int32& Remaining (class RateLimiter r) cil managed
{
    .custom instance void System.Runtime.CompilerServices.UnsafeAccessorAttribute::.ctor(
        valuetype System.Runtime.CompilerServices.UnsafeAccessorKind) = (
        01 00 03 00 00 00 01 00 54 0e 04 4e 61 6d 65 06 5f 72 65 6d 61 69 6e 69 6e 67
    )
}
```

The bytes are the point. That blob is the entire binding instruction, and you can read it by hand. `01 00` is the attribute prolog. `03 00 00 00` is the single constructor argument — `UnsafeAccessorKind.Field`, whose enum value is `3`. `01 00` says there is one named argument. `54` marks it as a property, `0e` is the element type `string`, `04 4e 61 6d 65` is the length-prefixed UTF-8 string `Name`, and `06 5f 72 65 6d 61 69 6e 69 6e 67` is the length-prefixed UTF-8 string `_remaining` — the bytes `5f 72 65 6d 61 69 6e 69 6e 67` spell `_remaining` character for character. The member name is not a token into the metadata tables. It is text, embedded in an attribute, invisible to anything that rewrites references by token.

When the method is first called, the JIT resolves it. It takes the kind (`Field`), the name (`_remaining`) and the accessor's signature, and searches the target type — the first parameter's type, `RateLimiter` — for a member that matches all three. For a field accessor the return type (`ref int`) must match the field type; for a method accessor the remaining parameters and the return type must match the target method's signature. If exactly one member matches, the runtime wires the call straight to it, with no reflection object and no per-call lookup. If none matches, you get `MissingFieldException` or `MissingMethodException`.

<figure class="my-8"><svg viewBox="0 0 720 300" role="img" aria-label="An UnsafeAccessor attribute binds to a private member by name plus signature. The accessor method Remaining carries an attribute whose blob contains the kind Field and the name string _remaining. At JIT time the runtime resolves that name against the target type RateLimiter. On the left, the correct case: renaming rewrites both the field to a and the accessor Name argument to a in lockstep, so the bind succeeds. On the right, the broken case: the field is renamed to a but the Name string still says _remaining, so the bind throws MissingFieldException." style="width:100%;height:auto"><defs><style>.ti{font:600 13px system-ui;fill:#6366f1}.lbl{font:600 11px system-ui;fill:#0f172a}.x{font:11px system-ui;fill:#64748b}.mono{font:600 10.5px ui-monospace,monospace;fill:#0f172a}.ok{fill:#ecfdf5;stroke:#6ee7b7}.bad{fill:#fef2f2;stroke:#fca5a5}.box{fill:#ffffff;stroke:#cbd5e1}.hub{fill:#eef2ff;stroke:#a5b4fc}.flow{stroke:#94a3b8;stroke-width:1.5;fill:none}.okt{font:600 11px system-ui;fill:#059669}.badt{font:600 11px system-ui;fill:#dc2626}</style><marker id="ar" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#94a3b8"/></marker></defs><rect class="hub" x="250" y="16" width="220" height="56" rx="8"/><text class="ti" x="360" y="38" text-anchor="middle">[UnsafeAccessor] bind</text><text class="x" x="360" y="58" text-anchor="middle">kind + Name string + signature</text><text class="mono" x="360" y="92" text-anchor="middle">.custom ...Kind = (03) Name = "_remaining"</text><path class="flow" d="M300 100 L150 132" marker-end="url(#ar)"/><path class="flow" d="M420 100 L570 132" marker-end="url(#ar)"/><rect class="ok" x="20" y="140" width="320" height="140" rx="8"/><text class="okt" x="34" y="162">renamed in lockstep — resolves</text><rect class="box" x="34" y="174" width="292" height="40" rx="5"/><text class="mono" x="46" y="190">field  _remaining  →  a</text><text class="mono" x="46" y="206">accessor Name "_remaining" → "a"</text><rect class="box" x="34" y="222" width="292" height="44" rx="5"/><text class="x" x="46" y="240">JIT finds field a on RateLimiter</text><text class="okt" x="46" y="258">bind succeeds · direct ref int access</text><rect class="bad" x="380" y="140" width="320" height="140" rx="8"/><text class="badt" x="394" y="162">name left stale — throws at first call</text><rect class="box" x="394" y="174" width="292" height="40" rx="5"/><text class="mono" x="406" y="190">field  _remaining  →  a</text><text class="mono" x="406" y="206">accessor Name "_remaining"  (unchanged)</text><rect class="box" x="394" y="222" width="292" height="44" rx="5"/><text class="x" x="406" y="240">JIT searches for _remaining — gone</text><text class="badt" x="406" y="258">MissingFieldException at runtime</text></svg></figure>

## Why renaming has to be lockstep

A normal method call survives renaming because it is a *token*. `callvirt instance int32 RateLimiter::get_Count()` encodes the target as a `MethodRef`/`MethodDef` handle — a number into the metadata tables. When the obfuscator renames `get_Count`, it changes the row that handle points at; the token is unchanged and still resolves to the right member. Tokens are why renaming is safe for the overwhelming majority of code: every reference is a handle, and the handle follows the member.

`[UnsafeAccessor]` opts out of that machinery. The member it binds to is named by a string in an attribute blob, deliberately, because the whole point is to reach a member you *cannot* reference by token — a private one the compiler would refuse to emit a call to. So there is no token to carry the rename. If the obfuscator treats the blob as opaque bytes, the name stays `_remaining` while the field becomes `a`, and the two drift apart at the next JIT.

This is why Nebula treats `[UnsafeAccessor]` as a first-class rename dependency rather than inert metadata. When it renames a member, it looks for accessor attributes in the input set whose kind, `Name` and signature resolve to that member, and rewrites the `Name` argument in the same pass — `"_remaining"` becomes `"a"`, in the blob, as the field becomes `a`. The accessor and its target move together, so the bind that succeeded before obfuscation succeeds after it, and the member name is gone from cleartext in both the declaration and the accessor. That lockstep rewrite is the correct behaviour, and it is exactly what reflection-string renaming cannot do, because a reflection string is an arbitrary expression the obfuscator cannot in general trace to a member — whereas an accessor's target is pinned by kind plus signature, which Nebula *can* resolve.

## Where it applies, and what you still do by hand

Most accessors in a codebase bind to a member in the same assembly, and Nebula handles those for you — rename the field, the accessor follows, nothing to configure. Two cases still need a decision.

**The accessor targets another assembly.** If you reach into a private member of a type you do not own — a framework type, a third-party library — that assembly is not in your input set, so Nebula never renames the target and the `Name` string stays valid on its own. There is nothing to do and nothing breaks. The hazard is strictly for same-assembly targets, which is also the only set the obfuscator can see.

**You would rather keep the member than rewrite the string.** For a small number of accessors, excluding the target from renaming is simpler to reason about than trusting the lockstep rewrite:

```csharp
public sealed class RateLimiter
{
    [Obfuscation(Feature = "renaming", Exclude = true)]   // bound by an UnsafeAccessor
    private int _remaining;
}
```

The cost is that `_remaining` stays readable in a decompiler. That is the whole trade: a keep leaves the name in cleartext but needs no understanding of the accessor; the lockstep rename hides the name but relies on Nebula resolving the target. Prefer the rename wherever Nebula can resolve the binding, and fall back to a keep only when it cannot — a target reached by an accessor whose signature is ambiguous, or one you have reason to pin for other code that also reads it by name.

There is one newer wrinkle to watch. Recent runtimes add `[UnsafeAccessorType]`, which names the *target type itself* as a fully-qualified string — `"MyApp.Internal.Secret"` — so an accessor can reach a type it cannot even reference. That pushes a type name into a blob the same way `Name` pushes a member name, and it has the same requirement: if the type is renamed, the string must be rewritten in lockstep or kept. Treat a type-name string in an accessor exactly as you treat the member name — it is another handle the renamer has to honour.

## When it breaks

The honest failure modes are all about resolution, not the rewrite itself.

**Overloads.** If a target type has two methods with the same name and the accessor's signature matches both after renaming — because renaming can make two distinct members' *display* identical while their tokens differ — resolution can land on the wrong one or become ambiguous. In practice the signature disambiguates, but it is the case to test, because the runtime picks silently.

**The member is also read by reflection.** An accessor is not the only thing that might name `_remaining`. If some other code does `GetField("_remaining")`, renaming the field breaks *that* even though the accessor was rewritten correctly. The accessor is handled; the reflection string is a separate dependency you still have to keep or pin. The catalog of those is in [obfuscation, reflection and serialization pitfalls](https://delta1labs.com/blog/obfuscation-reflection-serialization-pitfalls/).

**You tested the wrong build.** The accessor resolves at first call, so a unit test that references the project and runs the un-obfuscated assembly will never see the break. The only test that catches it executes the *protected* output and calls the accessor path. Build the protected assembly, run it, and exercise every accessor at least once — a stale `Name` throws the instant the JIT touches it, and that is the signal you want in CI rather than in a customer's logs.

## The takeaway

`[UnsafeAccessor]` is the right tool for fast private-member access, and it is perfectly compatible with aggressive obfuscation — but only because the obfuscator understands it. The member name it binds to is a string in a custom-attribute blob, not a token, so it does not follow a rename for free. Nebula resolves each accessor by kind and signature and rewrites its `Name` argument in the same pass that renames the target, so the binding stays intact and the name stays out of cleartext. Where it cannot resolve the target — a cross-assembly member, an ambiguous signature — the name is already safe or you keep it deliberately. Then prove it on the protected build, because this is a failure the compiler will never show you and the first call always will. [Nebula.NET](https://delta1labs.com/products/nebula) renames, and [Glass.NET](https://delta1labs.com/products/glass) lets you read the blob back to confirm the name moved.

