[ObjCRuntime] Fix GC race in RetainAndAutoreleaseHandle causing intermittent SIGSEGV#24814
Conversation
…mittent SIGSEGV 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>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
✅ [CI Build #7fc7c65] Build passed (Build packages) ✅Pipeline on Agent |
✅ [PR Build #7fc7c65] Build passed (Detect API changes) ✅Pipeline on Agent |
✅ API diff for current PR / commitNET (empty diffs)✅ API diff vs stableNET (empty diffs)ℹ️ Generator diffGenerator Diff: vsdrops (html) vsdrops (raw diff) gist (raw diff) - Please review changes) Pipeline on Agent |
✅ [CI Build #7fc7c65] Build passed (Build macOS tests) ✅Pipeline on Agent |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
🚀 [CI Build #7fc7c65] Test results 🚀Test results✅ All tests passed on VSTS: test results. 🎉 All 156 tests passed 🎉 Tests counts✅ cecil: All 1 tests passed. Html Report (VSDrops) Download macOS tests✅ Tests on macOS Monterey (12): All 5 tests passed. Html Report (VSDrops) Download Pipeline on Agent |
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).