Repository navigation
Description
Description
In the CoreCLR interpreter, an exception filter that reads this (ldarg.0) gets null when both of these are true:
- The method's generic context comes from
this(CORINFO_GENERICS_CTXT_FROM_THIS, for example an instance method of a generic class instantiated over a reference type), or the method is an instance method marked[MethodImpl(MethodImplOptions.Synchronized)]. - The method body never stores to
thisor takes its address (nostarg 0and noldarga 0).
The filter then throws a NullReferenceException. The runtime treats a filter that throws as returning false, so the catch clause is skipped and the original exception propagates. No error is reported. AppDomain.FirstChanceException is the only visible sign of the NullReferenceException.
Here is how it shows up in practice. On iOS and tvOS, the interpreter runs all non-R2R code. In a Debug build, user assemblies are excluded from the R2R composite, so all of the app's own code runs in the interpreter. Debug C# builds emit async state machines as classes and hoist locals, including catch (X e) variables, into fields. So an ordinary
catch (SomeException e) when (Classify(e)) { ... }inside an async method of a generic class, or inside a generic async method, with a reference-type T, compiles to a filter that runs ldarg.0; ldloc; stfld <e>5__1 inside <M>d__N<T>.MoveNext. That filter silently stops matching in a Debug build on the iOS simulator or a device. Release (NativeAOT), Release (CoreCLR + composite R2R) and desktop JIT all behave correctly.
Reproduction Steps
Here is a minimal net11.0-ios app. It also builds as a plain net11.0 console app; on desktop this is the JIT control.
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
public static class Program
{
static void Main()
{
// Run off the UI thread so Task.Yield/GetResult can't deadlock before UIApplication.Main.
Task.Run(Run).GetAwaiter().GetResult();
Environment.Exit(0);
}
static void Run()
{
AppDomain.CurrentDomain.FirstChanceException += (_, e) => Console.WriteLine(" first chance: " + e.Exception.GetType().Name);
Check("G<string>.InstanceReadsField (sync)", () => new G<string>().InstanceReadsField());
Check("G<int>.InstanceReadsField (sync)", () => new G<int>().InstanceReadsField());
Check("G<string>.AsyncCatchVar (async, Debug C#)", () => G<string>.AsyncCatchVar().GetAwaiter().GetResult());
Check("S.SynchronizedReadsField (non-generic)", () => new S().SynchronizedReadsField());
}
static void Check(string name, Func<bool> f)
{
string r;
try { r = f() ? "PASS" : "FAIL (wrong clause)"; }
catch (Exception e) { r = "FAIL (escaped: " + e.GetType().Name + ")"; }
Console.WriteLine($"{r} {name}");
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Throw() => throw new InvalidOperationException("boom");
}
public sealed class G<T>
{
int _field = 1;
// No async and no catch variable: the filter only reads this._field.
public bool InstanceReadsField()
{
try { Program.Throw(); return false; }
catch (InvalidOperationException) when (_field != 0) { return true; }
}
// The shape that is hit in real code: in a Debug C# build the filter stores `e` into a field of the
// state machine class, through `this`.
public static async Task<bool> AsyncCatchVar()
{
try { Program.Throw(); await Task.Yield(); return false; }
catch (InvalidOperationException e) when (e.Message.Length > 0) { return true; }
}
}
public sealed class S
{
int _field = 1;
[MethodImpl(MethodImplOptions.Synchronized)]
public bool SynchronizedReadsField()
{
try { Program.Throw(); return false; }
catch (InvalidOperationException) when (_field != 0) { return true; }
}
}Build and run it on the iOS simulator in Debug. This is the default configuration: CoreCLR, the interpreter for user code, and BCL code in the composite R2R image.
dotnet build -c Debug -r iossimulator-arm64
xcrun simctl install <udid> bin/Debug/net11.0-ios/iossimulator-arm64/<App>.app
xcrun simctl launch --console-pty <udid> <bundle id>
(The iOS project needs <ValidateSceneManifest>false</ValidateSceneManifest>, since Main exits before any UI starts.)
The fuller test app I used has 19 C# cases plus a Reflection.Emit probe. It is attached / available on request.
Expected behavior
Every case prints PASS. The filter sees the real this, evaluates to true, and the catch clause runs. Desktop JIT, NativeAOT and CoreCLR+R2R on iOS all do this.
Actual behavior
On the iOS simulator in Debug (the interpreter):
first chance: InvalidOperationException
first chance: NullReferenceException
FAIL (escaped: InvalidOperationException) G<string>.InstanceReadsField (sync)
first chance: InvalidOperationException
PASS G<int>.InstanceReadsField (sync)
first chance: InvalidOperationException
first chance: NullReferenceException
first chance: InvalidOperationException
FAIL (escaped: InvalidOperationException) G<string>.AsyncCatchVar (async, Debug C#)
first chance: InvalidOperationException
first chance: NullReferenceException
FAIL (escaped: InvalidOperationException) S.SynchronizedReadsField (non-generic)
Full matrix from the test app (Debug, iOS simulator):
| Case | Interpreter result |
|---|---|
async method of G<string>, catch (X e) when (e…) (Debug C#) |
FAIL, NRE in filter |
generic async method M<string>, same |
FAIL |
async method of G<string>, catch var, filter doesn't use it (when (True())) |
FAIL (the filter still stores e through this) |
async method of G<string>, throw after await |
FAIL |
async instance method of G<string> |
FAIL |
async method of G<string>, no catch var, filter reads a hoisted local |
FAIL |
sync instance method of G<string>, no catch var, filter reads this._field |
FAIL |
non-generic [Synchronized] instance method, filter reads this._field |
FAIL |
async method of G<string>, catch var, no filter |
PASS |
async method of G<string>, no catch var, when (True()) (no ldarg.0 in filter) |
PASS |
sync static method of G<string>, catch var (it's a plain local) |
PASS |
G<int> / M<int> (unshared code) |
PASS |
| non-generic async method, catch var | PASS |
filters using typeof(T) (static, instance, generic method, async) |
PASS (the generic context is copied correctly) |
same app, C# Optimize=true (struct state machines, no hoisting) |
async cases PASS; the sync this._field and [Synchronized] cases still FAIL |
The decisive probe uses Reflection.Emit, which the interpreter supports. It builds a generic class Dyn<T> with two instance methods whose filter is just pop; ldarg.0; stsfld Seen.This; ldc.i4.1; endfilter. The second method also starts with ldarg.0; starg.s 0:
FAIL (filter saw this == null) Dyn<String>.Plain
PASS (filter saw the right this) Dyn<String>.WithThisStore (method also does starg.s 0)
PASS (filter saw the right this) Dyn<Int32>.Plain
PASS (filter saw the right this) Dyn<Int32>.WithThisStore
Adding a store to this elsewhere in the method fixes the filter. That matches the root cause below.
Regression?
Not a regression from a working CoreCLR build, as far as I know. CoreCLR on iOS is new in .NET 11, and I have not tested an earlier CoreCLR interpreter build. Moving an iOS app from Mono (the .NET 10 default) to CoreCLR in .NET 11 exposes it.
Known Workarounds
- Classify in the catch block and
throw;, instead of using a filter that touchesthis/ hoisted locals. - Build the app's own assemblies with R2R in Debug (
-p:FilterReadyToRunAssemblies=false) so they don't run in the interpreter. - Compile the C# with optimizations (this only helps the async/hoisting variant).
Configuration
- .NET SDK 11.0.100 (commit 297acf930f), workload set 11.0.100.1,
iosworkload manifest 27.2.11039/11.0.100 (Microsoft.iOS.Sdk.net11.0_27.2 27.2.11039) - Runtime pack
Microsoft.NETCore.App.Runtime.iossimulator-arm6411.0.0, built from dotnet/dotnet 297acf930fb0f5c07fd4e51d78e521b4ad2e5d1f = dotnet/runtime deae2e3 - iOS Simulator 18.6 (22G86), iPhone 16 Pro,
iossimulator-arm64; Xcode 27.2 (27B52); macOS 27.2 on Apple silicon RuntimeInformation.FrameworkDescription=.NET 11.0.0;RuntimeFeature.IsDynamicCodeCompiled= false (interpreter),IsDynamicCodeSupported= true
Control results (same app, same simulator):
| Build | Engine for app code | Result |
|---|---|---|
| Debug (default) | CoreCLR interpreter | 8 C# cases + the Dyn<String>.Plain probe fail |
Debug, C# Optimize=true |
CoreCLR interpreter | 2 fail (sync this._field, [Synchronized]) + the Dyn<String>.Plain probe |
Debug, FilterReadyToRunAssemblies=false |
CoreCLR + composite R2R | all C# cases pass; the Emit probe Dyn<String>.Plain (dynamic code, so always interpreted) still fails |
| Release (default CoreCLR) | CoreCLR + composite R2R | all C# cases pass; Dyn<String>.Plain still fails |
Release, PublishAot=true |
NativeAOT | all pass (the Emit probe is skipped) |
desktop net11.0 console, osx-arm64 |
RyuJIT | all pass, Emit probe included |
So Release CoreCLR apps on iOS and tvOS are exposed too, for any method that ends up in the interpreter rather than in R2R code. Dynamic code is one such case.
I could not run the desktop interpreter (DOTNET_Interpreter / DOTNET_InterpMode). The shipped osx-arm64 runtime is a Release build and doesn't include the interpreter (FEATURE_INTERPRETER is on only for Debug/Checked desktop builds, per src/coreclr/clrfeatures.cmake). A Checked desktop runtime with DOTNET_InterpMode=1 should reproduce it, but that is untested.
Other information
Root cause (as far as I can tell from source)
Sources are pinned to dotnet/runtime deae2e32bf0e018e09d64597b7c59b62b73bb3ce, the runtime in 11.0.0. All of the relevant code is unchanged on main at 9de2163, the latest change to compiler.cpp when this was written, and on release/11.0.
-
A
thisshadow copy is planned up front. InCreateILVars, compiler.cpp L2462, a method whose generic context comes fromthis(CORINFO_GENERICS_CTXT_FROM_THIS, set by jitinterface.cpp L7705 for shared instance methods on generic classes), or a synchronized instance method, getsm_shadowCopyOfThisPointerHasVar = true. The incomingthisis allocated asm_paramArgIndexat offset 0 (L2505). IL arg 0 (var 0) becomes a separate shadow slot allocated after the IL locals, at some offsetS != 0(L2559-L2566). -
Filter code bakes var 0's offset in at import time. A filter funclet runs on its own frame, so IL locals and args are reached through the parent frame:
INTOP_LOAD_FRAMEVAR(interpexec.cpp L1639) followed by anldindwhose displacement is the var's currentm_pVars[var].offset. SeeEmitLoadVar, L3075-L3082;EmitStoreVar(L3110-L3115) andEmitLdLocA(L7080+) do the same. Soldarg.0in a filter is emitted as "load parent frame +S".EmitLoadVardoes not setm_shadowCopyOfThisPointerActuallyNeeded. OnlyEmitStoreVar(L3102) andEmitLdLocA(L7075) set it. -
After codegen the shadow copy is elided, but the baked offset is not fixed up. At the end of
InterpCompiler::GenerateCode(L11787-L11805), if nothing stored tothisor took its address, noMOV_P param -> var0is inserted. Insteadm_pVars[0].offset = 0aliases var 0 back onto the realthis. Code outside filters refers to var 0 by index, so it picks up offset 0 and works. The filter'sldindstill has displacementS. Nothing ever assigns slotS. It lies inside the rangeINTOP_INITLOCALSalways zeroes (m_ILLocalsSizeis computed after the shadow allocation, L2593-L2594), so the filter deterministically reads null.
That explains every row of the matrix:
typeof(T)in a filter works: the generic context is reloaded fromm_paramArgIndexat filter entry (L9080-L9096), and that offset never moves.G<int>, non-generic code and static methods have no shadow copy.- Debug C# async methods fail because the filter's
stfld <e>5__1/ldfld <x>5__1goes throughldarg.0on the state-machine class. WithOptimize=truethe state machine is a struct (byrefthis, context via an instantiating stub, notFROM_THIS) and the locals aren't hoisted, so those cases pass. ldarg.0; starg.s 0anywhere in the method setsm_shadowCopyOfThisPointerActuallyNeeded, so slotSis initialized and the filter works (the Reflection.Emit probe).[Synchronized]non-generic instance methods hit the same path through them_isSynchronized && hasThisbranch.
Possible fixes, for the area owners to judge:
- In the filter branch of
EmitLoadVar, whenvar == 0 && m_shadowCopyOfThisPointerHasVar, setm_shadowCopyOfThisPointerActuallyNeeded = true. (EmitStoreVarandEmitLdLocAalready set the flag before their filter branches.) Simplest: slotSis then initialized in the prolog. - Or defer the frame-var displacement until offsets are final, for example by keeping the var index in the instruction and resolving it when the final code is emitted.
I have not verified a fix by building the runtime.
Related issues searched
I searched dotnet/runtime issues and PRs for interpreter + filter / funclet / shadow this / generic context / NullReferenceException. I found no duplicate. The nearest are unrelated: #120811 "Fix interpreter EH when exception escapes filter funclet" (merged Oct 2025, about exceptions thrown out of filters, not this offset problem), #116046 "Interpreter EH implementation" (introduced INTOP_LOAD_FRAMEVAR), and #47624 (a Mono interpreter filter recursion bug).
Activity
dotnet-policy-service commentedon Nov 16, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
dotnet-policy-service commentedon Nov 16, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @BrzVlad, @janvorli
See info in area-owners.md if you want to be subscribed.
Fix fetching of this pointer from interpreted filters (dotnet#137778)