Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cmake/targets/BuildBun.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -1265,6 +1265,14 @@ if(BUN_LINK_ONLY)
endif()

if(WIN32)
# bmalloc/libpas causes GC crashes on Windows under memory pressure
# (see https://github.com/oven-sh/bun/issues/21569). Bun overrides
# bmalloc's SystemHeap on Windows (BmallocSystemHeapOverride.cpp) to use
# mimalloc instead of the unimplemented stubs. Combined with setting
# Malloc=1 at startup, this bypasses libpas for all allocations.
# bmalloc.lib is still linked because WTF.lib references bmalloc symbols.
# Once oven-sh/WebKit prebuilts are rebuilt without libpas on Windows,
# bmalloc.lib can be removed entirely.
if(DEBUG)
target_link_libraries(${bun} PRIVATE
${WEBKIT_LIB_PATH}/WTF.lib
Expand Down
287 changes: 287 additions & 0 deletions src/bun.js/bindings/BmallocSystemHeapOverride.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,287 @@
/**
* Working SystemHeap implementation for Windows using mimalloc.
*
* bmalloc's SystemHeap is unimplemented on Windows (all methods crash with
* RELEASE_BASSERT_NOT_REACHED). This file provides a functional replacement
* that uses mimalloc for allocations.
*
* Combined with setting the "Malloc" environment variable at process startup,
* this causes bmalloc/libpas to redirect all allocations through this
* SystemHeap instead of using libpas directly. This avoids GC crashes caused
* by libpas instability on Windows under memory pressure.
*
* See: https://github.com/oven-sh/bun/issues/21569
* https://github.com/oven-sh/bun/issues/28097
*
* How it works:
* 1. Bun sets Malloc=1 env var early in main() (see src/main.zig)
* 2. bmalloc's Environment reads Malloc=1 and sets
* shouldBmallocAllocateThroughSystemHeap() = true
* 3. All bmalloc allocations route through SystemHeap
* 4. This file provides SystemHeap using mimalloc instead of crashing
*
* 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.
Comment on lines +23 to +27

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 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.txt

Repository: 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.cmake

Repository: 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.

*/

#include <bmalloc/BPlatform.h>

// Only override on Windows where SystemHeap is unimplemented.
#if BOS(WINDOWS)

#include <bmalloc/SystemHeap.h>
#include <bmalloc/Algorithm.h>
#include <bmalloc/BAssert.h>
#include <bmalloc/VMAllocate.h>
#include "mimalloc.h"

#if BENABLE(LIBPAS)
#include <bmalloc/pas_system_heap.h>
#endif

namespace bmalloc {

SystemHeap* systemHeapCache { nullptr };

BALLOW_DEPRECATED_DECLARATIONS_BEGIN
DEFINE_STATIC_PER_PROCESS_STORAGE(SystemHeap);
BALLOW_DEPRECATED_DECLARATIONS_END

SystemHeap::SystemHeap(const LockHolder&)
: m_pageSize(vmPageSize())
{
}

void* SystemHeap::malloc(size_t size, FailureAction action)
{
void* result = mi_malloc(size);
RELEASE_BASSERT(action == FailureAction::ReturnNull || result);
return result;
}

void* SystemHeap::memalign(size_t alignment, size_t size, FailureAction action)
{
void* result = mi_malloc_aligned(size, alignment);
RELEASE_BASSERT(action == FailureAction::ReturnNull || result);
return result;
}

void* SystemHeap::realloc(void* object, size_t size, FailureAction action)
{
void* result = mi_realloc(object, size);
RELEASE_BASSERT(action == FailureAction::ReturnNull || result);
return result;
}

void SystemHeap::free(void* object)
{
mi_free(object);
}

void SystemHeap::scavenge()
{
mi_collect(false);
}

void SystemHeap::dump()
{
}

// memalignLarge / freeLarge use virtual memory directly (same as upstream).
void* SystemHeap::memalignLarge(size_t alignment, size_t size)
{
alignment = roundUpToMultipleOf(m_pageSize, alignment);
size = roundUpToMultipleOf(m_pageSize, size);
void* result = tryVMAllocate(alignment, size);
if (!result)
return nullptr;
{
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);
Comment on lines +101 to +118

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

}

vmDeallocate(base, size);
}

SystemHeap* SystemHeap::tryGetSlow()
{
SystemHeap* result;
if (Environment::get()->isSystemHeapEnabled()) {
systemHeapCache = SystemHeap::get();
result = systemHeapCache;
} else {
systemHeapCache = systemHeapDisabled();
result = nullptr;
}
RELEASE_BASSERT(systemHeapCache);
return result;
}

} // namespace bmalloc

// libpas integration — same as upstream, but our SystemHeap actually works.
#if BENABLE(LIBPAS)

#if BUSE(LIBPAS)

using namespace bmalloc;

bool pas_system_heap_is_enabled(pas_heap_config_kind kind)
{
switch (kind) {
case pas_heap_config_kind_bmalloc:
return !!SystemHeap::tryGet();
case pas_heap_config_kind_jit:
case pas_heap_config_kind_pas_utility:
return false;
default:
BCRASH();
return false;
}
}

bool pas_system_heap_should_supplant_bmalloc(pas_heap_config_kind kind)
{
SystemHeap* heap;
switch (kind) {
case pas_heap_config_kind_bmalloc:
heap = SystemHeap::tryGet();
if (!heap)
return false;
return heap->shouldSupplantBmalloc();
case pas_heap_config_kind_jit:
case pas_heap_config_kind_pas_utility:
return false;
default:
BCRASH();
return false;
}
}

void* pas_system_heap_malloc(size_t size)
{
return SystemHeap::getExisting()->malloc(size, FailureAction::ReturnNull);
}

void* pas_system_heap_memalign(size_t alignment, size_t size)
{
return SystemHeap::getExisting()->memalign(alignment, size, FailureAction::ReturnNull);
}

void* pas_system_heap_realloc(void* ptr, size_t size)
{
return SystemHeap::getExisting()->realloc(ptr, size, FailureAction::ReturnNull);
}

void pas_system_heap_free(void* ptr)
{
SystemHeap::getExisting()->free(ptr);
}

void* pas_system_heap_malloc_compact(size_t size)
{
return SystemHeap::getExisting()->malloc(size, FailureAction::ReturnNull);
}

void* pas_system_heap_memalign_compact(size_t alignment, size_t size)
{
return SystemHeap::getExisting()->memalign(alignment, size, FailureAction::ReturnNull);
}

void* pas_system_heap_realloc_compact(void* ptr, size_t size)
{
return SystemHeap::getExisting()->realloc(ptr, size, FailureAction::ReturnNull);
}

#else // !BUSE(LIBPAS)

bool pas_system_heap_is_enabled(pas_heap_config_kind kind)
{
BUNUSED_PARAM(kind);
return false;
}

bool pas_system_heap_should_supplant_bmalloc(pas_heap_config_kind kind)
{
BUNUSED_PARAM(kind);
return false;
}

void* pas_system_heap_malloc(size_t size)
{
BUNUSED_PARAM(size);
RELEASE_BASSERT_NOT_REACHED();
return nullptr;
}

void* pas_system_heap_memalign(size_t alignment, size_t size)
{
BUNUSED_PARAM(size);
BUNUSED_PARAM(alignment);
RELEASE_BASSERT_NOT_REACHED();
return nullptr;
}

void* pas_system_heap_realloc(void* ptr, size_t size)
{
BUNUSED_PARAM(ptr);
BUNUSED_PARAM(size);
RELEASE_BASSERT_NOT_REACHED();
return nullptr;
}

void* pas_system_heap_malloc_compact(size_t size)
{
BUNUSED_PARAM(size);
RELEASE_BASSERT_NOT_REACHED();
return nullptr;
}

void* pas_system_heap_memalign_compact(size_t alignment, size_t size)
{
BUNUSED_PARAM(size);
BUNUSED_PARAM(alignment);
RELEASE_BASSERT_NOT_REACHED();
return nullptr;
}

void* pas_system_heap_realloc_compact(void* ptr, size_t size)
{
BUNUSED_PARAM(ptr);
BUNUSED_PARAM(size);
RELEASE_BASSERT_NOT_REACHED();
return nullptr;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
void pas_system_heap_free(void* ptr)
{
BUNUSED_PARAM(ptr);
RELEASE_BASSERT_NOT_REACHED();
}
#pragma clang diagnostic pop

#endif // BUSE(LIBPAS)

#endif // BENABLE(LIBPAS)

#endif // BOS(WINDOWS)
1 change: 1 addition & 0 deletions src/c-headers-for-zig.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
#if WINDOWS
#include <windows.h>
#include <winternl.h>
#include <stdlib.h> // _putenv
#endif

#undef lstat
Expand Down
11 changes: 11 additions & 0 deletions src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ pub extern "c" var environ: ?*anyopaque;
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");
}
Comment on lines +24 to +33

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ 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.


if (Environment.isPosix) {
var act: std.posix.Sigaction = .{
.handler = .{ .handler = std.posix.SIG.IGN },
Expand Down
Loading