Skip to content

Runtime crash when deserialising under NativeAOT #382

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Nolram12345 opened this issue Mar 5, 2025 · 2 comments
Open

Runtime crash when deserialising under NativeAOT #382

Nolram12345 opened this issue Mar 5, 2025 · 2 comments

Comments

@Nolram12345
Copy link

When attempting to deserialise a class containing a List of structs deriving from an interface (all tagged according to the MemoryPack documentation, i.e. with [MemoryPackUnion(tag, type)]), when compiling under NativeAOT, the following crash occurs:

Process terminated. Failed to create generic virtual method implementation

Declaring type: MemoryPack.Formatters.MemoryPackableFormatter`1<GameCore.Scenes.Scene>
Method name: Serialize
Instantiation:
  Argument 00000000: MemoryPack.Internal.ReusableLinkedArrayBufferWriter

   at System.RuntimeExceptionHelpers.FailFast(String, Exception, String, RhFailFastReason, IntPtr, IntPtr) + 0x249
   at Internal.Runtime.TypeLoader.TypeLoaderEnvironment.ResolveGenericVirtualMethodTarget(RuntimeTypeHandle, RuntimeMethodHandle) + 0x256
   at System.Runtime.TypeLoaderExports.<>c.<GVMLookupForSlotSlow>b__8_0(IntPtr, IntPtr, Object, IntPtr&) + 0x3e
   at System.Runtime.TypeLoaderExports.CacheMiss(IntPtr, IntPtr, RuntimeObjectFactory, Object) + 0x3c
   at System.Runtime.TypeLoaderExports.GVMLookupForSlotSlow(Object, RuntimeMethodHandle) + 0x68
   at System.Runtime.TypeLoaderExports.GVMLookupForSlot(Object, RuntimeMethodHandle) + 0x91
   at MemoryPack.MemoryPackWriter`1.WriteValue[T](T&) + 0x3d
   at MemoryPack.MemoryPackSerializer.Serialize[T](T&, MemoryPackSerializerOptions) + 0x342
   at Game.Main(String[] args) + 0xaa

This is after ensuring both a Serialize and Deserialize method are available (per #189 , in this case just with a dirty workaround by making a useless call to Serialize).

@MichalStrehovsky
Copy link

This is a bug in native AOT, tracked at dotnet/runtime#113664.

Once fixed, MemoryPack will run into the following exception:

throw new InvalidOperationException("Type implements IMemoryPackFormatterRegister but can not found RegisterFormatter. Type: " + type.FullName);

That code is not trimming safe - native AOT optimizes away reflection metadata even if the method exists.

I would suggest replacing the inexact1 interface method invocation with something trim and AOT safe, like:

static bool TryInvokeRegisterFormatter<T>()
{
    if (typeof(IMemoryPackFormatterRegister).IsAssignableFrom(typeof(T)))
    {
        // Will not trigger trimming or AOT warnings as of .NET 9 since the entire chain can be statically analyzed
        // You will see an AOT warning if you're still on .NET 8, but that's purely a point in time issue
        // More about intrinsically recognized AOT unsafe APIs: https://learn.microsoft.com/dotnet/core/deploying/native-aot/intrinsic-requiresdynamiccode-apis
        typeof(MemoryPackFormatterProvider).GetMethod("InvokeRegisterFormatter").MakeGenericMethod(typeof(T)).Invoke(null, null);
    }
}

static void InvokeRegisterFormatter<T>() where T : IMemoryPackFormatterRegister
{
    T.RegisterFormatter();
}

I would also recommend marking the project with <IsAotCompatible>true</IsAotCompatible> property so that trimming and AOT compatibility analyzers run on it and flag any other problematic code - I've not looked if there's more.

Footnotes

  1. The fact that the name matches doesn't mean it actually implements the method

@Nolram12345
Copy link
Author

@neuecc Would it be possible to get these fixes rolled into MemoryPack itself and perhaps have a warning about this in the readme?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants