Repository navigation
Conversation
…essure bmalloc's libpas allocator causes segmentation faults on Windows during GC sweep (MarkedBlock::isNewlyAllocatedStale) under memory pressure. The root cause is that bmalloc's SystemHeap is unimplemented on Windows — all its methods call RELEASE_BASSERT_NOT_REACHED(). This fix: 1. Implements SystemHeap on Windows using mimalloc as the backing allocator (BmallocSystemHeapOverride.cpp). The object file's symbols override bmalloc.lib's unimplemented stubs at link time. 2. Sets Malloc=1 env var early in main() to trigger bmalloc's system heap bypass, routing all allocations through our mimalloc-backed SystemHeap instead of libpas. Fixes #21569 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
Updated 7:12 AM PT - Mar 18th, 2026
❌ Your commit
🧪 To try this PR locally: bunx bun-pr 28230That installs a local version of the PR into your bun-28230 --bun |
|
Found 8 issues this PR may fix:
🤖 Generated with Claude Code |
WalkthroughThis PR implements Windows-specific memory allocation improvements by introducing a SystemHeap implementation for bmalloc backed by mimalloc, updating the Windows build configuration to link required WebKit libraries, and setting an environment variable on Windows startup to activate this custom heap behavior. Changes
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 📝 Coding Plan
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/bun.js/bindings/BmallocSystemHeapOverride.cpp`:
- Around line 101-118: The m_sizeMap bookkeeping currently uses operator[]
(m_sizeMap[result] = size) and operator[] lookups (m_sizeMap[base]) which can
silently insert defaults; change the allocation path to insert with a
non-overwriting operation (e.g., emplace/insert) and assert the insert succeeded
(no duplicate key) in the allocation function (where result is stored), and
change SystemHeap::freeLarge to use find() to locate the iterator, assert the
iterator != end (fail if missing), read the size from the iterator, then call
erase(it) and assert erase removed one entry; do not use operator[] anywhere for
m_sizeMap to avoid implicit insertion.
- Around line 23-27: Add the missing source to the BUN_CXX_SOURCES list so the
override is compiled: in BuildBun.cmake, after the comment that documents the
override and before the if(DEBUG) block, append the
BmallocSystemHeapOverride.cpp path to the BUN_CXX_SOURCES variable (i.e., add a
list(APPEND BUN_CXX_SOURCES
${CWD}/src/bun.js/bindings/BmallocSystemHeapOverride.cpp) directive) so the
link-time override in src/bun.js/bindings/BmallocSystemHeapOverride.cpp is built
and the bmalloc stubs are replaced.
In `@src/main.zig`:
- Around line 24-33: Move the Windows allocator switch so it runs as the very
first statement inside main(): check Environment.isWindows and call
_bun.c._putenv("Malloc=1") before any other initialization (in particular before
_bun.crash_handler.init() or any code that may touch WTF/JSC/bmalloc). Ensure
the if (Environment.isWindows) { _ = _bun.c._putenv("Malloc=1"); } block appears
at the top of main() so bmalloc's Environment initializes using SystemHeap
reliably.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: c9801825-2964-4294-b8dd-b0fc8d994bc0
📒 Files selected for processing (4)
cmake/targets/BuildBun.cmakesrc/bun.js/bindings/BmallocSystemHeapOverride.cppsrc/c-headers-for-zig.hsrc/main.zig
| * Link-time override: | ||
| * This object file defines the same symbols as bmalloc.lib's | ||
| * SystemHeap.cpp.o. Since object files are processed before static | ||
| * libraries, the linker uses these definitions and skips bmalloc.lib's | ||
| * unimplemented stubs. |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show how Bun collects C++ sources, then confirm the new TU is listed.
rg -n -C1 'absolute_sources\(BUN_CXX_SOURCES' cmake/targets/BuildBun.cmake
rg -n --fixed-strings 'BmallocSystemHeapOverride.cpp' cmake/sources/CxxSources.txtRepository: oven-sh/bun
Length of output: 390
🏁 Script executed:
# Check if CxxSources.txt exists anywhere or if it's generated
fd -name '*CxxSources*' .
# Look for patterns of how sources might be added to BUN_CXX_SOURCES
rg -n 'BUN_CXX_SOURCES' cmake/targets/BuildBun.cmake
# Check if BmallocSystemHeapOverride.cpp is referenced directly anywhere
rg -n 'BmallocSystemHeapOverride' cmake/
# Look at the structure of cmake/sources/ to understand what files exist there
ls -la cmake/sources/ 2>/dev/null || echo "cmake/sources/ not found"Repository: oven-sh/bun
Length of output: 732
🏁 Script executed:
# Read around line 1270 where BmallocSystemHeapOverride is mentioned
sed -n '1265,1280p' cmake/targets/BuildBun.cmake
# Check if BmallocSystemHeapOverride.cpp is being appended anywhere
rg -n 'list\(APPEND BUN_CXX_SOURCES' cmake/targets/BuildBun.cmake | head -20
# Check the full Windows-specific section where rescle is appended
sed -n '755,765p' cmake/targets/BuildBun.cmakeRepository: oven-sh/bun
Length of output: 1236
🏁 Script executed:
# Comprehensive search for BmallocSystemHeapOverride being added to any target/sources
rg -i 'BmallocSystemHeapOverride' cmake/Repository: oven-sh/bun
Length of output: 158
BmallocSystemHeapOverride.cpp is not being compiled—missing list(APPEND BUN_CXX_SOURCES ...) directive.
The override file is documented in the comment at cmake/targets/BuildBun.cmake:1270, but it is never added to the build. Add this line after the comment and before the if(DEBUG) block:
list(APPEND BUN_CXX_SOURCES ${CWD}/src/bun.js/bindings/BmallocSystemHeapOverride.cpp)Without this, the entire override mechanism is non-functional and Windows will continue to use the problematic bmalloc stubs.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/bun.js/bindings/BmallocSystemHeapOverride.cpp` around lines 23 - 27, Add
the missing source to the BUN_CXX_SOURCES list so the override is compiled: in
BuildBun.cmake, after the comment that documents the override and before the
if(DEBUG) block, append the BmallocSystemHeapOverride.cpp path to the
BUN_CXX_SOURCES variable (i.e., add a list(APPEND BUN_CXX_SOURCES
${CWD}/src/bun.js/bindings/BmallocSystemHeapOverride.cpp) directive) so the
link-time override in src/bun.js/bindings/BmallocSystemHeapOverride.cpp is built
and the bmalloc stubs are replaced.
| { | ||
| LockHolder locker(mutex()); | ||
| m_sizeMap[result] = size; | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| void SystemHeap::freeLarge(void* base) | ||
| { | ||
| if (!base) | ||
| return; | ||
|
|
||
| size_t size; | ||
| { | ||
| LockHolder locker(mutex()); | ||
| size = m_sizeMap[base]; | ||
| size_t numErased = m_sizeMap.erase(base); | ||
| RELEASE_BASSERT(numErased == 1); |
There was a problem hiding this comment.
Use non-inserting map operations for m_sizeMap bookkeeping.
Line 116 inserts a default entry when base is missing, so numErased == 1 still passes and this can fall through to vmDeallocate(base, 0) instead of tripping the invariant. Line 103 has the dual problem: it silently overwrites duplicate keys. This allocator metadata should use an asserting insert on allocation and a find/erase-by-iterator path on free.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/bun.js/bindings/BmallocSystemHeapOverride.cpp` around lines 101 - 118,
The m_sizeMap bookkeeping currently uses operator[] (m_sizeMap[result] = size)
and operator[] lookups (m_sizeMap[base]) which can silently insert defaults;
change the allocation path to insert with a non-overwriting operation (e.g.,
emplace/insert) and assert the insert succeeded (no duplicate key) in the
allocation function (where result is stored), and change SystemHeap::freeLarge
to use find() to locate the iterator, assert the iterator != end (fail if
missing), read the size from the iterator, then call erase(it) and assert erase
removed one entry; do not use operator[] anywhere for m_sizeMap to avoid
implicit insertion.
| // Force bmalloc to use SystemHeap (mimalloc) instead of libpas on Windows. | ||
| // bmalloc's libpas allocator causes GC crashes under memory pressure on | ||
| // Windows. Setting "Malloc" causes bmalloc::Environment to route all | ||
| // allocations through SystemHeap, which we implement using mimalloc | ||
| // (see BmallocSystemHeapOverride.cpp). Must be set before any bmalloc | ||
| // allocation triggers Environment initialization. | ||
| // See: https://github.com/oven-sh/bun/issues/21569 | ||
| if (Environment.isWindows) { | ||
| _ = _bun.c._putenv("Malloc=1"); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Make the allocator switch the first statement in main().
Line 22 still runs before this block, so the workaround currently depends on _bun.crash_handler.init() never touching WTF/JSC allocation. Moving _putenv("Malloc=1") to the top removes that hidden ordering requirement and makes the fix robust against future refactors.
Proposed reorder
pub fn main() void {
- _bun.crash_handler.init();
-
// Force bmalloc to use SystemHeap (mimalloc) instead of libpas on Windows.
// bmalloc's libpas allocator causes GC crashes under memory pressure on
// Windows. Setting "Malloc" causes bmalloc::Environment to route all
// allocations through SystemHeap, which we implement using mimalloc
// (see BmallocSystemHeapOverride.cpp). Must be set before any bmalloc
// allocation triggers Environment initialization.
// See: https://github.com/oven-sh/bun/issues/21569
if (Environment.isWindows) {
_ = _bun.c._putenv("Malloc=1");
}
+
+ _bun.crash_handler.init();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/main.zig` around lines 24 - 33, Move the Windows allocator switch so it
runs as the very first statement inside main(): check Environment.isWindows and
call _bun.c._putenv("Malloc=1") before any other initialization (in particular
before _bun.crash_handler.init() or any code that may touch WTF/JSC/bmalloc).
Ensure the if (Environment.isWindows) { _ = _bun.c._putenv("Malloc=1"); } block
appears at the top of main() so bmalloc's Environment initializes using
SystemHeap reliably.
There was a problem hiding this comment.
This PR adds a new memory allocator override for Windows (287-line BmallocSystemHeapOverride.cpp) that relies on link-time symbol resolution and bmalloc internals — a human should verify the SystemHeap implementation correctness and the link-time override strategy before merging.
Extended reasoning...
Overview
This PR fixes Windows GC crashes under memory pressure by bypassing bmalloc/libpas. It adds a new BmallocSystemHeapOverride.cpp (287 lines) implementing bmalloc::SystemHeap backed by mimalloc, sets Malloc=1 env var early in main.zig to trigger bmalloc's system heap bypass, adds <stdlib.h> to c-headers-for-zig.h for _putenv, and adds explanatory comments to BuildBun.cmake.
Security risks
Memory allocator overrides are inherently security-sensitive. An incorrect implementation could lead to memory corruption, use-after-free, or other exploitable conditions. The memalignLarge/freeLarge functions use a m_sizeMap that must be correctly maintained under concurrent access — while a lock is used, the correctness of the locking strategy relative to bmalloc's threading model needs human verification. Setting environment variables (Malloc=1) at startup could theoretically be observable by other code.
Level of scrutiny
This warrants careful human review. It touches the allocator subsystem, which is one of the most correctness-critical parts of a runtime. The link-time symbol override approach (object files taking precedence over static library symbols) is a well-known linker behavior but relies on MSVC/link.exe specifics. The new C++ file must exactly match bmalloc's SystemHeap interface — any mismatch in method signatures, calling conventions, or semantics could cause subtle runtime failures. The test plan also has unchecked Windows CI items.
Other factors
- The PR is labeled
claude, indicating it was auto-generated by Claude Code - No human reviewers have weighed in yet
- The approach of overriding SystemHeap while keeping bmalloc.lib linked is a pragmatic workaround, but the long-term plan (rebuilding WebKit prebuilts) should be tracked
- The
BmallocSystemHeapOverride.cppwill be automatically picked up by the build via thesrc/bun.js/bindings/*.cppglob inSources.json
Summary
MarkedBlock::isNewlyAllocatedStale) caused by bmalloc's libpas allocator under memory pressureSystemHeapon Windows using mimalloc as the backing allocator (upstream WebKit leaves this unimplemented — all methods crash withRELEASE_BASSERT_NOT_REACHED())Malloc=1environment variable early inmain()to trigger bmalloc's system heap bypass, routing all allocations through our mimalloc-backed SystemHeap instead of libpasHow it works
BmallocSystemHeapOverride.cpp— Provides a workingbmalloc::SystemHeapfor Windows using mimalloc (mi_malloc,mi_malloc_aligned,mi_realloc,mi_free). At link time, these symbols override bmalloc.lib's unimplemented stubs because object files are resolved before static libraries.main.zig— SetsMalloc=1via_putenvbefore any bmalloc initialization. bmalloc'sEnvironmentclass reads this and setsshouldBmallocAllocateThroughSystemHeap() = true, causing all allocations to route throughSystemHeap.c-headers-for-zig.h— Adds<stdlib.h>to Windows includes so_putenvis available to Zig code.Why bmalloc.lib is still linked
WTF.libreferences ~230 bmalloc symbols, so bmalloc.lib cannot be removed without rebuilding WebKit prebuilts. This fix works alongside bmalloc.lib by overriding only theSystemHeapsymbols. Once oven-sh/WebKit prebuilts are rebuilt without libpas on Windows, bmalloc.lib can be removed entirely.Fixes #21569
Test plan
bun bdcompiles successfully on Linuxbun run zig:check-windowspasses (Windows cross-compilation check)bun run zig:check-allpasses (all platform compilation checks)🤖 Generated with Claude Code