Skip to content

Make GC stack walking robust in the presence of unmanaged byrefs with extended lifetime #75865

@jkotas

Description

@jkotas

Consider this example:

byte* ptr = Marshal.AllocHGlobal(...);
ref byte b = ref Unsafe.AsRef<byte>(ptr);
Use(ref b);
Marshal.FreeHGlobal(ptr);

// `b` never used again in the code. Let's assume JIT decided to extend the `b` variable lifetime till end of the method.

object o = new object(); // Let's assume that the GC run out of space, allocated a new memory block using virtual alloc, and the OS memory manager decides to give it the memory block that was just freed by `Marshal.FreeHGlobal`.

GC.Collect(); // The GC may assert or crash because of it will see `byref b` pointing into middle of the segment where no valid byrefs are supposed to point to

Context: #75857 (comment)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions