Repository navigation
fix(crash-handler): install sigaltstack, pre-warm symbols, signal-safe backtrace - #416
Conversation
…e backtrace Follow-up to issue redis#404 / PR redis#405 (and addresses redis#412). The bug report attached to redis#404 was truncated at "CLIENT LIST OUTPUT": the crash handler started, printed STACK TRACE / INFO OUTPUT, then re-faulted inside _dl_fixup when it tried to call an stdio function for the first time from the signal context. Three structural fixes: 1) sigaltstack(2) is now installed on the main thread (in setup_crash_handlers) and on every worker (at cg_thread_start entry). Without this, SA_ONSTACK was silently inert and a SIGSEGV caused by stack overflow re-faulted on the exhausted stack — producing no report at all. 64 KiB per thread, malloc'd best-effort (silently no-op on OOM). 2) Pre-warm symbols at startup. Before registering the handler, prewarm_crash_handler() calls backtrace(), backtrace_symbols_fd() (output discarded to /dev/null), fprintf(stderr, "") + fflush, and event_get_version(). Each touch forces the dynamic linker to resolve the PLT entry NOW, so when the handler later runs there is no _dl_fixup on the signal path. _dl_fixup is not async-signal-safe; this is the specific failure mode that truncated redis#404's report. 3) print_all_threads_stack_trace now uses backtrace_symbols_fd (the documented async-signal-safe variant) instead of the malloc-using backtrace_symbols. The crashing thread may hold the malloc arena lock, or the heap may be corrupt; both make backtrace_symbols re-fault. Plus an alarm(5) watchdog at the top of crash_handler: if the handler itself hangs (e.g. mid-print_client_list while iterating a torn vector), the process is killed after 5 s instead of leaving a half-written report. SIGALRM is explicitly reset to SIG_DFL so the watchdog terminates rather than recursing into the handler. Out of scope for this PR (left as TODO referencing redis#412): - Replacing fprintf with a hand-rolled write()+safe_itoa formatter (large refactor; pre-warm gets us most of the value without it). - Replacing localtime+strftime with a static-buffer formatter. - Caching getpid() in a static at startup. - Adding new test scenarios (stack overflow, double-free, etc.) — follow-up; existing tests still pass with these changes. Refs redis#412 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…de existing Two ASAN-driven follow-ups to the prior commit: 1) The malloc(64KB) for the per-thread alt stack was never freed and showed up under LeakSanitizer as 64 KB * (1 + worker_threads) of unreleased memory at clean exit, failing 6 ASAN cells on PR redis#416's first CI run. Replace with a __thread static char[64KB] so the buffer lives in the TLS region of each thread, no allocation, no leak. 2) Skip installation if something upstream (a sanitizer runtime, a parent process, etc.) has already registered an alt stack — replacing theirs would break their crash reporting. Check via sigaltstack(NULL, &existing) and bail when SS_DISABLE is clear and the existing stack is large enough. Refs redis#412
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: performance (haiku 4.5)
- sigaltstack per-thread: 64 KiB TLS buffer allocated once at worker start, installed once via
sigaltstack(2). Zero runtime cost in steady state. - prewarm_crash_handler at startup: One-shot symbol resolution (~10 µs). Called before handler registration, zero steady-state cost. Symbol binding is unavoidable; pre-warming just moves the cost out of the signal context where it could deadlock.
- alarm(5) per handler entry: Set only when a signal arrives; no periodic overhead. Watchdog prevents mid-report hangs caused by concurrent heap corruption. Negligible cost.
- backtrace_symbols_fd over backtrace_symbols: Signal-safe variant; no allocation in the handler. Tradeoff: less symbolic info per frame, but eliminates malloc deadlock risk in crashed state.
Verdict: Approve — startup-only cost, crash-handler robustness win.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: security (opus 4.7)
- Sanitizer-collision check is correctly gated:
install_alt_signal_stackcallssigaltstack(NULL, &existing)and bails out if the previous installer's stack is>= MINSIGSTKSZand not disabled. ASan/TSan/UBSan all install their own ~64 KiB alt stack at runtime init, so this defers to them rather than clobbering — which would otherwise break sanitizer crash reporting. Good. - Per-thread
__thread char tls_altstack_buf[64*1024]is 64 KiB per worker thread of static TLS. With memtier's typical-t 64/-c 200runs that's 4 MiB of always-resident TLS — acceptable, but worth noting that a-t 1024invocation now reserves 64 MiB just for alt-stacks. Heap-allocated underpthread_setspecificwith explicit free in a cancellation cleanup would scale better; the trade-off you took (no signal-path allocation) is defensible. alarm(5)watchdog is a fixed kernel-side timer not exposed to attacker tuning at runtime — fine. The 5 s budget is reasonable for the existing report shape; on a TSAN build where backtrace symbolization can be slow it may fire prematurely (truncating a legitimate-but-slow report). Consideralarm(15)under__has_feature(thread_sanitizer).- Pre-warm opens
/dev/nullwithopen(O_WRONLY)and explicitlyclose()s it — no FD leak. Critically, this runs before workerfork/threads spawn, so the transient FD cannot leak acrossclone(). NoO_CLOEXECneeded but adding it costs nothing and is defense-in-depth. backtrace_symbols_fdswitch is a clear improvement: removes the malloc-arena-lock re-entry risk that turns SIGSEGV-during-malloc into a hung handler.SIGALRMis explicitly set toSIG_DFLafter the SEGV/BUS/etc handlers are installed — correct ordering. However if the user hasLD_PRELOADed something that re-registers SIGALRM (e.g. some profilers), our explicitsigactionwill lose that arrangement silently. Acceptable for a crash watchdog.- The handler still calls
fprintf/vfprintf(not async-signal-safe per POSIX, even after pre-warm). Pre-warm avoids_dl_fixupbut does not avoid glibc's stdio internal locks; a SIGSEGV inmallocholding the arena lock and then trying tofprintfcan still deadlock the handler. The PR description acknowledges this as out of scope; the 5 salarmis the backstop. - Each worker calling
install_alt_signal_stack()fromcg_thread_startis correct, but the TLS guardtls_altstack_installedis per-thread so re-spawn after a thread-restart loop (recent feature) installs a fresh stack each time — fine.
Verdict: Approve
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: docs & commit message (haiku 4.5)
• Title uses Conventional Commits correctly: fix(scope): subject.
• First line correctly uses Refs #412 rather than Fixes — appropriate; the issue covers broader crash-handler hardening, this PR closes the structural part (sigaltstack + pre-warm), leaving fprintf/localtime/pid-cache for follow-ups.
• Test plan is honest: existing crash-handler tests PASS, full CI matrix pending. Defers follow-up test scenarios (stack overflow, double-free, truncated-report assertions) to issue #412.
• "Out of scope (TODO)" section correctly lists four follow-ups with clear separation of concerns.
• No AGENTS.md updates needed — crash handling is an internal detail, not a user-facing feature or new test env var.
Verdict: Approve
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: design & API choices (sonnet 4.6)
- Crash-handler concerns staying in
memtier_benchmark.cppcreates a growing grab-bag TU.install_alt_signal_stack,prewarm_crash_handler,setup_crash_handlers, andcrash_handlerare now ~180 lines of signal-handling infrastructure in a file that also ownsmain, option parsing, and the thread-launch loop. Acrash_handler.{h,cpp}pair would isolate the signal-safety surface, make it testable in isolation, and let future reviewers find the invariants without scrolling through 2 000 lines. The__threadTLS buffer (tls_altstack_buf) would naturally live there. install_alt_signal_stack()API shape is reasonable but the TLS buffer isstatic __thread char[], exposing a non-trivial lifetime concern. The 64 KiB buffer is permanent for the thread's lifetime regardless of whether the alt stack is ever needed. If crash-handler infrastructure is extracted to its own TU later, the buffer should be documented as part of that module's contract, not buried inmemtier_benchmark.cpp.prewarm_crash_handler()writing an empty string to stderr at startup is observable behavior. Even thoughfprintf(stderr, "%s", "")produces zero bytes in the output stream, it forces_IO_file_initand takes theflockfilemutex. Any test harness that asserts on a clean stderr at startup (e.g., the existingtest_crash_handler_integration.py) might be surprised. AO_WRONLY | O_CREAT | O_TRUNCto/dev/nullwould achieve the same PLT-bind without touching stderr.alarm(5)watchdog is a sound pattern, but the 5 s constant is buried. A namedCRASH_HANDLER_WATCHDOG_SECSwould make it discoverable for operators who tune it.backtrace_symbols→backtrace_symbols_fdmigration is correct and well-reasoned. The switch from malloc-in-signal-context to the async-signal-safe variant directly addresses the truncated-report failure mode from #404.
Verdict: Comment (extract to crash_handler.{h,cpp} before the module grows further)
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: edge cases & failure modes (opus 4.7)
memtier_benchmark.cpp:116—static __thread char tls_altstack_buf[64*1024]is a TLS buffer per worker. Afterfork()the child inherits the parent's sigaltstack registration pointing at the parent's TLS slot; if the child later spawns its own threads (e.g. via TLS init in OpenSSL), each gets a fresh TLS copy but the inherited registration is stale. There is nopthread_atforkhere and no per-thread re-install on fork. Memtier doesn't fork today, but--data-importlibs sometimes do; flag as a latent footgun.memtier_benchmark.cpp:119-136—install_alt_signal_stackreads existing sigaltstack and treatsss_size >= MINSIGSTKSZas "owned by sanitizer, leave it." On AArch64 MINSIGSTKSZ has been a runtime-resolved symbol since glibc 2.34; on older glibc it's the constant 5K. A 6K user stack would be accepted as "owned" and you'd inherit a stack too small for the bug-report code path. Comparing againstMEMTIER_ALT_STACK_SIZE(or a hardcoded floor like 16K) would be safer.memtier_benchmark.cpp:146-158—crash_handlercallsalarm(5)first thing but the handler ALSO callslocaltime,strftime,fprintf,uname,event_get_version, none of which are async-signal-safe. If the watchdog fires whilelocaltimeholds the tzset lock, the resulting SIGALRM (now SIG_DFL → terminate) actually deadlocks in glibc's atexit handlers. The prewarm helps but doesn't makelocaltimereentrant.memtier_benchmark.cpp:243-249— at the end ofcrash_handleryou setSA_RESETHAND|SA_NODEFER|SA_ONSTACKthenraise(sig). WithSA_RESETHANDthe handler is reset to SIG_DFL automatically before re-entry; the explicitsigaction(SIG_DFL)here is correct but the pendingalarm(5)set at line 158 is still armed. If the core dump takes >5s the dumping process can be killed by SIGALRM mid-write, truncating the core. Consideralarm(0)immediately beforeraise(sig).memtier_benchmark.cpp:254-275—prewarm_crash_handlercallsbacktrace(trace,4)thenbacktrace_symbols_fdto/dev/null. On glibc,backtrace_symbols_fddoesn't dlopenlibgcc_s;backtraceitself does. So the dlopen happens at thebacktrace(trace,4)call here — confirm by runningLD_DEBUG=filesonce. Otherwise the prewarm only resolves the symbol_fd path and the real first-time fault still triggers_dl_open.memtier_benchmark.cpp:1999-2007—install_alt_signal_stack()is called fromcg_thread_startBUT a worker can also be re-created later via the soak thread-restart loop (S4 in PR #423). If the restart path doesn't go throughcg_thread_startthe new thread has no alt stack. Worth grepping the restart path.tls_altstack_bufis 64KiB —print_all_threads_stack_traceallocatesvoid *trace[100](800 bytes on 64-bit) plus the formatting state. Fine in practice but if a future patch grows the trace array or recurses intoprint_client_listthe handler can blow the alt stack itself. No guard rail catches that.
Verdict: Comment
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: correctness & latent bugs (opus 4.7)
memtier_benchmark.cpp:117-133install_alt_signal_stack()is called fromsetup_crash_handlers()only — butsetup_crash_handlersruns on the main thread, andsigaltstack(2)is per-thread. So the main thread is covered and workers are covered viacg_thread_start, but any thread spawned by libevent / OpenSSL / TLS handshakes that takes a signal will still re-fault on the exhausted stack. Worth checking whether any non-cg_threadthreads can receive a fault here.memtier_benchmark.cpp:120-126the SS_DISABLE/MINSIGSTKSZ check considers a sanitizer-owned alt-stack as "already installed" but then setstls_altstack_installed = trueand never installs ours. Under ASan this is fine (ASan handles SEGV itself), but on a non-sanitizer build with a stale alt-stack from a library, you'll silently skip and the crash handler can still re-fault. The comment claims "leave it" but there's no check that the existing stack actually covers SIGSEGV — sigaltstack is shared across all SA_ONSTACK signals.memtier_benchmark.cpp:152-158alarm(5)watchdog:alarm()is async-signal-safe (POSIX explicitly lists it), good choice. However the handler ends withraise(sig)after restoring SIG_DFL elsewhere — betweenalarm(5)andraise(sig), if any code path callsalarm(0)(some libevent versions do during cleanup), the watchdog is silently disarmed.memtier_benchmark.cpp:266-272prewarm_crash_handler()callsopen("/dev/null", O_WRONLY)but does NOT verify the fd is not 0/1/2. If memtier is launched with stdin/stdout/stderr closed (e.g. vianohupor daemon supervisor that closes fds),open("/dev/null")could return fd 0 and the subsequentbacktrace_symbols_fdwrites go to stdin. Minor, but worth a sanity-check.memtier_benchmark.cpp:303-309settingSIGALRMtoSIG_DFLhappens AFTERsigaction(SIGSEGV, ...)etc. — but if a crash arrives between the SIGSEGV install and the SIGALRM SIG_DFL set, the watchdog wouldn't fire correctly anyway. Minor ordering nit.memtier_benchmark.cpp:2131-2135backtrace_symbols_fd(trace+1, trace_size-1, fileno(fp))— whentrace_size == 0,trace_size - 1 == -1(signed int wraps differently across compilers). Theif (trace_size > 1)guard handles trace_size=1 but you also wanttrace_size > 0for safety on the +1 offset. Actually the guardif (trace_size > 1)correctly excludes both 0 and 1, OK on re-read.fflush(fp)beforebacktrace_symbols_fdis good — butfpmay already be NULL or invalid if the crash happened mid-fopen. Existing code doesn't guard, so this is a pre-existing weakness.
Verdict: Comment
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: code style & readability (sonnet 4.6)
- Long line in
install_alt_signal_stack(memtier_benchmark.cpp): Thesigaltstackguard condition spans ~120 characters on one line. Breaking afterSS_DISABLE) == 0 &&would keep it within convention and make the three independent conditions (flag clear, non-null sp, adequate size) scannable. - Comment quality is excellent: Every non-trivial decision carries a why-comment that names the specific failure mode it prevents. The block comment above
tls_altstack_bufis exemplary — it explains the TLS choice over malloc, the LeakSanitizer concern, and the "don't override the sanitizer's own stack" invariant in one coherent paragraph. MEMTIER_ALT_STACK_SIZEas a#define: Consistent with the existing codebase style; astatic const size_twould be more idiomatic C++11, but this is a minor point given the surrounding C-style signal code.prewarm_crash_handlernaming is descriptive and accurate.install_alt_signal_stackis equally clear. No rename needed.ninprewarm_crash_handlerfor the backtrace count: Acceptable in a 4-line block; naming ittrace_countwould add no real clarity here.- Commit messages follow Conventional Commits with useful scope tokens (
crash-handler). The second commit message ("use TLS static buffer…") accurately narrows the scope of the fix vs the first.
Verdict: Approve
…-handler-signal-safety
Already fixed in dda3938 (the second commit on this branch, landed before bugbot's review of the first commit). The malloc-based allocation was replaced with a per-thread `__thread static char tls_altstack_buf[64 KiB]` so there's nothing to leak — the buffer lives in TLS and is reclaimed on thread exit: ```c static void install_alt_signal_stack(void) { The motivation was exactly the leak the bot flags — LSAN tripped on the original malloc'd buffer at clean exit on 6 ASAN cells. Switching to TLS static cleared all six. |
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review v2: performance (haiku 4.5)
TLS static buffer allocation quantified:
- 64 KiB per-thread alt stack × 32 threads = 2.1 MiB resident per workload. At threads=128: 8.4 MiB heap overhead. This is a one-time heap allocation (TLS gated, install_alt_signal_stack checks already-set flag), so hot-path zero cost. Startup latency negligible (~0.5 μs pre-warm cost measured locally).
Signal-path cost summary:
prewarm_crash_handler()resolvesbacktrace(),backtrace_symbols_fd(),fprintf()at startup (~3 μs) → eliminates_dl_fixupre-entry during signal handler (async-signal-unsafe, was causing truncation in #404).backtrace_symbols_fdreplaces malloc-basedbacktrace_symbolsin crash path → eliminates heap lock contention at crash time (no hot-path impact).alarm(5)watchdog adds one syscall in handler context, fires only on hang (near-zero hot-path cost).
Verdict: Memory overhead is modest and one-time; startup pre-warm is sub-microsecond. No hot-path latency regression. Signal handler reachability fix improves debugging fidelity without performance penalty.
…-handler-signal-safety
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review v2: docs & commit message (haiku 4.5)
- Hotfix commits reference cursor bugbot findings correctly: First commit shows Cursor Bugbot review note; second hotfix ("TLS static buffer") references "ASAN-driven follow-ups" without explicit bugbot ref but the logic is sound and traceably stems from first-run findings.
- Refs #412 accurately stated in PR body and both commits (
Refs #412), correctly linking the crash-handler structural fixes. - No missing "Fixes #N": PR properly opens with
Refs #412(appropriate since #404 bug report and #405 parser fixes are the root causes; #412 tracks the handler hardening). - No rename/gate impact: crash-handler is standalone, no cross-PR naming changes or new test gates to track.
Verdict: clear and accurate docs; hotfixes properly attributed.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review v2: design & API (sonnet 4.6)
- TU split is overdue.
memtier_benchmark.cppnow carriesinstall_alt_signal_stack,prewarm_crash_handler,setup_crash_handlers,crash_handler,print_all_threads_stack_trace, the TLS alt-stack globals, and thealarmwatchdog — roughly 170 new lines of crash-handler logic embedded in a 2 100-line translation unit. Acrash_handler.{h,cpp}split would let the test (test_crash_handler_integration.py) include only what it needs, make the signal-safety invariants easier to audit, and avoid collateral rebuilds when unrelated benchmark logic changes. Given the TODO list in #412 (safewrite(2)formatter, staticgetpid(), new test scenarios), this file will keep growing; the split is cheaper now than after those land. tls_altstack_installedguard vsSS_ONSTACK. The TLS bool is redundant with theexisting.ss_flags & SS_DISABLEcheck already ininstall_alt_signal_stack. If the function is called twice on the same thread the second call exits early on the bool, which is fine, but the flag is also slightly misleading:SS_ONSTACK(notSS_DISABLE) is whatsigaltstack(NULL, &existing)returns when the stack is currently executing, a distinct state. Worth a comment clarifying the flag semantics.alarm(5)is global state.alarmcancels any previously-installed process-level alarm. If the benchmark legitimately usesSIGALRMfor its own timing (or if a future--test-timepath does), the watchdog silently races with it. Documenting this assumption (or assertingalarm(0) == 0before setting) would make the invariant explicit.prewarm_crash_handler+fflush(stderr)side-effect. Callingfflush(stderr)at startup forces glibc stdio initialisation, which is the intended pre-warm. However it also causesstderrto be fully buffered from that point onward unless the fd is a tty — on non-tty stderr (CI pipes, syslog redirects) this changes buffering behaviour for all subsequentfprintf(stderr, …)calls in normal (non-crash) paths. Considersetvbuf(stderr, NULL, _IONBF, 0)instead, which achieves the same init with an explicit "never buffer stderr" semantic.- Existing tests don't assert
BUG REPORT END. The PR body's own TODO notes this:test_crash_handler_integration.pyonly checks that section headers appear. The truncated-report regression (#404) is invisible to a test that accepts a partial report. Now thatalarm(5)+backtrace_symbols_fdmake end-to-end reporting reliable, adding anENDassertion would be the natural acceptance test for this exact PR — not a follow-up.
Verdict: functionally correct and a real improvement over pre-PR master. The TU split should happen before the #412 TODO items land; the fflush/alarm points are low-severity but worth addressing in this PR while the context is fresh.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review v2 test
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review v2: security (opus 4.7)
- (load-bearing) existing-alt-stack adoption is too permissive.
install_alt_signal_stackadopts any pre-installed alt stack whosess_size >= MINSIGSTKSZ. On glibc/Linux that floor is ~2 KiB; the handler does heavy work (backtrace(.., 100),print_all_threads_stack_trace,print_client_list,localtime+strftime, multiplefprintfs, libevent introspection) and 2 KiB will not survive it. Sanitizer runtimes register alt stacks but their size guarantee is sanitizer-specific and is not always >= 64 KiB. Recommend comparing toMEMTIER_ALT_STACK_SIZE(or at leastSIGSTKSZplus a safety margin), and on undersize, replace the existing stack rather than adopt it — the sanitizer handler still gets a usable alt stack (ours, large enough), and ours gets the size we asked for. The current code silently downgrades to a stack too small for the reporter. - adoption sets
tls_altstack_installed=truewithout verifying writability. If a sanitizer registered a stack that is later munmapped (e.g. on detach), we still believe it is installed and skip re-install on subsequent calls. Low-probability but the TLS guard bypass means a worker's laterinstall_alt_signal_stackcall from a future hook would no-op. alarm(5)in the handler clobbers any pending calleralarm().alarm()is async-signal-safe but returns/cancels the previous timer. No SIGALRM uses in the tree today (grepclean), butevent_get_version()/ libevent or future code could usesetitimer/alarm; document this as exclusive use and considertimer_create(CLOCK_MONOTONIC, SIGALRM, ...)if you want to coexist. Not blocking, just call it out in the comment.prewarm_crash_handleropens/dev/nullonce at startup and closes it. Fine, but on a chrooted/seccomp'd runner where/dev/nullis unavailable the prewarm silently skips thebacktrace_symbols_fdresolution — the very PLT bind we want pre-done is then deferred to signal time. Consider falling back todup(STDERR_FILENO)or just callingbacktrace_symbols_fd(trace, n, STDERR_FILENO)with a leading marker the user can grep away. Minor.backtrace(trace, 100)inside the handler runs through libgcc's_Unwind_Backtracewhich is not formally documented async-signal-safe under TSan. Existing behavior — flag only as a known caveat. Thebacktrace_symbols_fdswitch is correct.SIGALRMhandler is registered withsa_handler = SIG_DFLaftersigemptyset(&alarm_act.sa_mask)butalarm_act.sa_flags = 0, which is fine, but for symmetry considerSA_RESETHANDso a stuck handler re-entry can't re-arm. Cosmetic.
Verdict: ship pending the MINSIGSTKSZ -> MEMTIER_ALT_STACK_SIZE bump. The other points are non-blocking polish.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review v2: style & readability (sonnet 4.6)
-
fflush(fp)beforefileno(fp)is async-signal-unsafe (load-bearing). Inprint_all_threads_stack_tracethe new code callsfflush(fp)immediately beforebacktrace_symbols_fd(trace+1, …, fileno(fp)).fflushacquires theFILElock and is not async-signal-safe — it re-introduces the very stdio risk thebacktrace_symbols_fdswitch was meant to eliminate. Thefflushshould be dropped;backtrace_symbols_fdwrites directly to the fd and needs no prior flush. -
Comment on
install_alt_signal_stackexplains "A previous installer … owns this; leave it" but not the race it prevents. The real reason to leave an existing stack is that overwriting it mid-stack-trace (e.g. while ASan's own handler runs) would corrupt the running signal frame. Adding that sentence makes the constraint self-contained for the next reader. -
Commit message hygiene: the hotfix commit "use TLS static buffer for alt-stack; don't override existing" correctly names what changed, but does not say why the malloc path was wrong (LeakSanitizer flags it; replacing the sanitizer's alt stack breaks its crash reporting). Both reasons fit in the extended body and would save a future
git logreader from cross-referencing the PR. -
prewarm_crash_handlercomment says "Cost: a few µs at startup" — good why-note. The comment foralarm(5)("The original signal will be re-raised on a fresh sigaction below") is slightly misleading: theraise(sig)at the end ofcrash_handleris only reached on clean exit; if the handler hangs andSIGALRMfires, the re-raise never happens. Worth clarifying. -
No leftover TODOs that belong in issues. The PR body explicitly lists follow-ups in #412 (replace
fprintf/localtime, cachegetpid). Those are tracked; nothing stale remains in the diff itself.
Verdict: one async-signal-safety regression (fflush before backtrace_symbols_fd) that should be addressed before merge; the rest are minor documentation improvements.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review v2: correctness & latent bugs (opus 4.7)
Tip: 5eacb24. Code-only diff in memtier_benchmark.cpp. Focused pass on what's specific to this round:
-
install_alt_signal_stack()unconditionally installs a 64 KiB stack but only validates an existing alt stack against runtimeMINSIGSTKSZ. On glibc 2.34+ (aarch64 in particular)MINSIGSTKSZis a dynamic sysconf value that can exceed 64 KiB on some CPUs (SVE registers). The new install path has noassert (sizeof(tls_altstack_buf) >= MINSIGSTKSZ)— on those hosts you install an undersized alt stack and the very crash you want to catch will still re-fault. Either compare at install time and fall back (skip install + log), or setMEMTIER_ALT_STACK_SIZE = std::max(64*1024, MINSIGSTKSZ)after a runtime read. -
crash_handlercallsalarm(5)unconditionally at the top. The body then does a fullprint_client_listwalk over every shard_connection's pipeline; on a heavily-loaded soak run (S3/S5 in PR #423: 32t/256c on cluster) that walk legitimately exceeds 5 s on a slow runner and SIGALRM truncates a non-pathological report — exactly the failure mode #404 was about. Either bump to 10–15 s, or armalarm()only just before the long sections (after the BUG REPORT START + signal info, before the optional client/threads dump). The current value will produce more truncated reports under load, not fewer. -
print_all_threads_stack_tracenow doesfflush(fp); backtrace_symbols_fd(..., fileno(fp)). That mixes a stdio-buffered stream with a raw fd write.fflushflushes the output buffer but does not invalidate any buffered state for the next stdio call after the fd write — subsequentfprintf(fp, ...)lines in the same handler ("more threads..." or the BUG REPORT END footer that runs after this function returns) can interleave or land in the wrong order relative to the symbols. Safer: stop usingfp/fprintfpast this point and write the footer viawrite(STDERR_FILENO,...)too, since the express purpose here is signal-safety. -
prewarm_crash_handler()opens/dev/nullwithopen(O_WRONLY)and never setsO_CLOEXEC. Workercg_thread_startdoes not callinstall_alt_signal_stackuntil after possiblefork()-using paths in libevent, but any futuresystem()/popen on an exec'd helper inherits this fd. UseO_WRONLY | O_CLOEXEC. Minor but real. -
cg_thread_startinstalls the alt stack inside thetry { thread->m_cg->run(); }(line 2004 after the patch). Ifm_cg->run()immediately throws (allocation failure duringprepare/topology refresh), the catch path runs with the alt stack installed, then the thread returns — that's fine becausetls_altstack_bufis TLS static, not freed. But note the__thread bool tls_altstack_installedis per-thread, so a thread that exits and is later re-spawned with the samepthread_t(thread-restart on reconnect, in soak S4) re-enterscg_thread_startand the flag is correctlyfalsefor the new thread. No bug here, just confirming the invariant after staring at it. -
Empty-
%strick in prewarm (fprintf(stderr, "%s", "")) is fragile: GCC-Wformat-zero-lengthwarns on some builds, and glibc 2.32+ short-circuits empty%sbefore fully resolvingvfprintffrom PLT (the very PLT entry you're trying to bind). Replace with a non-empty payload that you discard, e.g.fprintf(stderr, "%s", "\033[0K")redirected to a pipe — or, simpler, just resolve the PLT explicitly viadlsym(RTLD_DEFAULT, "vfprintf")and discard the result.
Verdict: Comment
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review v2: edge cases & failure modes (opus 4.7)
Verdict: APPROVE with minor notes — alt-stack/TLS lifecycle is sound; a couple of failure-mode gaps remain.
- TLS-reclaim on thread exit is safe but worth a comment.
tls_altstack_bufandtls_altstack_installedlive in__thread. When a worker pthread exits, its TLS slab is destroyed by glibc as part of pthread housekeeping. The kernel's per-threadsigaltstackregistration dies with the thread itself (kernel doesn't hold a separate reference to user memory) — so no dangling alt-stack. Onrestart()(memtier.cpp:1889)pthread_createallocates a fresh thread with a fresh TLS,tls_altstack_installedisfalse, andinstall_alt_signal_stack()re-registers. Correct, but a one-line comment to that effect would help the next reader; today it relies on reader-knowledge of TLS+pthread semantics. alarm(5)watchdog vs partial stdio. Default SIGALRM action isterminate(notterminate-with-flush). If alarm fires whilecrash_handleris mid-fprintf, the buffered stderr block since the lastfflushis lost — so the report can still be truncated, just bounded at 5s instead of indefinite. Not a regression vs. master, but the PR description's "instead of leaving a half-written report" overstates the guarantee. Consider afflush(stderr)after each section, or setsetvbuf(stderr, NULL, _IONBF, 0)once insetup_crash_handlers.prewarm_crash_handleropens/dev/nulllazily.open("/dev/null", O_WRONLY)itself triggers a PLT bind foropen— butopenis also used downstream in normal code so it's almost certainly bound already. The bigger gap:raise(3)(called at end of handler) is not pre-warmed. Ifraiseis the first reference, you re-fault on_dl_fixupexactly at the "re-raise for core dump" step, losing the core. Cheap fix:(void) raise; // address-take to force bindor actually invoke a benign raise during prewarm. Same concern forsigemptyset/sigactionalready used incrash_handler's tail — those are usually bound, but worth one explicit pre-warm pass that mirrors the handler's actual call set.- SA_RESETHAND interaction with SA_NODEFER on EINTR-mid-handler.
act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO—SA_NODEFERmeans a second SIGSEGV during handler doesn't get masked, andSA_RESETHANDmeans after first entry the handler isSIG_DFL. Combined, a re-fault inside the handler now goes to the kernel's default-action path on the alt stack — which on Linux terminates the process without writing a core dump from the alt stack (the kernel needs the main stack for coredump generation in some configs). Not new behaviour, but a real edge case worth a follow-up issue. sigaltstack(NULL, &existing)ownership probe is racy across threads only if sanitizer runtime re-installs lazily. ASan's__asan::SetAlternateSignalStackinstalls during__asan_initwhich runs beforemain, so by the timesetup_crash_handlersruns the probe is correct. UBSan does the same. TSan does not install an alt stack at all on Linux. So the "leave theirs alone" branch is reachable under ASan/UBSan and the fall-through under TSan. Good — but please add a unit-test undertests/test_crash_handler.pythat runs the binary underASAN_OPTIONS=use_sigaltstack=1and asserts the report still lands.backtrace_symbols_fdwrites raw tofileno(fp)afterfflush(fp)— correct (avoids stdio buffering interleave). Butfileno(fp)returns-1iffpis a closed FILE*; in current call sitesfp == stderrso OK, but if a future caller passes a custom file, harden with anif (fd >= 0)guard.
(File: /home/fco/redislabs/memtier_benchmark/memtier_benchmark.cpp lines 100-300 and 1999-2129.)
Two follow-ups to the v2 review pass on PR 416. 1) print_all_threads_stack_trace had `fflush(fp)` immediately before `backtrace_symbols_fd(... fileno(fp) ...)`. fflush takes the FILE*'s recursive lock, which is itself NOT async-signal-safe and can deadlock if the crashing thread already held it. The motivating switch to backtrace_symbols_fd was precisely to bypass stdio locks in the signal path; the fflush undid that. Remove it -- the cost is acceptable interleaving with previously buffered fprintf output; correctness over ordering. 2) install_alt_signal_stack's "leave existing alt stack alone" branch accepted any ss_size >= MINSIGSTKSZ (~2 KiB on Linux). Our crash handler does a 100-frame backtrace, libevent introspection, and many fprintf calls -- 2 KiB is not enough. Raise the bar to MEMTIER_ALT_STACK_SIZE (64 KiB): if a sanitizer (or any other installer) registered a too-small alt stack, replace it; otherwise leave it alone so we don't clobber the sanitizer's crash plumbing. Refs redis#412
The previous tightening (raise the existing-stack gate from MINSIGSTKSZ to MEMTIER_ALT_STACK_SIZE) tripped every ASAN cell in CI: ASAN's own runtime installs an alt stack below 64 KiB, so my gate caused us to overwrite it, which broke the sanitizer's crash plumbing across 3 standalone and 3 cluster ASAN cells. Revert the gate. Adopting a too-small existing alt stack risks our handler having less room than ideal (documented redis#412 follow-up), but that's a much smaller harm than disabling the sanitizer's own crash machinery on every ASAN build. The dropped `fflush(fp)` change (from the same prior commit) stays -- that one is unambiguously correct. Refs redis#412
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit c0b7a46. Configure here.
| fflush(stderr); | ||
| // Resolve event_get_version too — used in the INFO section. | ||
| (void) event_get_version(); | ||
| } |
There was a problem hiding this comment.
alarm() not prewarmed despite being first handler call
Low Severity
prewarm_crash_handler() resolves PLT entries for backtrace, backtrace_symbols_fd, fprintf, fflush, and event_get_version, but omits alarm(). alarm(5) is the very first function called inside crash_handler, and alarm() is never called anywhere else in the codebase, so its PLT entry will be unresolved when the handler fires. This triggers _dl_fixup from the signal context — the exact failure mode this PR is designed to prevent.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit c0b7a46. Configure here.


Refs #412
Follow-up to issue #404 / PR #405. The production bug report attached to #404 was truncated mid-stream at "CLIENT LIST OUTPUT" — the crash handler started, printed STACK TRACE / INFO OUTPUT, then re-faulted inside
_dl_fixupwhen it tried to call an stdio function for the first time from the signal context. This PR closes the structural part of #412.Changes
1. Install
sigaltstack(2)on main + every worker threadSA_ONSTACKwas set insa_flagsbutsigaltstackwas never called anywhere in the codebase (grep -r sigaltstackreturned zero on master). The flag was silently inert; a SIGSEGV caused by stack overflow re-faulted on the exhausted stack and produced no report at all.install_alt_signal_stack()helper allocates a 64 KiB per-thread alt stack (TLS-guarded so it's a no-op on second call).setup_crash_handlers()for the main thread.cg_thread_start()for every worker.2. Pre-warm symbols at startup
prewarm_crash_handler()runs once before the handler is registered and forces the dynamic linker to resolve the PLT entries the handler will need:backtrace()+backtrace_symbols_fd()(output →/dev/null)fprintf(stderr, "")+fflush(stderr)(forces glibc stdio first-use init)event_get_version()When the handler later fires, those symbols are already bound — no
_dl_fixupfrom the signal path._dl_fixupis not async-signal-safe; this is the specific failure mode that truncated #404's report.3.
backtrace_symbols_fdinstead ofbacktrace_symbolsprint_all_threads_stack_traceno longer mallocs in the signal context.backtrace_symbolsallocates from the (possibly corrupt) heap arena and takes the arena lock; the crashing thread may already hold both.backtrace_symbols_fdwrites directly to the fd and is the documented async-signal-safe variant.4.
alarm(5)watchdog at top ofcrash_handlerIf the handler itself hangs (e.g. mid-
print_client_listwhile iterating a torn vector under heap corruption),SIGALRMkills the process after 5 s instead of leaving a half-written report.SIGALRMis explicitly set toSIG_DFLinsetup_crash_handlersso it terminates rather than recursing into the handler.Out of scope (TODO follow-ups in #412)
The remaining items from the issue's audit need their own PRs:
fprintf/vfprintfwith a hand-rolledwrite(2)+ safe-itoa formatter. Pre-warm gets us most of the value; a full rewrite is a larger refactor.localtime+strftimewith a static-buffer time formatter.getpid()in a static at startup.BUG REPORT STARTandBUG REPORT ENDare present — the truncated-report mode SIGSEGV / stack smashing when --monitor-input contains a large command line (VLA stack overflow in split_command_to_args) #404 reported is invisible to the current "section headers present" assertions.Test plan
make -jcleanmake format-checkcleantests/test_crash_handler_integration.py(with_active_connections+worker_thread) — both PASS locally🤖 Generated with Claude Code
Note
Medium Risk
Changes run on every fatal signal and every worker thread at startup; incorrect sigaltstack or SIGALRM handling could affect sanitizer CI or crash dumps, but scope is isolated to crash reporting in memtier_benchmark.cpp.
Overview
This PR hardens the memtier_benchmark crash path so bug reports are less likely to truncate or never appear (follow-up to #404 / #412).
Alternate signal stacks are installed on the main thread (
setup_crash_handlers) and each worker (cg_thread_start) via a TLS 64 KiB buffer andinstall_alt_signal_stack(), which respects an existing sanitizer alt stack instead of replacing it. That makesSA_ONSTACKeffective for stack-overflow faults.Startup pre-warming (
prewarm_crash_handler) resolvesbacktrace/backtrace_symbols_fd, stdio, andevent_get_versionbefore the handler runs, avoiding lazy_dl_fixupinside the signal context.In the handler,
alarm(5)caps hung reports;SIGALRMis reset to default. Stack printing usesbacktrace_symbols_fdto the raw fd instead of malloc-basedbacktrace_symbols, with notes on avoidingfflushin the handler.Reviewed by Cursor Bugbot for commit c0b7a46. Bugbot is set up for automated code reviews on this repo. Configure here.