Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

wip: route windows allocations through mimalloc via --wrap

Martin Vogel1c71b9977464
diff --git a/Makefile.cbm b/Makefile.cbm
index d9330afec..ebda5034b 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -94,8 +94,20 @@ CXXFLAGS_TSAN = $(CXXFLAGS_COMMON) -g -O1 \
# Auto-detected via compiler; no manual override needed.
IS_MINGW := $(shell echo | $(CC) -dM -E - 2>/dev/null | grep -q 'define _WIN32 ' && echo yes || echo no)
WIN32_LIBS :=
+# Route Windows allocations through mimalloc (#581). mimalloc's own static
+# override is gated on _MSC_VER, which clang/MinGW never defines, so it
+# compiled out and the CRT won the link: ordinary malloc went to the CRT heap,
+# which keeps freed pages committed, leaving every allocator tuning in
+# cbm_mem_init POSIX-only. --wrap redirects the same population of allocations
+# that link-order override captures on POSIX, so the purge configuration
+# finally applies here too. src/foundation/mem_override_win.c supplies the
+# wrappers; its deallocating paths check mi_is_in_heap_region so a CRT-owned
+# pointer can never reach mi_free (#424).
+MIMALLOC_WRAP_SYMS := malloc calloc realloc free strdup strndup _msize \
+ _aligned_malloc _aligned_free
+MIMALLOC_WRAP_FLAGS := $(foreach sym,$(MIMALLOC_WRAP_SYMS),-Wl,--wrap=$(sym))
ifeq ($(IS_MINGW),yes)
-WIN32_LIBS := -lws2_32 -lpsapi -lshell32 -ladvapi32 -Wl,--allow-multiple-definition -Wl,--stack,8388608 -static
+WIN32_LIBS := -lws2_32 -lpsapi -lshell32 -ladvapi32 -Wl,--allow-multiple-definition -Wl,--stack,8388608 -static $(MIMALLOC_WRAP_FLAGS)
endif
# STATIC=1 produces a fully static binary (for Alpine/musl portable builds)
@@ -110,6 +122,7 @@ LDFLAGS_TSAN = -lm -lstdc++ -lpthread -lz $(TSAN_SANITIZE) $(WIN32_LIBS)
# ── Source files ─────────────────────────────────────────────────
FOUNDATION_SRCS = \
+ src/foundation/mem_override_win.c \
src/foundation/arena.c \
src/foundation/hash_table.c \
src/foundation/str_intern.c \
diff --git a/src/foundation/mem.c b/src/foundation/mem.c
index 537ffc85d..4de336913 100644
--- a/src/foundation/mem.c
+++ b/src/foundation/mem.c
@@ -212,6 +212,26 @@ void cbm_mem_init_with_cap(double ram_fraction, size_t hard_cap_bytes) {
* spawn-fail degrade, embedders). */
mi_option_set(mi_option_page_reclaim_on_free, 1);
+ /* Every option above is inert unless ordinary malloc actually reaches this
+ * allocator. That silently stopped being true on Windows — mimalloc's
+ * static override is gated on _MSC_VER, which clang/MinGW never defines —
+ * and nothing checked, so a long-lived daemon ratcheted committed memory
+ * for months (#581). Probe it once, out loud: a real malloc asked whether
+ * mimalloc owns it. Anything but true means the tuning here is decoration
+ * and freed pages will not come back. */
+ void *ownership_probe = malloc(CBM_SZ_64);
+ if (ownership_probe) {
+ bool owned = mi_is_in_heap_region(ownership_probe);
+ free(ownership_probe);
+ if (!owned) {
+ cbm_log_warn("mem.allocator.not_owned", "detail",
+ "malloc is not served by mimalloc: purge/reclaim options "
+ "have no effect and freed pages will stay committed");
+ } else {
+ cbm_log_info("mem.allocator.owned", "detail", "malloc is served by mimalloc");
+ }
+ }
+
/* CBM_MEM_BUDGET_MB env override (memory analogue of CBM_WORKERS).
* Lets users cap the budget directly without an enclosing cgroup —
* useful on bare-metal hosts where cgroup memory limits are absent
diff --git a/src/foundation/mem_override_win.c b/src/foundation/mem_override_win.c
new file mode 100644
index 000000000..6c7dfdf6c
--- /dev/null
+++ b/src/foundation/mem_override_win.c
@@ -0,0 +1,141 @@
+/*
+ * mem_override_win.c — Route Windows allocations through mimalloc.
+ *
+ * WHY THIS FILE EXISTS
+ *
+ * On POSIX the build links mimalloc's object first, so its strong malloc/free
+ * symbols win and every allocation in everything we compile — our code,
+ * SQLite, the tree-sitter grammars, yyjson — lands in mimalloc. cbm_mem_init
+ * then sets purge_delay=0 and purge_decommits=1, so a page that becomes empty
+ * is decommitted immediately and the OS takes it straight back. That is why a
+ * long-lived POSIX daemon stays flat.
+ *
+ * Windows got none of that. mimalloc's own static override is gated on
+ * `#elif defined(_MSC_VER)` (vendored/mimalloc/src/alloc-override.c), and this
+ * project builds with clang/MinGW, which never defines _MSC_VER. So the branch
+ * compiled out, the generic fallback's plain malloc/free definitions lost the
+ * link against the static CRT, and -DMI_MALLOC_OVERRIDE=1 was defined but
+ * inert. Ordinary malloc went to the CRT heap, which keeps freed pages
+ * committed — so every allocator tuning in cbm_mem_init was POSIX-only, and a
+ * long-lived daemon ratcheted committed memory until Windows fell over (#581).
+ *
+ * HOW THIS FIXES IT
+ *
+ * The linker's --wrap redirects every undefined reference to `malloc` in the
+ * objects we link to `__wrap_malloc`, and gives us `__real_malloc` for the
+ * original. That captures exactly the same population of allocations that
+ * link-order override captures on POSIX, so parity follows by construction
+ * rather than by trimming a heap afterwards.
+ *
+ * THE SAFETY PROPERTY THAT MATTERS
+ *
+ * --wrap only rewrites references in objects passed to this link. Code already
+ * compiled into ucrt/msvcrt and the system DLLs still calls the CRT's
+ * allocator, so the CRT can hand us a pointer mimalloc never made. Passing
+ * such a pointer to mi_free aborts with "mi_free: invalid pointer" — that is
+ * #424, which crashed `index` on every run. Every deallocating wrapper here
+ * therefore asks mi_is_in_heap_region() who owns the pointer and routes it to
+ * the matching allocator. Cross-allocator frees become impossible by
+ * construction instead of by convention.
+ *
+ * Allocating wrappers need no such check: serving a new allocation from
+ * mimalloc is always safe.
+ */
+#include "foundation/mem.h"
+
+#include <mimalloc.h>
+#include <stddef.h>
+#include <string.h>
+
+#ifdef _WIN32
+
+/* The originals, supplied by the linker because of --wrap. */
+void *__real_malloc(size_t size);
+void *__real_calloc(size_t count, size_t size);
+void *__real_realloc(void *block, size_t size);
+void __real_free(void *block);
+char *__real_strdup(const char *text);
+
+/* True when mimalloc made this block, so it must be returned to mimalloc.
+ * NULL is nobody's: callers handle it before asking. */
+static inline bool mem_override_is_ours(const void *block) {
+ return mi_is_in_heap_region(block);
+}
+
+void *__wrap_malloc(size_t size) {
+ return mi_malloc(size);
+}
+
+void *__wrap_calloc(size_t count, size_t size) {
+ return mi_calloc(count, size);
+}
+
+char *__wrap_strdup(const char *text) {
+ return mi_strdup(text);
+}
+
+char *__wrap_strndup(const char *text, size_t length) {
+ return mi_strndup(text, length);
+}
+
+void *__wrap__aligned_malloc(size_t size, size_t alignment) {
+ /* Windows spells aligned allocation _aligned_malloc(size, alignment) —
+ * note the argument order is the reverse of mi_malloc_aligned's. */
+ return mi_malloc_aligned(size, alignment);
+}
+
+void __wrap_free(void *block) {
+ if (!block) {
+ return;
+ }
+ if (mem_override_is_ours(block)) {
+ mi_free(block);
+ return;
+ }
+ /* Allocated inside the CRT or a system DLL, where --wrap could not reach.
+ * Returning it to mimalloc would abort (#424), so give it back to its
+ * real owner. */
+ __real_free(block);
+}
+
+void __wrap__aligned_free(void *block) {
+ if (!block) {
+ return;
+ }
+ if (mem_override_is_ours(block)) {
+ mi_free(block);
+ return;
+ }
+ __real_free(block);
+}
+
+void *__wrap_realloc(void *block, size_t size) {
+ if (!block) {
+ return mi_malloc(size);
+ }
+ if (mem_override_is_ours(block)) {
+ return mi_realloc(block, size);
+ }
+ /* A CRT block cannot be handed to mi_realloc, and the CRT's realloc must
+ * not be asked to grow into mimalloc's space either. Copy across the
+ * boundary once: allocate from mimalloc, move the smaller of the two
+ * sizes, release the original to the CRT. mi_usable_size is unavailable
+ * for a foreign block, so the CRT's own accounting bounds the copy. */
+ size_t old_size = _msize(block);
+ void *moved = mi_malloc(size);
+ if (!moved) {
+ return NULL; /* original stays valid, as realloc requires */
+ }
+ memcpy(moved, block, old_size < size ? old_size : size);
+ __real_free(block);
+ return moved;
+}
+
+size_t __wrap__msize(void *block) {
+ if (block && mem_override_is_ours(block)) {
+ return mi_usable_size(block);
+ }
+ return block ? _msize(block) : 0;
+}
+
+#endif /* _WIN32 */