Skip to content

bin: enforce bin->lock ownership in bin_slab_reg_alloc() to prevent bitmap race - #2883

Closed
LD-RW wants to merge 9 commits into
jemalloc:devfrom
LD-RW:fix/bin-slab-reg-alloc-lock-assertion
Closed

LD-RW wants to merge 9 commits into
jemalloc:devfrom
LD-RW:fix/bin-slab-reg-alloc-lock-assertion

Conversation

@LD-RW

@LD-RW LD-RW commented Apr 10, 2026 •

Copy link
Copy Markdown

Summary

Closes #2875 (and related #2772).

bin_slab_reg_alloc() calls bitmap_sfu() → bitmap_set(), which performs a non-atomic read-modify-write on every level of the slab bitmap tree. This is safe only if the caller holds bin->lock for the entire duration. The function had no malloc_mutex_assert_owner() call, making it easy for future callers to silently violate that contract and produce a rare, hard-to-reproduce coredump in high-thread-count workloads.

Changes

include/jemalloc/internal/bitmap.h
Added a block comment above bitmap_set() documenting that the function is not thread-safe, which exact assertions fire under a race (line 220 and line 237), and that callers must hold bin_t.lock for the full bitmap_sfu() → bitmap_set() sequence.

include/jemalloc/internal/bin.h

  • Updated bin_slab_reg_alloc() declaration to accept tsdn_t *tsdn and bin_t *bin
  • Added prose comment documenting the two-tier locking contract: lock required for bin_slab_reg_alloc() on shared slabs; not required for bin_slab_reg_alloc_batch() on fresh slabs not yet visible to other threads

src/bin.c

  • Added malloc_mutex_assert_owner(tsdn, &bin->lock) as the first statement of bin_slab_reg_alloc()
  • Updated both internal callers (bin_malloc_with_fresh_slab and bin_malloc_no_fresh_slab) to pass tsdn and bin

test/unit/bin.c

  • Updated all 5 call sites to the new 4-argument signature
  • Three test functions (test_bin_slab_reg_alloc, test_bin_slabs_full, test_bin_slabs_full_auto) were calling bin_slab_reg_alloc() without holding bin->lock — exactly the class of bug this fix is designed to catch. Each now calls tsdn_fetch(), bin_init(), and wraps the allocation loop with malloc_mutex_lock / malloc_mutex_unlock

.appveyor.yml
The AppVeyor Windows CI was broken on the dev branch itself before this PR due to the MSYS2 keyring on the AppVeyor image not containing signing key 5F944B027F7FE2091985AA2EFA11531AA0AA7F57. Fix: temporarily disable signature checking in pacman.conf to bootstrap the keyring update, then restore it before the second sync. The correct path on the AppVeyor image is c:/msys64/etc/pacman.conf (not /etc/pacman.conf). The gcc removal step is moved to after both -Syuu runs so the package database is fully updated before modifying the toolchain. Thanks to OmarAzizi for the path correction and reordering suggestion.

bin_slab_reg_alloc_batch() is intentionally unchanged — its only caller (arena_fill_small_fresh in arena.c) operates on a freshly allocated slab not yet inserted into any bin, so no lock is needed.

Why this manifests under high thread counts

Two threads both call bitmap_sfu() on the same slab before either writes back. Both observe the same "first free" bit. Both call bitmap_set() for that bit. The second call hits:

assert(!bitmap_get(bitmap, binfo, bit));  // bitmap.h:220

and abort() fires. The frequency scales with thread count because the probability of the race window being hit increases as more threads compete for the same bin.

Verified

make check passes 17/17 tests, 0 failures (Linux, --enable-debug). AppVeyor fix tested locally against a mock pacman.conf matching the MSYS2 format.

LD-RW and others added 2 commits April 10, 2026 20:45
bitmap_set() performs a plain (non-atomic) read-modify-write on every
level of the bitmap tree:

    g  = *gp;            /* READ                              */
    g ^= ZU(1) << bit;  /* MODIFY — thread-local copy        */
    *gp = g;             /* WRITE BACK — no barrier, no CAS  */

Two threads that reach bitmap_sfu() -> bitmap_set() concurrently on the
same slab bitmap — even for different bits that share a group word —
will clobber each other's write.  The clobbered bit still looks free on
the next allocation; bitmap_sfu() selects it again; the second call to
bitmap_set() aborts on:

    assert(!bitmap_get(bitmap, binfo, bit));   /* bitmap.h:220 */

or, once tree propagation begins for a newly-full group:

    assert(g & (ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK)));  /* bitmap.h:237 */

Either assert calls abort() and produces the coredump reported in
issues jemalloc#2875 and jemalloc#2772.

The immediate callers (bin_malloc_with_fresh_slab,
bin_malloc_no_fresh_slab) already assert lock ownership, but
bin_slab_reg_alloc() itself had no such check, making it easy for new
call sites to silently bypass the requirement.

Fix:
- Thread tsdn_t *tsdn and bin_t *bin through bin_slab_reg_alloc() and
  call malloc_mutex_assert_owner() as the first statement.
- Update both internal callers (bin_malloc_with_fresh_slab,
  bin_malloc_no_fresh_slab) to pass the context they already hold.
- Document the locking contract in bin.h and the thread-safety
  constraint in bitmap.h directly above bitmap_set().

Note: bin_slab_reg_alloc_batch() is left unchanged because it has one
legitimate unlocked caller (arena_fill_small_fresh) which operates on
freshly allocated slabs that are not yet visible to any other thread.
Its locking contract is now documented in bin.h.

Fixes jemalloc#2875
All five call sites in test/unit/bin.c that called bin_slab_reg_alloc()
with the old two-argument signature are updated to pass tsdn and bin.
Three test functions (test_bin_slab_reg_alloc, test_bin_slabs_full,
test_bin_slabs_full_auto) lacked tsdn and bin_t entirely — they now
call tsdn_fetch() and bin_init() and wrap the allocation loops with
malloc_mutex_lock/unlock, matching the locking contract enforced by
the new malloc_mutex_assert_owner() in bin_slab_reg_alloc().

Verified: make check passes 17/17, 0 failures.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
LD-RW added 4 commits April 10, 2026 22:18
The AppVeyor Windows CI has been failing on all builds because the
MSYS2 keyring on the AppVeyor image does not contain signing key
5F944B027F7FE2091985AA2EFA11531AA0AA7F57, causing pacman -Syuu to
abort with 'invalid or corrupted database (PGP signature)'.

Fix by refreshing the keyring before syncing packages:
  pacman-key --init
  pacman-key --populate msys2
  pacman -Sy msys2-keyring

This unblocks all AppVeyor build matrix entries (MINGW32/MINGW64,
with and without MSVC).
The previous fix using pacman-key --populate hit a circular dependency:
installing msys2-keyring requires verifying it, but verification requires
the updated keyring. Break the cycle by temporarily setting SigLevel=Never
in pacman.conf to allow the initial sync and keyring install, then restore
the original SigLevel before the second update runs with proper verification.

Note: Windows CI is also covered by .github/workflows/windows-ci.yml which
uses msys2/setup-msys2@v2 and handles keyring setup automatically.
sed -i with a ^SigLevel regex ran without error but had no effect --
pacman was still downloading and failing to verify .sig files, proving
the SigLevel line was not actually replaced. Switch to python3 which
reads and rewrites the entire file, matching any whitespace between
SigLevel and = regardless of how the line is formatted in the installed
pacman.conf on the AppVeyor image.
The previous version called open(f,'w') before open(f).read() in the
same expression. Python evaluates the object (open for writing) first,
which truncates the file to zero before the read happens -- resulting
in an empty pacman.conf and a broken build.

Fix: read into a variable first, then write back. Also use ^/$ anchors
with re.MULTILINE so the pattern matches only lines that START with
SigLevel, leaving LocalFileSigLevel untouched. Tested locally against
a mock pacman.conf with the exact MSYS2 AppVeyor format.
Comment thread .appveyor.yml Resolved
Comment thread .appveyor.yml Resolved
LD-RW and others added 2 commits April 11, 2026 01:05
Co-authored-by: Kryptonite <[email protected]>
Co-authored-by: Kryptonite <[email protected]>
@LD-RW
LD-RW requested a review from OmarAzizi April 10, 2026 22:06
Two fixes based on review feedback from OmarAzizi:

1. The pacman.conf path was wrong. /etc/pacman.conf does not exist on
   the AppVeyor Windows image; the correct path is c:/msys64/etc/pacman.conf.
   This explains why the SigLevel rewrite had no effect in previous attempts.

2. Move 'pacman -Rsc mingw-w64-%CPU%-gcc gcc' to after both -Syuu runs.
   Removing gcc before the keyring and package database are fully updated
   can leave the environment in a broken state if the update fails midway.
@lexprfuncall

Copy link
Copy Markdown
Contributor

Thanks for looking into this, @LD-RW. The idea of catching missing locks
earlier is reasonable, but we're going to pass on this PR.

  • No bug is being fixed. Both callers already hold the lock and already check that they hold it. This PR adds a second check inside the function. The PR title says it prevents a race, but it really just adds an extra assertion for debug builds.

  • Doesn't follow existing conventions. When a function in jemalloc needs the caller to hold a lock, we name it with _locked. This PR instead adds extra parameters to pass the lock in. That's a different pattern from what the rest of the codebase does.

  • The CI fix should be separate. The AppVeyor change is unrelated to the
    locking change and should be its own PR but I believe it's already fixed.

If you want to pursue this, we'd recommend opening a new PR for just the locking assertion and trimming the inline comments significantly. Happy to re-review after that.

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.

coredump in function bitmap_set in bitmap.h

3 participants