Skip to content

Keep the crash report header out of localtime() and stdio - #755

Merged
fcostaoliveira merged 4 commits into
masterfrom
fix/681-crash-handler-deadlock
Oct 17, 2026
Merged

fcostaoliveira merged 4 commits into
masterfrom
fix/681-crash-handler-deadlock

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

The crash handler can lose its whole bug report. crash_handler() called localtime() and strftime() before printing anything. When the crash interrupts a thread that holds the malloc or time zone lock, the handler deadlocks before the === MEMTIER_BENCHMARK BUG REPORT START line. Its own alarm(5) watchdog then kills the process with SIGALRM and no output. This is the flaky test_crash_handler_worker_thread failure on PR #636.

Root cause

localtime() is not async-signal-safe: it takes glibc's time zone lock. Nothing else in memtier calls it, so the handler always makes the first call in the process. That first call runs tzset_internal(), which does strdup, fopen("/etc/localtime") and a stdio buffer malloc (gdb trace in #681). prewarm_crash_handler() did not warm it.

Fix

  • Timestamp. At startup, prewarm_crash_handler() takes the local UTC offset with crash_utc_offset() (localtime_r/gmtime_r). The handler formats time(NULL) + offset with integer arithmetic (Hinnant's civil_from_days) in the same %d %b %Y %H:%M:%S format. The code lives in the new header crash_report.h.
  • Essential lines first. The START header and the crashed by signal, Crashed running signal <...>, Signal code and Fault address lines are formatted into a stack buffer and written with write(2) to fd 2. This happens before backtrace(), stdio, or anything else that can lock. The text is unchanged. The fault address is printed as 0x<hex>, or (nil) for NULL, which matches glibc's %p. Other libcs differ for NULL (macOS prints 0x0, musl prints 0), so on those platforms the NULL case now looks like glibc.
  • Watchdog. Before alarm(5), the handler installs a SIGALRM handler with SA_ONSTACK | SA_NODEFER | SA_RESETHAND. That handler first calls alarm(1) and then writes === MEMTIER_BENCHMARK BUG REPORT INCOMPLETE: crash handler timed out ===. If that write blocks too (stderr is a full pipe or a stopped tty), the second SIGALRM takes the default action, so the process always dies: at about 5 s when the line can be written, about 6 s when it cannot.
    • ThreadSanitizer builds keep SIG_DFL for SIGALRM, as on master. TSan defers a handler for an asynchronous signal until the thread enters an intercepted call, and a thread stuck on a futex or in a blocked write never does.
  • Best effort after that. Everything after the essential lines is unchanged. A comment lists what is still not async-signal-safe there:
    • backtrace() takes the loader lock while unwinding; its first-use cost is prewarmed.
    • fprintf(stderr) takes the FILE lock. It is recursive, so it blocks only while another thread is inside a stderr call.
    • print_client_list() reads worker vectors without synchronization.
  • Docs. DEVELOPMENT.md documents the INCOMPLETE line.

Known limitations:

  • A DST change during a run shifts the crash timestamp by the DST offset.
  • A second crash by a different signal re-enters the handler and re-arms alarm(5), so death can take about 11 s. It is still bounded.

Tests

tests/crash_handler_lock_injector.c is an LD_PRELOAD shim. It follows the worker_exception_injector.cpp pattern and keeps the sanitizer runtime first. Tests that use it skip when the shim cannot be compiled (120 s timeout) or when ldd fails (60 s timeout); the skip reason includes the compiler output. Every test sends SIGSEGV to a real worker with tgkill(2). It skips threads that block SIGSEGV, such as TSan's background thread. On TSan builds the tests use kill(2) to the process instead, as they did before this PR: TSan runs the handler for a signal sent to a busy worker later, off the signal stack, and in 1 of about 20 local runs that handler printed nothing. The shim writes a marker file (MEMTIER_TEST_SHIM_MARKER) recording what it saw: the handler arming alarm() on a signal stack, each function it blocked, and the helper taking the stderr lock. The tests assert those markers, so a shim that never loaded cannot pass silently. TSan builds are detected by the __tsan_init symbol name in the binary, which covers both GCC's shared runtime and clang's static one.

test what it forces expects
test_crash_handler_time_zone_lock_held localtime/localtime_r/strftime/tzset block on the signal stack (#681), with TZ=<+0530>-5:30 exit by SIGSEGV, full report, header time = UTC+05:30 ±5 s
test_crash_handler_watchdog_marks_incomplete_report backtrace() blocks on the signal stack START, then INCOMPLETE (not on TSan), exit by SIGALRM in < 8 s
test_crash_handler_header_survives_stderr_lock a helper thread takes stderr's stdio lock when the handler arms alarm() START, signal, code, address, INCOMPLETE, no STACK TRACE, exit by SIGALRM in < 10 s. Skipped on TSan: in CI (job 117257659823) nothing after the SEGV was printed and the process never exited, because TSan's deferred signal delivery plus a helper thread parked in a stdio lock is not deterministic
test_crash_handler_watchdog_blocked_stderr stderr is a 4 KiB pipe, filled and never read exit by SIGALRM in < 9 s
crash_report_test (unit) crash_format_time() vs gmtime_r+strftime from 1900 to 2400 (only the part that fits time_t on 32-bit) at 8 zone offsets, plus leap days and year ends; crash_utc_offset() vs localtime_r for POSIX TZ strings, including DST and local/UTC year boundaries equal

Results (standalone OSS)

binary crash test file (6 tests)
origin/master 3 fail: time zone lock, INCOMPLETE and stderr lock tests (exit -14, no START)
first push of this PR (2daf36a) blocked-stderr test fails: the process hangs until it is SIGKILLed
this head, default build 6/6 pass in 2 runs on c19de5a (on 6a8099c), 8 earlier runs; also passes with TLS
this head, ASan (detect_leaks=1) 6/6 pass on c19de5a, 3 earlier runs; also passes with TLS
this head, TSan (setarch -R, as in CI) 3/3 runs on c19de5a and 5/5 on cca68ae: 5 pass, stderr-lock test skipped
this head, UBSan 6/6 pass

make check passes 12/12 on the default build of c19de5a (11/11 on ASan and UBSan before the rebase that added keylist_growth_test). crash_report_test also passes in an i386/ubuntu:bionic container (32-bit time_t), with the 151003 cases outside the time_t range skipped.

Timings with this head: blocked stderr exits about 6.0 s after the SEGV, and the hung-backtrace and stderr-lock tests exit at about 5.0 s.

Mutants:

  • Killed by the unit test: inverted offset sign, inverted year-carry sign, wrong month index, Jan/Feb year carry, hour + 1, offset not applied.
  • Killed by the RLTest tests: START line written with fprintf, watchdog handler not installed, UTC offset never stored.
  • Survives: dropping the raise() from the watchdog (the redundant signal(SIG_DFL) before it was removed, since SA_RESETHAND already restores the default). The process then dies at 6 s from alarm(1) instead of at 5 s, so the only difference is 1 s of timing. I left it uncovered rather than add a sub-second timing assertion.

Affected versions

2.3.0 through 2.5.2 (latest) and master.

Fixes #681

🤖 Generated with Claude Code


Note

Medium Risk
Changes signal-handler behavior and crash-report output paths (including watchdog termination via SIGALRM instead of the original fault signal when the handler hangs), which is security-adjacent infrastructure but well-tested.

Overview
Fixes #681: the crash handler could deadlock on localtime()/stdio and print nothing before alarm(5) killed the process.

Crash path. UTC offset is captured at startup via crash_utc_offset() in new crash_report.h; the handler formats timestamps with integer-only crash_format_time() instead of localtime/strftime. The START line, signal name, code, and fault address go through a crash_line buffer and write(2) before any backtrace or fprintf. A SIGALRM watchdog prints BUG REPORT INCOMPLETE when the best-effort section hangs (with a second alarm(1) if stderr blocks); ThreadSanitizer builds keep default SIGALRM behavior.

Tests & docs. Unit crash_report_test compares formatting to libc; an LD_PRELOAD lock injector and expanded RLTest scenarios cover timezone-lock simulation, watchdog timeout, stderr lock, and blocked pipe; DEVELOPMENT.md documents incomplete reports.

Reviewed by Cursor Bugbot for commit c19de5a. Bugbot is set up for automated code reviews on this repo. Configure here.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks for this, and for the very thorough write-up. I went through the handler change, crash_report.h, the shim and the tests. Nothing blocking from my side, just a couple of small questions.

  • The report text doesn't change: same lines, same timestamp format, and the fault address matches glibc's %p. The only visible difference is NULL on macOS/musl, and you already called that out. So I don't see a compat concern. The regression test also clears the bar this repo has set before (PR#364): test_crash_handler_time_zone_lock_held fails on master (exit -14, no START) and passes with the fix.
  • On the DST limitation: did you consider refreshing g_crash_utc_offset from the main thread instead of setting it only once in prewarm_crash_handler()? It could happen once per stats tick. The handler no longer calls localtime(), so a crash that interrupts the main thread inside localtime_r() would no longer deadlock anything. That would remove the "off by the DST shift" caveat on long runs. Not a big deal either way, and I may be missing a reason it's worse. If you keep it as is, maybe a volatile on the global would make the "written once, read from a signal handler" intent explicit?
  • Just checking: once the report finishes normally and the original signal is re-raised, alarm(5) is still pending with crash_watchdog_handler installed. I think that's harmless because the re-raise ends the process first, but I'd like to confirm there's no path where the handler returns (e.g. a signal with a non-fatal default action) and an INCOMPLETE line shows up after the END marker.
  • Nitpicking: _SYS_TGKILL hardcodes syscall numbers per arch. They look right to me (234/131/270/268), and it's only a fallback for pre-2.30 glibc, so fine to keep.

The core fix looks solid to me. The DST point is optional. I'd just like a quick answer on the re-raise question before this merges.

@fcostaoliveira
fcostaoliveira force-pushed the fix/681-crash-handler-deadlock branch from 2daf36a to 6315c51 Compare October 17, 2026 00:21
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Replies to your points, against 6315c51:

a. The stale SIGALRM comment in setup_crash_handlers(): fixed. It now says that SIG_DFL is the baseline and that crash_handler() installs crash_watchdog_handler before it calls alarm(5).

b. Output format: yes, this is intended.

  • The report lines are unchanged. %d stays zero-padded, and the fault address is printed as 0x<hex>, or (nil) for NULL, which is what glibc's %p prints.
  • The INCOMPLETE line appears only when the watchdog fires. In that case master printed nothing after the point where it got stuck. The INCOMPLETE line never appears in a report that completes. test_crash_handler_time_zone_lock_held asserts its absence on a full report, and test_crash_handler_watchdog_marks_incomplete_report asserts its presence when backtrace() hangs.
  • One change from the first push: the line no longer hard-codes "after 5 seconds". It now reads === MEMTIER_BENCHMARK BUG REPORT INCOMPLETE: crash handler timed out ===, and it is documented in DEVELOPMENT.md.

c. No [pid] timestr # prefix on the INCOMPLETE line: kept on purpose. It is a === marker like START and END, which have no prefix either, and it ends the report in place of END.

Also changed in this push, from the other reviews:

  • Watchdog death guarantee. The watchdog handler is now installed with SA_NODEFER | SA_RESETHAND and calls alarm(1) before it writes. If stderr is a full pipe and the INCOMPLETE write blocks, the second SIGALRM takes the default action. Before this, the process hung forever in that case.
  • TSan builds keep SIG_DFL for SIGALRM, because TSan would defer the handler indefinitely.
  • Time formatting moved to crash_report.h and has a unit test.
  • Tests now signal the worker with tgkill. There are new tests for the stderr-lock, hung-backtrace and blocked-pipe cases. Compiling the shim and running ldd now have timeouts and skip on failure.

🤖 Generated with Claude Code

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 6315c51. Configure here.

Comment thread tests/unit/crash_report_test.cpp Resolved
Comment thread tests/test_crash_handler_integration.py Resolved
fcostaoliveira and others added 3 commits October 17, 2026 01:51
crash_handler() called localtime() and strftime() before it printed
anything. localtime() takes glibc's time zone lock, and the first call
in the process (always the one in the handler, since nothing else in
memtier calls it) runs tzset_internal(), which mallocs and opens
/etc/localtime. A crash that interrupts a thread holding the malloc or
time zone lock therefore deadlocked the handler before the
"BUG REPORT START" line, and its own alarm(5) watchdog then killed the
process with SIGALRM and no output. That is the flaky
test_crash_handler_worker_thread failure seen on PR #636.

The handler now:
- takes the local UTC offset once in prewarm_crash_handler() and formats
  the timestamp with integer arithmetic, in the same "%d %b %Y %H:%M:%S"
  format;
- writes the START header, the signal number and name, the signal code
  and the fault address with write(2) to stderr, before backtrace(),
  stdio or anything else that can lock;
- arms a SIGALRM handler that writes a "BUG REPORT INCOMPLETE" line
  before the watchdog ends the process, so a later hang is visible.

The rest of the report (backtrace, fprintf, client list) is unchanged
and stays after the essential lines; a comment lists which of those
calls are not async-signal-safe and why.

The new test_crash_handler_time_zone_lock_held preloads a shim whose
localtime/localtime_r/strftime/tzset block when called on a signal
stack, which reproduces the deadlock on every run: it fails on master
(exit -14, no report) and passes with this change.

Fixes #681

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up for the crash handler change.

- If stderr is a pipe or tty that stopped draining, the crash handler
  blocks in write(2), and the SIGALRM handler then blocks writing its
  INCOMPLETE line. SIGALRM stayed masked while that handler ran, so the
  process hung for good, where master died at 5 s. The watchdog handler
  is now installed with SA_NODEFER | SA_RESETHAND and calls alarm(1)
  before it writes, so a second SIGALRM takes the default action.
- ThreadSanitizer runs a handler for an asynchronous signal only when
  the thread enters or leaves an intercepted call, which a thread stuck
  on a futex or a blocked write never does. TSan builds keep SIG_DFL for
  SIGALRM, as before this change.
- Move the line buffer, the UTC offset and the time formatting into
  crash_report.h, and check them against gmtime_r/localtime_r +
  strftime in a new crash_report_test unit test (1900-2400, real zone
  offsets, POSIX TZ strings, DST, year ends).
- Tests: send the SEGV to a worker with tgkill(2) and skip threads that
  block SIGSEGV (TSan's background thread); check the header time under
  TZ=<+0530>-5:30; add tests where backtrace() hangs (INCOMPLETE, exit
  by SIGALRM), where a helper thread holds stderr's stdio lock (the
  write(2) lines and INCOMPLETE still appear), and where stderr is a
  full pipe (exit by SIGALRM). Compiling the shim and ldd get a 120 s /
  60 s timeout and skip, with the compiler output, on failure.
- Document the INCOMPLETE line in DEVELOPMENT.md and fix the stale
  SIGALRM comment in setup_crash_handlers().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up.

- crash_watchdog_handler: drop the signal(sig, SIG_DFL) before raise();
  SA_RESETHAND already restored the default action. Note that a crash by
  a different signal re-arms alarm(5), so death can take about 11 s.
- The shim records in MEMTIER_TEST_SHIM_MARKER when the crash handler
  arms alarm() on a signal stack, when it blocks a function, and when
  the helper holds the stderr lock; the tests assert those lines, so a
  shim that never loaded or never saw the handler fails the test. The
  shim now arms the real alarm before waiting for the helper and waits
  at most 2 s, so a helper that never gets the lock cannot hang the
  process.
- _crash_shim_env() also drops an inherited MEMTIER_TEST_LOCK_STDERR.
- _tsan_build() looks for __tsan_init in the binary, so a clang build
  with the runtime linked in is detected too, not only libtsan in ldd.
- On TSan builds, send the crash signal with kill(2) as before: TSan
  runs the handler for a signal sent to a busy worker later, off the
  signal stack, and that occasionally printed nothing. Skip
  test_crash_handler_header_survives_stderr_lock on TSan: in CI
  (job 117257659823) nothing after the SEGV was printed and the process
  never exited.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira
fcostaoliveira force-pushed the fix/681-crash-handler-deadlock branch from 6315c51 to cca68ae Compare October 17, 2026 01:07
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Replies to the rewritten review, against cca68ae:

  1. The PR description quoted the old marker. I've updated it. The body now quotes the string the code and DEVELOPMENT.md print: === MEMTIER_BENCHMARK BUG REPORT INCOMPLETE: crash handler timed out ===.

  2. MEMTIER_TEST_LOCK_STDERR was not removed from the inherited environment. Fixed. _crash_shim_env() now pops both MEMTIER_TEST_BLOCK_BACKTRACE and MEMTIER_TEST_LOCK_STDERR.

  3. The signal(sig, SIG_DFL) before raise() was redundant. Removed. SA_RESETHAND already restored the default, and a comment now says so. I also documented the remaining edge case: a second crash by a different signal re-enters crash_handler() and re-arms alarm(5), so the process can take about 11 s to die. That is still bounded.

  4. Checking that the shim actually ran. Added. The shim appends to a marker file (MEMTIER_TEST_SHIM_MARKER):

    • signal-stack when the crash handler calls alarm() on a signal stack;
    • blocked <function> when it blocks a call;
    • stderr-locked when the helper thread holds the stderr lock.

    The tz-lock test asserts signal-stack, the backtrace test asserts blocked backtrace, and the stderr-lock test asserts both signal-stack and stderr-locked. If the shim did not load, or the handler did not run on the alternate stack, these tests now fail instead of passing trivially.

On the SIGALRM/TSan interaction, two changes from CI:

  • Skipped on TSan: test_crash_handler_header_survives_stderr_lock. In "TSAN Single Endpoint: TCP Plaintext" (job 117257659823), nothing after the SEGV was printed and the process never exited. TSan runs handlers for asynchronous signals only at intercepted-call boundaries, so a helper thread parked in a stdio lock is not deterministic there. On TSan, the write(2) header is still covered by the tz-lock test, and the watchdog exit by the two other watchdog tests.
  • Signal delivery on TSan: TSan builds now get kill(2) to the process, as these tests always used, instead of tgkill to a worker.
  • TSan detection: _tsan_build() now looks for __tsan_init in the binary. It no longer relies on ldd showing libtsan, so a clang build with the runtime linked in is detected too.

A review of the TSan part by whoever owns the sanitizer CI cells would still be welcome.

🤖 Generated with Claude Code

Review follow-up.

- crash_report_test compared crash_format_time() with gmtime_r() for
  1900-2400, but a 32-bit time_t (i386 and older armhf .deb builds,
  which run make check) only covers 1901-2038, so libc formatted
  wrapped values and the test failed with 151003 mismatches. Cases
  that do not fit time_t are now skipped and counted; the formatter
  itself computes in long long and is unaffected. Checked in an
  i386/ubuntu:bionic container: passes, 151003 cases skipped.
- Comment at the watchdog install that SIGALRM may land on any thread,
  which is fine.
- Keep getpid() in the best-effort part of the report, as on master,
  to keep the diff to what changed.
- The time zone test parses the month name by hand instead of with
  strptime's locale-dependent %b; tgkill comes from libc when it has
  it; _tsan_build() is cached.
- DEVELOPMENT.md: TSan builds never print the INCOMPLETE line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Replies to the current review, against c19de5a:

  1. 32-bit time_t: fixed. check_format() now skips, and counts, cases where t + offset does not fit time_t, because libc cannot be the reference there; the formatter itself works in long long. I built and ran the test in an i386/ubuntu:bionic container. It passes, with 151003 cases skipped as out of range. Without the fix it reported 151003 failures, matching what you found.
  2. SIGALRM on any thread: yes, I considered it. There is now a comment at the watchdog install saying so: the handler only calls alarm, write and raise, which are safe on any thread, and SA_RESETHAND resets the disposition for the whole process.
  3. Diff churn: reverted. The best-effort part of the report keeps getpid() as on master, and the gcc_version line is back to its original wrapping. The only pid uses left are in the new write(2) header code.

🤖 Generated with Claude Code

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. On the open points:

  • Re-raise with alarm(5) still pending: there's no path where the handler returns after END. crash_handler() is only installed for SIGSEGV, SIGBUS, SIGFPE, SIGILL and SIGABRT, and all five have a terminating (core-dumping) default action. At the end of the report the handler sets SIG_DFL for that signal and calls raise(sig). With SA_NODEFER it's delivered immediately and ends the process, so the pending alarm never fires and no INCOMPLETE line can follow END. The INCOMPLETE line only appears if the report itself stalls for 5 s.
  • Refreshing the UTC offset from the main thread: a good idea, and it would remove the DST caveat on long runs. It needs a periodic hook and a lock-free publish of the new offset to the handler. I'd rather do it as a small follow-up than grow this PR. Until then the limitation is documented in the code.
  • volatile on the offset global: it's written once in prewarm_crash_handler(), before the handler is installed with sigaction(), so the handler can never observe a partial write. If the follow-up above refreshes it at runtime, it'll become a volatile sig_atomic_t-sized value or an atomic.
  • _SYS_TGKILL numbers: agreed, they're only the fallback for glibc before 2.30; libc.tgkill is tried first.

@fcostaoliveira
fcostaoliveira merged commit 400b637 into master Oct 17, 2026
129 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Crash handler can deadlock in localtime() before printing anything; alarm(5) then kills the process silently (flaky test_crash_handler_worker_thread)

1 participant