Repository navigation
Description
If a devirtualized call on a boxed struct goes to the unboxed entry, the JIT replaces the box with a stack copy when canValueClassInstancePointerEscape returns false. For a property, C# emits [UnscopedRef] on the property rather than on the get_ accessor. Both the VM and crossgen2/ILC check only the accessor, so the returned ref points into a dead stack frame.
Minimal Repro
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
public interface I1
{
[UnscopedRef]
ref int Prop { get; }
}
public struct Struct1 : I1
{
public int Field;
[UnscopedRef]
public ref int Prop
{
[MethodImpl(MethodImplOptions.NoInlining)]
get => ref Field;
}
}
public class Program
{
public static int Main()
{
ref int r = ref EscapeRef();
r = 42;
Clobber();
Console.WriteLine(r);
return r == 42 ? 100 : 101;
}
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
private static ref int EscapeRef()
{
Struct1 s = new Struct1 { Field = 7 };
return ref BoxedRefEscape(s);
}
// The receiver is a heap box, so returning a ref into it is legal.
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
private static ref int BoxedRefEscape(Struct1 x) => ref ((I1)x).Prop;
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Clobber()
{
Span<int> spam = stackalloc int[64];
for (int i = 0; i < spam.Length; i++)
spam[i] = unchecked((int)0xDEADBEEF);
if (spam[0] != unchecked((int)0xDEADBEEF))
throw new Exception();
}
}Expected
42
Actual
-559038737
The program reads 0xDEADBEEF through a dangling ref. The box becomes a stack slot whose address is passed as this and then returned:
mov dword ptr [rsp+0x20], ecx
lea rcx, [rsp+0x20]
call [Struct1:get_Prop():byref:this]This also reproduces with crossgen2 (after removing AggressiveOptimization), and ILC generates the same code.
Regression?
The bug is reported to also reproduce on .NET 10.0.15; this was not re-verified. It reproduces on main.
Notes
This is the property version of Runtime_122099. impDevirtualizeCall calls gtTryRemoveBoxUpstreamEffects(..., BR_MAKE_LOCAL_COPY) when !canValueClassInstancePointerEscape(unboxedEntry). CEEInfo::canValueClassInstancePointerEscape (jitinterface.cpp) and CorInfoImpl.canValueClassInstancePointerEscape check only the method's own attributes. They should also check the owning property (or event) when the method is an accessor. If [UnscopedRef] is moved onto the get accessor, the output is correct.
Activity
dotnet-policy-service commentedon Nov 18, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
EgorBo commentedon Nov 18, 2026
Haven't checked this one, might be related to #130863 ?
Honor [UnscopedRef] on properties in canValueClassInstancePointerEsca…