Skip to content

Commit 13312b6

Browse files
rolfbjarneCopilot
andauthored
[ObjCRuntime] Fix GC race in RetainAndAutoreleaseHandle causing intermittent SIGSEGV (#24814)
After obj.GetHandle() extracts the native handle, the GC can finalize obj (a NativeObject, not protected by ObjC runtime reference tracking) before DangerousRetain executes. This causes a use-after-free when the finalizer calls CFRelease on the handle before it's been retained. Add GC.KeepAlive(obj) to ensure the managed wrapper survives until after the retain+autorelease has completed. This fixes intermittent SIGSEGV crashes in CGBitmapContext.CreateAdaptive tests (and potentially any other caller of RetainAndAutoreleaseHandle with NativeObject-derived types). --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 9cf7f59 commit 13312b6

File tree

2 files changed

+3
-4
lines changed

2 files changed

+3
-4
lines changed

src/ObjCRuntime/Runtime.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2337,9 +2337,9 @@ internal static NativeHandle RetainAndAutoreleaseHandle (INativeObject? obj)
23372337
{
23382338
if (obj is null)
23392339
return NativeHandle.Zero;
2340-
#pragma warning disable RBI0014
2341-
return RetainAndAutoreleaseHandle (obj.GetHandle ());
2342-
#pragma warning restore RBI0014
2340+
var rv = RetainAndAutoreleaseHandle (obj.GetHandle ());
2341+
GC.KeepAlive (obj);
2342+
return rv;
23432343
}
23442344

23452345
/// <summary>Retain and autorelease the given handle, then return the handle.</summary>

tests/cecil-tests/HandleSafety.KnownFailures.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,6 @@ public partial class HandleSafetyTest {
149149
"ObjCRuntime.RegistrarHelper.INativeObject_managed_to_native (System.IntPtr, ObjCRuntime.INativeObject, ObjCRuntime.INativeObject, System.Boolean)",
150150
"ObjCRuntime.Runtime.ConvertSmartEnumToNSString (System.IntPtr)",
151151
"ObjCRuntime.Runtime.GetHandleForINativeObject (System.IntPtr)",
152-
"ObjCRuntime.Runtime.RetainAndAutoreleaseHandle (ObjCRuntime.INativeObject)",
153152
"ObjCRuntime.Runtime.RetainAndAutoreleaseNativeObject (ObjCRuntime.INativeObject)",
154153
"ObjCRuntime.Runtime.RetainAndAutoreleaseNSObject (Foundation.NSObject)",
155154
"ObjCRuntime.Runtime.RetainNativeObject (ObjCRuntime.INativeObject)",

0 commit comments

Comments
 (0)