DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

Why LibraryImport survives obfuscation

Migrating from [DllImport] to [LibraryImport] is sold as a performance story — ahead-of-time-friendly marshalling, no IL stub generated at runtime, trim-safe. There is a quieter consequence that matters just as much if you obfuscate: the source generator changes where the native entry-point name lives, and in doing so it turns P/Invoke from one of the most rename-hostile surfaces in .NET into one of the safest.

The real question

A native call has exactly one string that must survive: the export name the operating system loader looks up. With classic [DllImport], that string is often your method's own name. Write [DllImport("user32.dll")] static extern int MessageBoxW(...) with no EntryPoint, and the runtime uses the managed name MessageBoxW as the export to resolve. Rename the method and you have renamed the lookup key — the call throws EntryPointNotFoundException at runtime, with nothing wrong at build time. (That path, and the rule an obfuscator follows for it, is the subject of obfuscating P/Invoke without breaking interop.)

So the question for the source-generated path is simply: after LibraryImportGenerator runs, where does that entry-point string end up — in an identifier the renamer will touch, or somewhere it will not?

The mechanism, shown

Start with what you write. A [LibraryImport] declaration is a partial method with no body; you never write the marshalling.

internal static partial class Native
{
    [LibraryImport("kernel32.dll", EntryPoint = "GetFileAttributesW",
                   StringMarshalling = StringMarshalling.Utf16)]
    internal static partial uint GetFileAttributes(string lpFileName);
}
Enter fullscreen mode Exit fullscreen mode

At compile time the Roslyn source generator fills the body in. The emitted code is not magic — it is plain C# you can read, and it has two parts: a marshalling stub (the body of your partial method) and a nested local function named __PInvoke that carries the actual [DllImport]. Abbreviated to its essence:

internal static partial class Native
{
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
    internal static unsafe partial uint GetFileAttributes(string lpFileName)
    {
        uint __retVal;
        // Marshal: pin the managed string as native UTF-16.
        fixed (void* __lpFileName_native = &Marshal.GetPinnableReference(lpFileName))
        {
            __retVal = __PInvoke((ushort*)__lpFileName_native);
        }
        return __retVal;

        // The real native call — a generated local function.
        [global::System.Runtime.InteropServices.DllImportAttribute("kernel32.dll",
            EntryPoint = "GetFileAttributesW", ExactSpelling = true)]
        static extern unsafe uint __PInvoke(ushort* lpFileName);
    }
}
Enter fullscreen mode Exit fullscreen mode

Read where the entry-point name went. It is not on your GetFileAttributes method anymore — that method now has a managed body and no DllImport at all. It moved down into the generated __PInvoke local function, as the EntryPoint = "GetFileAttributesW" argument of a DllImportAttribute, with ExactSpelling = true so the runtime resolves that exact export and never probes for an A/W suffix. The native name is now a string literal baked into an attribute, one level removed from any name you declared.

The decisive case is when you write no EntryPoint. The generator still cannot leave it implied, because the function that actually carries the [DllImport] is called __PInvoke, not your method — so an implied-name resolution would look up the export "__PInvoke", which is wrong. To avoid that, the generator snapshots your method name into an explicit EntryPoint at generation time:

// You wrote: [LibraryImport("kernel32.dll")]
//            internal static partial uint GetTickCount();
// The generator emits, inside the body:
[global::System.Runtime.InteropServices.DllImportAttribute("kernel32.dll",
    EntryPoint = "GetTickCount", ExactSpelling = true)]
static extern uint __PInvoke();
Enter fullscreen mode Exit fullscreen mode

That is the whole insight. Where classic [DllImport] leaves the native name implied by a managed identifier, the source generator freezes it as a literal before the obfuscator ever runs. The coupling that makes classic P/Invoke rename-hostile is gone by the time Nebula opens the assembly.

Now obfuscate. GetFileAttributes becomes a, the class Native becomes X, the generated __PInvoke local function is mangled, the parameters are stripped of their names. All of that is ordinary IL in the same module, so Nebula renames it in a single consistent pass — the call site a still invokes the same mangled local function, which still points at the same DllImportAttribute. The EntryPoint = "GetFileAttributesW" argument is a custom-attribute blob value, and Nebula renames metadata identifiers without rewriting attribute values, so that literal rides through untouched. The native loader is handed the string "GetFileAttributesW" exactly as before and resolves the same export. It never saw the managed name, so the rename is invisible to it.

How it applies

Because the entry point is already a literal, the default Nebula configuration renames your whole interop layer with no keep-list for the P/Invoke names themselves:

{
  "schemaVersion": 1,
  "inputs": [ "bin/Release/net8.0/Acme.Interop.dll" ],
  "outputDirectory": "protected",
  "encryptStrings": true,
  "controlFlowObfuscation": true,
  "renaming": {
    "rules": [ { "pattern": "Acme.Interop.*", "action": "rename" } ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Two boundaries still have to be respected, and both are data, not names. Struct layout: any [StructLayout] type that crosses the boundary is marshalled positionally, so the field names rename freely but the field order, Pack, explicit [FieldOffset] values, and per-field [MarshalAs] directives are frozen — the generated glue and the native code both read the struct by byte offset.

[StructLayout(LayoutKind.Sequential)]
internal struct FileInfo       // names free, layout frozen
{
    public uint Attributes;    // offset 0
    public long Size;          // offset 8 (after padding)
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public byte[] Reserved;    // MarshalAs is load-bearing
}
Enter fullscreen mode Exit fullscreen mode

Nebula treats such a type as layout-frozen and name-free, and will not reorder its fields even though it reorders members of ordinary classes. Custom marshallers: a [MarshalUsing(typeof(MyMarshaller))] names a type whose ConvertToUnmanaged/ConvertToManaged methods the generated glue calls directly in IL — so there is a real managed caller and the marshaller stays reachable and renames consistently; nothing special to configure.

Then verify, because interop breakage is a runtime event, never a build error. Open the protected assembly in Glass.NET and confirm the generated [DllImport] still reads EntryPoint = "GetFileAttributesW" with ExactSpelling = true, then run the real native call against the obfuscated binary. A test that mocks the native layer proves nothing here — the entire risk lives in the real marshalling stub the generator produced.

When it breaks

The guarantee is specifically that renaming is safe. It says nothing about the migration gotchas [LibraryImport] brings on its own. Because the generator always emits ExactSpelling = true and never appends an A/W suffix for you, the EntryPoint string must name the real export precisely — if you wrote EntryPoint = "MessageBox" expecting the runtime to find MessageBoxW, it will not, obfuscated or not. Fix that in the source, not in the protector.

The other edge is pruning, not renaming. If an interop type is internal and nothing in your managed code calls it — it exists only to be invoked reflectively or through a hand-written dispatch — the reachability pass can read it as dead. That is the ordinary reachability caveat, and the fix is a keep rule against removal, which still leaves the type in the rename ruleset so its identifiers change. The entry point itself needs no such rule, because it is a literal, not a reference.

Takeaway

Classic [DllImport] made a managed identifier double as the native lookup key, which is why obfuscating it has always meant knowing which method names were load-bearing. The [LibraryImport] source generator does that work for you: it lifts the entry-point name out of your method and freezes it as a string literal in a generated attribute before the obfuscator ever runs. So the modern P/Invoke surface is one you can hand to Nebula whole — rename the wrapper, the class, the parameters, the generated stub — keep struct layout and [MarshalAs] frozen, and the native call binds exactly as it did before.

Top comments (0)