Skip to content

Simple Native AOT program crashes with "Failed to create generic virtual method implementation" #414

@samuelmatn

Description

@samuelmatn

We have an application which is Native AOT compiled and uses MemoryPack to serialize data for logging. Recently, we made some changes in the logic. Some data types previously used throught the logic became used only for logging. To my surprise, Native AOT build wasn't setting most of the values in the affected data types. I thought the compiler must have incorrectly optimized away setting the values.

As a workaround, I tried running a quick serialization-deserialization test on startup and checking that all the values are equal. However, after the change, the application started to crash on startup.

Luckily, the latter problem is reproducible with a small example. Consider the following data type being serialized:

using MemoryPack;

namespace MemoryPackNativeAotCrash;

[MemoryPackable]
public partial class MyClass
{
    public int Value { get; }

    public MyClass(int value)
    {
        Value = value;
    }
}

We can create a simple program to peform serialization, deserialization and an equality test:

using MemoryPack;
using MemoryPackNativeAotCrash;
using Microsoft;

MyClass expected = new(value: 10);
byte[] buffer = MemoryPackSerializer.Serialize(expected);
MyClass? actual = MemoryPackSerializer.Deserialize<MyClass>(buffer);
Assumes.NotNull(actual);
Assumes.True(expected.Value == actual.Value);

When this program is Native AOT compiled and executed, it crashes immediately with the following error:

Declaring type: MemoryPack.Formatters.MemoryPackableFormatter`1<MemoryPackNativeAotCrash.MyClass>
Method name: Serialize
Instantiation:
  Argument 00000000: MemoryPack.Internal.FixedArrayBufferWriter

The complete example can be found here: https://github.com/samuelmatn/dotnet-bug-reports/tree/main/MemoryPackNativeAotCrash

Our Windows builds currently use Visual Studio 2022 Build Tools 17.14.7.

Can MemoryPack do something to help out the compiler or is this a bug in Native AOT?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions