Repository navigation
feat: pthread_atfork fork-safety handlers with lock-order contract - #289
Conversation
fork() from a multithreaded process only clones the calling thread; any mimalloc-internal lock held by another thread at that moment stays locked forever in the child, hanging its first allocation. Implements #270 (Bun parity P5): - test/test-fork-locks.c: POSIX repro (Step 1) -- a churn thread holding heaps_lock/arena_reserve_lock racing 200 fork()s, watchdog-guarded. - src/subproc.c: _mi_process_fork_prepare/parent/child with a documented 13-step lock order (comment block at the top of the file), self-checked in MI_DEBUG builds. Ported design (not code) from oven-sh/mimalloc @942b8342, MIT; the tld->theaps_lock gap (needs Bun's scavenger tld registry, not yet in this tree) is called out as a known limitation and marked `// Phase 7: scavenger`. - src/init.c: single pthread_atfork registration in mi_process_init_once, POSIX only -- never per-heap (Bun's own history: a per-heap registration exhausted glibc's atfork table and aborted BoringSSL). - src/prim/osx/alloc-override-zone.c: wires the macOS zone force_lock/ force_unlock/reinit_lock callbacks and the _malloc_fork_* DYLD interpose to the same handlers. - src/{profile,dhat,memory-events,threadlocal,options}.c: fork handlers for each subsystem's own lock; profiler/DHAT/memory-events all continue in the child (their state is ordinary process memory, only the lock needs resetting). - test/test-fork-user-heap.c: imported from oven-sh/mimalloc @942b8342, MIT; cases needing the scavenger/tld registry are disabled (`#if 0 // Phase 7`) since they don't compile against this tree yet. Found and fixed during evidence-gathering: the depth counter as first ported from Bun assumes fork() calls are serialized across threads, which glibc does not do. Under genuinely concurrent multi-threaded fork() this produced a real internal_lock_release_by_non_owner (an ABA race across overlapping fork "generations"), caught by the P1 reentrancy checker. Fixed by making the depth counter per-thread and adding a real mutex (mi_fork_serialize_lock) for true cross-thread exclusion. MIMALLOC_FORKS.md's pthread_atfork row -> IMPORTED. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
cargo run -p xtask -- amalgamate-c && amalgamate-h, after the C-core fork-safety commit. cargo test -p mimalloc-pprof: all green. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Addresses Opus review of #289 (two blockers): Blocker 1 (compile break, all non-Linux CI reds): _mi_process_is_initialized was declared only inside prim-tls.h's `#if MI_TLS_MODEL_LOCAL` branch, which macOS (pthreads) and Windows don't take. Declared unconditionally in internal.h instead (dropped page.c's now-redundant local extern), and guarded the whole fork-handler definition block in subproc.c with the same `#if !defined(_WIN32) && !defined(__wasi__)` init.c already uses to call it, so it is not dead code there (rule 6). Blocker 2 (deterministic AB-BA deadlock under MIMALLOC_PROF=1): Bun's ported rule ("locks held across an allocation go before arena_reserve_lock") assumed those locks are never taken from inside the allocation path itself. In this tree prof_lock/dhat_lock/memevt_cb_lock ARE alloc/free-hook locks that can nest under a heap's arena_pages_lock a few frames up the same call stack, so taking them first (steps 3-5) was backwards and deadlocked against a concurrent mi_malloc under MIMALLOC_PROF=1 (reproduced 3/3 in Release, confirmed via the actual call-stack nesting rather than Bun's stated rule). Reordered: hook locks now sit innermost, alongside out_buf_lock. Also corrected mi_heap_ensure_arena_pages's real nesting (non-main heap's arena_pages_lock can sit outside heap_main's, the opposite of the previous order) and documented the residual, pre-existing mi_prof_visit/prof_lock inversion this phase does not close. Also fixes (found during the same review pass): - mi_fork_depth/mi_fork_lock_level were mi_decl_thread (__thread), which this codebase already knows is unsafe for hook-adjacent state reached from inside libSystem's fork machinery on macOS (see hooks-tld.h/#266). Replaced with a shared owner (_Atomic mi_threadid_t) + plain depth, both protected by mi_fork_serialize_lock, needing no TLS at all. Symmetric ownership checks in parent/child also close an asymmetric-guard-latch gap. - dhat_once/memevt_once (env-var lazy-init guards) now reset in the child via a new _mi_atomic_once_fork_child_reset helper, unless already resolved. - New MI_DEBUG-only test hooks (_mi_test_hold_heaps_lock etc) give test-fork-locks.c a deterministic repro alongside the probabilistic one (0/200 measured on main gave it near-zero discriminating power). New ctest variants register MIMALLOC_PROF=1/MIMALLOC_DHAT=1/ MIMALLOC_MEMORY_EVENTS=1 env runs of the same binary so a future reordering regresses loudly in CI. Verified: test-fork-locks (base + all three env variants) and test-fork-user-heap green 20x in Debug+FULL and 20x in Release, including the exact MIMALLOC_PROF=1 Release repro from the review (3/3 clean, was 3/3 hung). Full ctest green in debug-full (39), release (32), and MI_PPROF=OFF (27). uv run ci/verify_local.py --keep-going: 9/11 pass (asan environmentally red as before -- confirmed via test-api, unrelated to this change; rust fails pending the following amalgamation commit). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
cargo run -p xtask -- amalgamate-c && amalgamate-h, after the review-fix C-core commit (macOS/Windows compile break + AB-BA deadlock). cargo test -p mimalloc-pprof: all green. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
…o src/fork.c Review round 2 on #270. The hook locks were already innermost, but the outer steps were never re-derived from the actual lock-nesting graph of this tree. F1. `_mi_meta_zalloc` holds `theap_meta_lock` across a full `mi_theap_zalloc` on `theap_meta`, whose heap IS `heap_main` -- so it nests `theap_meta_lock` OUTSIDE `heap_main->arena_pages_lock` (arena.c:685), `arena_reserve_lock` (arena.c:534) and the page-map lock (page-map.c:393). Prepare took all three BEFORE `theap_meta_lock`: a latent deadlock against any thread starting up (init.c:268 / theap.c:329 allocate a fresh tld/theap through `_mi_meta_zalloc`). The whole order (steps 1-14) is now re-derived by tracing, for every internal lock, what can be acquired while it is held; the resulting edge list is written out as a table in src/fork.c and the acquisition sequence is a topological order of it. Two structural consequences: * `mi_thread_locals_lock` is process-global but sits BETWEEN two per-subprocess levels (`heaps_lock` -> ... -> `theap_meta_lock`), and a heap's three locks do not share one level (`theaps_lock` must precede `theap_meta_lock` via `mi_heap_free_theaps` -> `_mi_meta_free`, while the MAIN heap's `arena_pages_lock` must follow it). Prepare therefore runs one pass per level over all subprocesses, not one walk per subprocess. * non-main `arena_pages_lock` stays outside `theap_meta_lock` (`mi_heap_free` frees under it), `heap_main`'s stays inside. `mi_fork_lock_order_assert` used to check only that this handler's own acquires were ordered -- true by construction. It is now backed by a real runtime detector (MI_DEBUG>2): diagnostic.c's reentrancy checker already records each lock's owning thread, so every acquire reads off which tracked locks the thread already holds and records the nesting edge; every fork() asserts the edges observed so far agree with the documented order. Prepare's own acquires are excluded (they would just re-derive the documented order). Verified end to end: swapping the documented levels of `mi_thread_locals_lock` and `theap_meta_lock` makes an ordinary test-fork-locks run report the violation. Rule 6: the handlers, the order table, the checker and the test hooks move to a new src/fork.c (POSIX-only, included by src/static.c and CMake under the same guard); subproc.c keeps two registry accessors. F2. The "deterministic" test hook had no discriminating power: no-op'ing prepare's `heaps_lock` acquire still passed 20/20, because the child re-inits that lock unconditionally. The holder thread now POISONS the structure the lock guards while holding it (detaches `sp->heaps`, restoring before release), and the child reports via `_mi_test_heaps_lock_poison_observed()`. Measured: acquire no-op'd 20/20 children see the poison; acquire restored 0/20. The false claims in the test header and in the deterministic-repro design note are rewritten, and `check_dump_in_child` now asserts `prof_ok`/`dhat_ok` when the corresponding subsystem was actually started in the parent. Also adds a `test-fork-locks-spawn-prof-env` ctest variant (MI_TEST_FORK_SPAWN=1 + MIMALLOC_PROF=1) that spawns threads continuously during the 200 forks -- F1's scenario. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
`src/static.c` now includes the new `src/fork.c` under `#if !defined(_WIN32) && !defined(__wasi__)`; the amalgamator carries the same guard through, so the sys crate picks up the fork handlers on POSIX and compiles them away on Windows. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
…onestly The spawn workload now holds up to 64 threads live at a time (detached, each allocating 8 MiB and lingering) instead of joining every wave immediately, so the meta theap has to keep allocating fresh tld/theap storage rather than recycling one freed slot -- that is the `theap_meta_lock` nesting the re-derived lock order is about. It also REPLACES the heap-churn thread in spawn mode instead of running alongside it: sustained `mi_heap_new`/`mi_heap_delete` churn concurrent with sustained thread starts trips the pre-existing, fork-unrelated `mi_theap_is_valid` assertion (theap.c:71) that this PR already flagged -- reproduced here 3/5 runs with a standalone churn+spawn program that never calls fork(), and 0/6 with the spawner alone. Keeping the two workloads in separate ctest variants keeps this test's signal about fork safety instead of importing a known unrelated flake into CI. The header comment now states the variant's real scope: it is a timing-based workload, the `theap_meta -> arena/page-map` nestings are rare (a meta allocation only reaches them on a cold page), and running it against the OLD inverted order did not hang here in 200 forks. The deterministic evidence for the order is the MI_DEBUG>2 observed-edge checker in src/fork.c. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Resolves the `src/static.c` include-list conflict (#286's `heap-dump.c` next to #270's `fork.c`) and regenerates the vendored amalgamation over the merged tree. Also picks up #290's `timed_allocation_audit` fix, which was the standing rust-native failure on win-gnu. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Update: review round 2 (F1 + F2)Commits:
F1 — the order is now derived, not assertedYou were right: the outer steps were never re-derived.
Derived order — a topological order of that graph, which is not one walk per subprocess (a process-global lock sits between two per-subprocess levels, and a heap's three locks do not share a level), so prepare runs one pass per level: Note
Detector verified end to end: deliberately swapping the documented levels of and abort. Restored: silent, and the full 40-test Debug+FULL suite runs clean with no violation reported — i.e. nothing the suite exercises contradicts the derived order. Rule 6: handlers, order table, checker and test hooks moved to a new F2 — the deterministic hook now discriminatesYou were right that it had none: the child re-inits
The false claims in the file header (lines 31-36) and in the deterministic-repro design note (142-160) are rewritten; Honest scope of the new stress variantNew ctest variant
Verification
CI on |
|
Opus review (three rounds): APPROVE. Final round reproduced both proofs: swapping two documented levels trips the MI_DEBUG>2 lock-order detector ( Follow-up (non-blocking, tracked on #264): anonymous Merging; only red is the designed |
…rate amalgamation) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
…, P4 #286) cargo run -p xtask -- amalgamate-c && amalgamate-h following the merge commit, which brought in src/fork.c (pthread_atfork, #270/#289) and src/heap-dump.c (#269/#286) from main. xtask check confirms the vendored amalgamation matches src/include again. Rust-only commit per CLAUDE.md rule 2. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
P5 (#289) landed a handler-only pthread_atfork design (src/fork.c) without a persistent "we are a forked child" flag, so the P6 teardown protocol's mi_heap_visit_page_claim (arena.c) was left with its forked-child branch deliberately dropped ("add it back when it lands"). Merging origin/main exposed the gap: test-fork-user-heap's case_a forks while a background thread churns a shared heap, and the child's mi_heap_delete walked into a page still queued on that (now-dead) thread's torn theap. The !mi_page_is_abandoned force-seize path took the page without reconciling its used/local_free/xthread_free bookkeeping, tripping mi_page_is_valid_init downstream -- a regression against a previously green test (confirmed passing 3/3 on origin/main alone via a side-by-side worktree, failing ~1/200 children on this branch). Fix, imported from oven-sh/mimalloc @ 942b8342 (MIT), issue #271 / Bun parity P6: - src/fork.c: add the missing `_mi_process_is_forked_child` flag (set once in `_mi_process_fork_child`, never cleared) that P5's design omitted. - src/arena.c: restore `mi_heap_visit_page_claim`'s forked-child branch, which re-derives page ownership from the page/arena bitmaps instead of trusting a dead thread's theap bookkeeping. - src/heap.c: `mi_heap_detach_theaps` now skips walking (and abandoning pages from) a theap whose owning thread did not survive the fork -- its pages are picked up by the claim-walk's forked-child branch instead. Verified: test-fork-user-heap 20x direct + in ctest (0/4000 fork-cycle failures across runs), full ctest suite (47/47) x3 clean, real ASan build (clang from ~/.clang-tool-chain, 46/46 + 4x direct fork-user-heap), and the imported P6 corpus (heap-teardown/heap-mt/heap-churn/heap-aba/ heap-delete-race/commit-fail) 20x each (140/140). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Issue #274 (Bun parity P9b). docs/bun-gap-analysis-2026-09-02.md re-runs the 2026-09-01 analysis's four checks against Bun's current pin: the scripts/build/deps/mimalloc.ts commit (942b8342) has not moved, and all five consumer files (mimalloc_sys.rs, MimallocArena.rs, MimallocWTFMalloc.h, BunJSCModule.h, heapStats-mimalloc.test.ts) are byte-identical to what was cached in that session -- no new gap exists at Bun's current pin, so no new sub-issue is filed. The rest of the doc is a status table for every item and gap ID (B1-B20) from the 2026-09-01 analysis against what has actually merged since (#276, #281, #284, #286, #289, #291, #297) versus what's still open (#299, #302, and the items tied to them): 7/9 required-before-pitch items done, 11/20 B-numbered gaps done, 1 partial, 0 new. docs/ci-gates.md gains a `bun-surface` row and a short section explaining why that CI job is temporarily continue-on-error (mi_on_thread_idle isn't on main yet) with a dated TODO for when to make it a hard gate. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Summary
pthread_atforkfork-safety handlers with adocumented lock-order contract, plus a POSIX repro test landed first per the
issue's Step 1.
src/subproc.cgains_mi_process_fork_prepare/parent/child, a 13-step lockorder documented in a comment block at the top of the file and self-checked in
MI_DEBUGbuilds (mi_fork_lock_order_assert).src/init.c'smi_process_init_once, POSIX only(
#if !defined(_WIN32) && !defined(__wasi__)) -- never per heap (see "what theissue got wrong" below for why that distinction matters).
alloc-override-zone.c: the introspectionforce_lock/force_unlock/reinit_lockcallbacks and the_malloc_fork_*DYLD interposeboth call the same handlers, made idempotent by a nesting guard.
is ordinary process memory (profiler/DHAT records come from the raw-OS-layer
arena per rule 4, never the hooked path) that survives fork() by plain
copy-on-write; only each subsystem's own lock needs resetting.
mi_prof_dump/mi_dhat_dumpare exercised in the child bytest-fork-locks.c.test/test-fork-user-heap.cimported fromoven-sh/mimalloc@942b8342(MIT),with the two cases needing the not-yet-landed scavenger/tld registry disabled
as
#if 0 // Phase 7(they don't compile against this tree).MIMALLOC_FORKS.md'spthread_atforkrow -> IMPORTED.Repro (issue Step 1)
test/test-fork-locks.c: a churn thread holdsheaps_lock/arena_reserve_lock(
mi_heap_new/mi_heap_delete+ a large allocation in a loop) while the mainthread
fork()s 200 times; each child doesmi_malloc(64)/mi_free/_exit(0),watchdog-guarded (5s
alarm()+waitpid).At the committed test's own scale (1 churn thread, 200 serialized forks) this
reproduced 0/200 failures on the pre-#270 tree, across 10+ runs (~2,000 forks
total) on this machine -- the race window is narrow, matching Bun's own
"Case A is probabilistic" caveat for their equivalent test. Since the issue asks
for an observed failure rate, I went further with an ad hoc, heavier
multi-threaded stress harness (not part of the committed suite: several forking
threads racing several heap-churn threads). That did reproduce the hazard
concretely on the pre-#270 tree: multiple single-threaded child processes left
permanently hung, confirmed via
/proc/<pid>/wchan=futex_do_waitwithThreads: 1, never progressing (a single-threaded process blocked forever on afutex is the unambiguous signature of an inherited, permanently-locked mutex --
nothing else produces it). After the handlers, the same heavier harness produced
zero hangs.
Verification
test-fork-locks/test-fork-user-heap: green x20 in Release, green x20 inDebug+
MI_DEBUG_FULL+MI_PPROF=ON, no hangs.Full
ctestsuite (36 tests, Debug+FULL+MI_PPROF=ON; 24 tests,MI_PPROF=OFF): 100% pass in both.uv run ci/verify_local.py --keep-going:asanis environmentally red in this sandbox:sanitizer/asan_interface.hisnot installed, so CMake falls back to
MI_TRACK_ASAN=OFFandverify_localcorrectly flags that as a failed gate. Confirmed this is unrelated to this PR --
even
mimalloc-test-api(no fork, untouched by this change) segfaults with zeroASan output under the same manual build.
A separate manual
gcc -fsanitize=address -fno-omit-frame-pointerbuild (notthrough
verify_local,MI_DEBUG=2) was attempted per the task instructions:it compiles clean, but running any test under it segfaults before printing an
ASan report (confirmed on
test-apitoo, not fork-specific) -- consistent withthe same environmental gap, not a regression from this PR.
pyright(uv run --with 'pyright[nodejs]==1.1.411' pyright): 0 errors.cargo run -p xtask -- amalgamate-c && amalgamate-h && check: clean;cargo test -p mimalloc-pprof: all green (regenerated in a separate, rust-onlycommit per rule 2).
Known limitations / what the issue got wrong
mi_tld_t::theaps_lockis not covered. Bun's ported skeleton quiesces aper-subprocess
tldregistry (sp->tlds/tlds_lock) that walks every livethread's
tld->theaps_lock. That registry is scavenger/park infrastructurethat does not exist in this tree yet (lands with META: Bun parity — gaps, closure plan, and documentation corrections before proposing a rebase to oven-sh/bun #264 item 7 / Bun parity P7: background scavenger, page hole purging, and mi_on_thread_idle #272). Per the
issue's own instruction to "port only the lock skeleton... leave a clearly
marked
// Phase 7: scavengerhook point," this gap is documented at everyaffected site in
subproc.cand inMIMALLOC_FORKS.md, rather thanapproximated with an ad hoc walk (a heap's
theapslist can reach the sametldthrough more than one theap -- one thread, several heaps -- and lockinga non-recursive mutex twice inside the handler itself would turn a rare hang
into a guaranteed one).
mi_fork_depthdesign (Bun's, as specified by the issue) assumesfork() calls are serialized across threads. glibc does not do this --
verified empirically with a minimal
pthread_atforkprobe: concurrentfork()calls from different threads interleave their prepare/parenthandlers essentially every time under load. The single-process-wide-atomic
nesting counter, exactly as ported, is only correct for same-thread nesting
(the macOS zone callback +
pthread_atforkfiring together for onefork()); under genuinely concurrent multi-threadedfork()it produced areal
internal_lock_release_by_non_owner(an ABA race across overlappingfork "generations", caught by the P1 reentrancy checker -- not a false
positive). Fixed here:
mi_fork_depthis now a per-thread (mi_decl_thread)reentrancy count, and a real mutex (
mi_fork_serialize_lock) gives truecross-thread exclusion around one fork "generation". This is not called out
in the issue at all; I found it during evidence-gathering for the repro
numbers above and fixed it rather than leaving a known-broken design in a
safety-critical path.
for the user): a pre-existing assertion failure
(
mi_theap_is_valid,theap.c:71) under sustained multi-threadedmi_heap_new/mi_heap_deletechurn -- reproduces with zero forkinginvolved (a single churn thread run alone for ~90s trips it), on both the
pre-Bun parity P5: pthread_atfork fork-safety handlers with a POSIX repro #270 and post-Bun parity P5: pthread_atfork fork-safety handlers with a POSIX repro #270 tree. Out of scope for this PR; worth its own issue.
under
dockur/macospending a golden image (per.github/workflows/cross.yml).So the zone/DYLD-interpose wiring in
alloc-override-zone.ciscompile-verified only in this PR -- not exercised by a running macOS test.
Merge gates checklist (CLAUDE.md rule 3)
c-uniton ubuntu withMI_PPROF=ON-- verified locally (verify_local +manual full ctest), CI pending.
MI_PPROF=OFFjob -- verified locally (manual build + ctest), CI pending.rust-native-- verified locally (cargo test -p mimalloc-pprof), CIpending.
here); relying on CI. macOS execution is cross-built/compile-only per above.
Closes #270
🤖 Generated with Claude Code
https://claude.ai/code/session_01YT4jVokb2gdT8ngFrH8i8S
Update: fixed after Opus review (both blockers reproduced and fixed)
_mi_process_is_initializedwas declared only insideprim-tls.h's#if MI_TLS_MODEL_LOCALbranch; macOS (pthreads TLS model) and Windows don'ttake that branch. Fixed: unconditional
externininternal.h(droppedpage.c's now-redundant local extern); the whole fork-handler definitionblock in
subproc.cis now guarded with the same#if !defined(_WIN32) && !defined(__wasi__)init.calready uses to callit, so it's not dead code there either (rule 6).
MIMALLOC_PROF=1):reproduced exactly as described (3/3 hangs, Release,
MI_PPROF=ON).Root cause confirmed: Bun's ported rule assumed hook locks
(
prof_lock/dhat_lock/memevt_cb_lock) are never taken from inside theallocation path itself, which is false in this tree (
_mi_prof_on_allocetc. are called from
alloc.c/page.cwhile a heap'sarena_pages_lockcan still be held up the stack). Fixed: hook locks now sit innermost in the
documented order, alongside
out_buf_lock; also corrected theheap_mainvs. non-main-heaparena_pages_lockordering per the review'snote on
mi_heap_ensure_arena_pages's real nesting. Verified: the exactMIMALLOC_PROF=1Release repro now passes 3/3 (and 20x); addedMIMALLOC_DHAT=1/
MIMALLOC_MEMORY_EVENTS=1ctest variants alongside it so a futurereordering regresses loudly in CI.
mi_decl_threadviolated the codebase's own Bun parity P1: bump upstream overlay pin bcee5a88 -> 6def7be9 (Bun's merge-base) + carry glibc 2.44 free(NULL) fix #266 rule): fixed --mi_fork_depth/mi_fork_lock_levelare no longermi_decl_thread.Replaced with a shared
mi_fork_owner(_Atomic mi_threadid_t) + plainintdepth, both protected by a real mutex (mi_fork_serialize_lock),needing no TLS at all. This also fixes the asymmetric-guard-latch gap
(
parent/childnow check ownership symmetrically withprepareinsteadof blindly decrementing).
dhat_once/memevt_oncenow reset in the child (new_mi_atomic_once_fork_child_resethelper) unless already resolved; addedMI_DEBUG-only test hooks (_mi_test_hold_heaps_locketc.) sotest-fork-locks.chas a deterministic repro alongside the probabilisticone (which measured 0/200 on
main, confirmed near-zero discriminatingpower on this machine).
mi_prof_visit/prof_lockinversion (visitor callback holds the lock, so an allocating visitor
inverts the alloc-hook nesting) as a "visitor must not allocate" contract
in
profile.h-- out of scope to fix in a fork-safety phase.Verified:
test-fork-locks(base + all 3 env variants) andtest-fork-user-heapgreen 20x in Debug+FULL and 20x in Release, includingthe exact review repro (
MIMALLOC_PROF=1, Release) now 3/3 clean where itwas 3/3 hung. Full
ctestgreen in debug-full (39 tests), release (32),and
MI_PPROF=OFF(27).uv run ci/verify_local.py --keep-going: 9/11 pass(
asanstill environmentally red -- confirmed viatest-api, unrelated tothis PR). Rust amalgamation regenerated in a separate commit;
cargo test -p mimalloc-pprofgreen.Commits:
73f22a43(original),da934391(original rust),ee890758(review fixes),
77a72e4d(review-fix rust amalgamation).