Repository navigation
fix(crash): prevent malloc deadlocks in signal handling - #8271
Conversation
supervacuus
left a comment
There was a problem hiding this comment.
While the solution addresses atomic updates to a thread-id/signum slot via 16-byte atomics, it is limited to x86_64 and arm64. This might be fine for most targets; however, there are at least watches (the Cocoa SDK supports watchOS 8) within the supported range that could be running on older ARM. I am not sure how this translates to downstream usage; just meant as a fair warning.
The bigger point here is that atomicity in this PR is only considered for in-slot writes. However, slot publishing and associated races are currently not considered.
Two examples:
The current handler consume looks abstractly like this:
entry = atomic_load(&slot);
if (entry.tid == currentTid) {
atomic_store(&slot, zero);
}In this approach the 8 slots must be just for safety, because if you ever have situation where two threads reach the same slot (one in the handler, one in ignore_next), the current code allows for accidental overwrites:
- Slot
icontains {thread=A, signum=SIGSEGV} - Thread A receives a SIGBUS
- Handler on A loads slot
i. It sees thread=A but signum does not match, but it will still consume/clear the slot - Before A stores zero, thread B calls ingore_next(SIGSEGV)
- the ringbuffer also lands on Slot
iand stores {thread=B, signum=SIGSEGV} - Handler on A resumes and stores zero.
Nothing in the current code prevents this. If you say that this will never happen because both threads and singals raised are bounded enough, that is a fair assumption, but that should be documented.
Another example would be with multiple pending entries, where a stale entry can suppress a real crash because this code treats any matching entry for the thread as enough to ignore:
- Thread A calls
ignore_next(SIGSEGV) - No signal arrives and the entry becomes stale
- Later, thread A calls
ignore_next(SIGBUS) - Now two entries may exist for A
- old {A, SIGSEGV}
- new {A, SIGBUS}
- A real native SIGSEGV happens on A
The handler sees the old {A, SIGSEGV} and ignores the crash. That would be a false negative or unreported crash.
Again it is fair to assume that in your case a thread that calls ingore_next() will always receive a signal. And then this is a non-issue. But again, i would add this to an invariant list, rather than just expose a public function.
I like the simplicity of the current approach but without concrete boundaries it is short of underspecfying the problem. That can be the right choice and keeping things simple has merit. But it could also be that you need a protocol to claim slots explicitly and maybe even offer generational bounds so that if you have multiple entries for a single thread, you know which one is the youngest.
|
What's the status here? |
|
I changed the fix proposal to use pthread-specifics instead of a pre-allocated array. It's no longer limited to an arbitrary number of threads, but it resulted in significantly more noise... 😅 @supervacuus What do you think? |
supervacuus
left a comment
There was a problem hiding this comment.
I think this is solid and surprisingly small. A rebase, a basic description at the top, maybe a reference to the downstream iOS coverage, and addressing the two other comments, and I think we are good here.
We will have to rethink the entire managed workaround in the context of switching to KSCrash for v10, but this is not a topic for this PR, and I will ping you on that some other time.
Another thing I already experimented with is statically checking affected code parts to ensure they don't have any TLV relocations and expressing that as a test. But that is also not a merge condition for now.
|
I just read this once more and realized I overlooked: "but it resulted in significantly more noise"... What do you mean by that? Noisy/flaky tests? Noise from the bots? |
Noise in terms of code. Pity to have all this managed-only clutter here. :( Anyway, I'll try to come up with an integration test for sentry-dotnet that triggers a crash from an unmanaged thread that Mono hasn't attached to. |
sentrycrashcm_signal_ignore_next stored its pending signal in _Thread_local state, which the signal handler then accessed. Resolving that storage on an unmanaged thread can allocate memory and deadlock when the signal interrupts malloc. Allocate and register one ignore entry per thread before entering the signal handler, and publish entries through an append-only atomic list. The handler uses pthread_self and lock-free atomics to find and consume the pending signal without TLS, allocation, or locks. Consume the pending request on the next signal delivery while suppressing the crash report only when the signal number matches. Clear the entry identity when the thread exits so reused pthread values cannot inherit stale requests.
pthread_key_create can fail without producing a valid TSD key. Track whether initialization succeeded under pthread_once synchronization and return before pthread_getspecific or pthread_setspecific when either initialization step fails.
Document why entries published to the signal handler's append-only list cannot be freed after their owning threads exit.
Replace stdio-based integer and floating-point formatting used during crash reporting with stack-only converters that do not allocate or access TLS.
SENTRY_STRERROR_R used a function-local thread-local buffer. Its first access on an unmanaged thread can allocate memory while resolving TLS, which can deadlock or abort if the crashing thread already holds the malloc zone lock. Allocate the temporary buffer in the caller's stack frame instead. This keeps it alive through the enclosing logging call without requiring TLS.
Add a CrashE2E scenario that starts a native pthread, force-locks the default malloc zone, and sends SIGSEGV to itself. This reproduces failures where signal handling allocates while malloc is already locked. Verify that the captured event identifies SIGSEGV and marks the native thread as crashed.
62c4578 to
9af64e0
Compare
|
I added a malloc-zone-locked test intended to reproduce the original unsafe TLS access from an unmanaged thread. The test starts a raw pthread, locks the default malloc zone with In addition to the
I pushed fixes straight to this branch for now, but this has now grown way beyond the original signal-ignore TLS fix. What's the preferred way forward? Do you want to split up the fixes into separate PRs? $ TestSamples/CrashE2E/run-crash-e2e.sh \
--platform ios \
--reporter SentryCrash \
--scenarios malloc-zone-locked-signal \
--quiet-build
[09:26:20] Using iOS simulator: iPhone 17 / iOS 26.5 (0E9F44B5-3681-43F1-BBA8-8F9C44A454E3)
[09:26:20] Generating CrashE2E Xcode project.
⚙️ Generating plists...
⚙️ Generating project...
⚙️ Writing project...
Created project at /Users/jpnurmi/Projects/sentry/sentry-dotnet/modules/sentry-cocoa/TestSamples/CrashE2E/CrashE2E.xcodeproj
[09:26:20] Building CrashE2E-iOS (default).
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:iOS Simulator, arch:arm64, id:0E9F44B5-3681-43F1-BBA8-8F9C44A454E3, OS:26.5, name:iPhone 17 }
{ platform:iOS Simulator, arch:x86_64, id:0E9F44B5-3681-43F1-BBA8-8F9C44A454E3, OS:26.5, name:iPhone 17 }
[09:26:25] Installing CrashE2E-iOS on 0E9F44B5-3681-43F1-BBA8-8F9C44A454E3.
[09:26:25] iOS scenario: malloc-zone-locked-signal
[09:26:26] iOS crash launch exited with status 0. Waiting for termination.
[09:26:28] Relaunching iOS app to drain previous crash.
[09:26:40] Extracted event: /Users/jpnurmi/Projects/sentry/sentry-dotnet/modules/sentry-cocoa/TestSamples/CrashE2E/artifacts/ios-malloc-zone-locked-signal-event.json
[09:26:40] ✅ ios/malloc-zone-locked-signal assertions passed.
[09:26:40] ✅ Crash E2E completed. |
Only trim zeros from the fractional part so six-digit integer values remain intact. Add regression coverage for 100000 and 123000.
Awesome, thanks!
I have no problem with them staying in this PR. But I would defer to the maintainer's choice: @NinjaLikesCheez, @philprime, and @itaybre, wdyt, should the fixes in the logger and the stdio usage for number formatting in the serialization path be in separate PRs, or would additional change logs suffice? |
I think it's fine to throw them in here - while it's growing it's not too massive yet and the work is related. We also have stacks that could help. From my side, here is fine though. |
There was a problem hiding this comment.
LGTM. Thanks for adding an isolated CrashE2E scenario; that is exactly what that thing was introduced for. I would still appreciate a second reviewer: @itaybre, @philprime, @NinjaLikesCheez
📲 Install BuildsiOS
|
philprime
left a comment
There was a problem hiding this comment.
LGTM! Changes make sense, but please update the PR with the changes on main and make sure the changelog entry is in the right urnreleased section.
Performance metrics 🚀
|
| Revision | Plain | With Sentry | Diff |
|---|---|---|---|
| df67624 | 1225.12 ms | 1259.90 ms | 34.78 ms |
| 6e35062 | 1232.19 ms | 1262.91 ms | 30.73 ms |
| 220d7ef | 1238.77 ms | 1267.42 ms | 28.65 ms |
| 4b5a1d7 | 1235.27 ms | 1264.49 ms | 29.22 ms |
| 9319185 | 1223.24 ms | 1249.98 ms | 26.73 ms |
| d0b52d1 | 1227.31 ms | 1258.32 ms | 31.01 ms |
| b6b0d1d | 1236.69 ms | 1270.22 ms | 33.52 ms |
| 5b1c31e | 1221.35 ms | 1246.14 ms | 24.79 ms |
| 9787f05 | 1233.67 ms | 1269.00 ms | 35.33 ms |
| 29d1b7f | 1220.58 ms | 1254.14 ms | 33.56 ms |
App size
| Revision | Plain | With Sentry | Diff |
|---|---|---|---|
| df67624 | 24.14 KiB | 1.14 MiB | 1.12 MiB |
| 6e35062 | 24.14 KiB | 1.22 MiB | 1.20 MiB |
| 220d7ef | 24.14 KiB | 1.17 MiB | 1.14 MiB |
| 4b5a1d7 | 24.14 KiB | 1.22 MiB | 1.20 MiB |
| 9319185 | 24.14 KiB | 1.16 MiB | 1.13 MiB |
| d0b52d1 | 24.14 KiB | 1.15 MiB | 1.13 MiB |
| b6b0d1d | 24.14 KiB | 1.18 MiB | 1.16 MiB |
| 5b1c31e | 24.14 KiB | 1.24 MiB | 1.22 MiB |
| 9787f05 | 24.14 KiB | 1.18 MiB | 1.15 MiB |
| 29d1b7f | 24.14 KiB | 1.26 MiB | 1.23 MiB |
Previous results on branch: jpnurmi/fix/tls
Startup times
| Revision | Plain | With Sentry | Diff |
|---|---|---|---|
| 0de6b5f | 1226.14 ms | 1252.87 ms | 26.73 ms |
| 41746bd | 1230.94 ms | 1259.73 ms | 28.79 ms |
| 56d93e3 | 1214.42 ms | 1232.06 ms | 17.64 ms |
App size
| Revision | Plain | With Sentry | Diff |
|---|---|---|---|
| 0de6b5f | 24.14 KiB | 1.29 MiB | 1.27 MiB |
| 41746bd | 24.14 KiB | 1.29 MiB | 1.27 MiB |
| 56d93e3 | 24.14 KiB | 1.29 MiB | 1.27 MiB |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Want reviews to match your repository better? Bugbot Learning can learn team-specific rules from PR activity. A team admin can enable Learning in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 89714d7. Configure here.
Conflicts: Sources/SentryCrash/Recording/Monitors/SentryCrashMonitor_Signal.c Sources/SentryCrash/Recording/Tools/SentryCrashJSONCodec.c TestSamples/CrashE2E/App/Sources/CrashE2ECrashTriggers.swift TestSamples/CrashE2E/App/Sources/CrashE2ERuntime.swift TestSamples/CrashE2E/Runner/Sources/CrashE2ERunner/Config.swift TestSamples/CrashE2E/Runner/Sources/CrashE2ERunner/EventAssertions.swift
|
Merged the latest $ TestSamples/CrashE2E/run-crash-e2e.sh \
--platform ios \
--reporter SentryCrash \
--scenarios malloc-zone-locked-signal \
--quiet-build
[11:07:45] Using iOS simulator: iPhone 17 / iOS 26.5 (0E9F44B5-3681-43F1-BBA8-8F9C44A454E3)
[11:07:45] Generating CrashE2E Xcode project.
⚙️ Generating plists...
⚙️ Generating project...
⚙️ Writing project...
Created project at /Users/jpnurmi/Projects/sentry/sentry-dotnet/modules/sentry-cocoa/TestSamples/CrashE2E/CrashE2E.xcodeproj
[11:07:45] Building CrashE2E-iOS (default).
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:iOS Simulator, arch:arm64, id:0E9F44B5-3681-43F1-BBA8-8F9C44A454E3, OS:26.5, name:iPhone 17 }
{ platform:iOS Simulator, arch:x86_64, id:0E9F44B5-3681-43F1-BBA8-8F9C44A454E3, OS:26.5, name:iPhone 17 }
[11:07:49] Installing CrashE2E-iOS on 0E9F44B5-3681-43F1-BBA8-8F9C44A454E3.
[11:07:50] iOS scenario: malloc-zone-locked-signal
[11:07:51] iOS crash launch exited with status 0. Waiting for termination.
[11:07:52] Relaunching iOS app to drain previous crash.
[11:08:04] Extracted event: /Users/jpnurmi/Projects/sentry/sentry-dotnet/modules/sentry-cocoa/TestSamples/CrashE2E/artifacts/ios-malloc-zone-locked-signal-event.json
[11:08:04] ✅ ios/malloc-zone-locked-signal assertions passed.
[11:08:04] ✅ Crash E2E completed.And with sentry-dotnet (WIP, depends on this fix): ::group::Run iOS app (TestArg=UnmanagedThreadCrash)
...
[+] sentry-dotnet/integration-test/ios.Tests.ps1 70.14s (69.4s|122ms)
Tests completed in 70.14s
Tests Passed: 1, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0 |
* fix(native): Enter signal handler state before handling a crash
A crash while the crashed thread holds the macOS malloc lock aborted
the process inside the native crash handler, before the daemon could
send the report:
_os_unfair_lock_recursive_abort
_xzm_xzone_malloc_freelist_outlined
dyld::ThreadLocalVariables::instantiateVariable
_tlv_get_addr
sentry__scope_save_active_trace
The scope skips its thread-locals and locks on the thread that entered
the signal handler state. The inproc, breakpad and crashpad handlers
enter it, but the native handler did not.
Ref: getsentry/sentry-cocoa#8271
* fix(scope): Keep thread-local access behind signal handler checks
The first thread-local access on a thread allocates on macOS. Clang
hoisted the inlined `g_scope_access` access above the
`sentry__block_for_signal_handler()` check, so crash handling still
called `_tlv_get_addr` with the malloc lock held:
_os_unfair_lock_recursive_abort
_tlv_get_addr
sentry__scope_save_active_trace
Read the thread-locals through non-inlined accessors that cannot be
hoisted above the check.
Ref: getsentry/sentry-cocoa#8271
* fix: Format numbers with stb_sprintf on Apple platforms
libc `vsnprintf` allocates while formatting doubles, which aborted
crash handling with the malloc lock held:
_os_unfair_lock_recursive_abort
__Balloc_D2A
__dtoa
sentry__snprintf_c
sentry__jsonwriter_write_double
Use the stack-only `stbsp_vsnprintf` that Linux already uses.
Ref: getsentry/sentry-cocoa#8271
* test(native): Add a crash test with the allocator locked
`sentry_test_malloc_lock` builds the integration fixture with a
`crash-malloc-locked` scenario, which locks the allocator on a new
thread and crashes there. It locks the default malloc zone on macOS
and the process heap on Windows, and replaces `malloc` with a blocking
version on glibc. Other configurations exit with 77 to skip.
Ref: getsentry/sentry-cocoa#8271
* Update CHANGELOG.md
* test(native): Skip the malloc-locked crash test on Windows
`HeapLock` is recursive for its owner thread, so the crashed thread
could still allocate in the exception filter, and the test could not
catch allocations in the crash handler on Windows. Drop the Windows
lock from the fixture and skip the test there.
Ref: #2336 (comment)

📜 Description
Prevent allocator-dependent operations during signal handling:
_Thread_localsignal-ignore state with pthread-specific entries registered before the signal handler and published through an append-only atomic list.snprintf-based JSON number formatting with stack-only converters.SENTRY_STRERROR_Rbuffer with caller stack storage.Add a CrashE2E scenario that starts a raw pthread, locks the default malloc zone, and sends
SIGSEGVto itself.💡 Motivation and Context
A signal can interrupt a thread while the malloc zone is locked. Lazy TLS resolution and unsafe formatting may allocate or acquire allocator locks, deadlocking before the crash report is persisted.
The malloc-zone-locked reproducer exposed each of these operations after the preceding one was fixed.
Close: #8134
💚 How did you test it?
malloc-zone-locked-signalCrashE2E scenario on an iOS simulator.📝 Checklist
You have to check all boxes before merging:
sendDefaultPIIis enabled.