Ray's Knowledge Base
Unlock

An unfiltered logging wrapper on munmap, madvise or mprotect crashes programs whose allocator calls them, such as jemalloc with aggressive purging

PitfallVerified 7 Oct 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

A tracer that wraps munmap, madvise, mprotect and similar calls with a wrapper that logs every call runs fine with glibc malloc and with jemalloc's default settings (8 to 13 madvise events). With MALLOC_CONF=dirty_decay_ms:0,muzzy_decay_ms:0 it crashes every time, rc=139 (segfault) or rc=134 (abort), after about 34,500 events. The unmodified build, with no wrapper for these calls, completes normally under the same setting.

Cause#

jemalloc calls madvise from its own library through the symbol table, so the wrapper runs inside the allocator's purge, for example from __nptl_deallocate_tsd at thread exit. The wrapper allocates (the event's metadata) and takes the logger's lock inside that call, while the allocator is in the middle of its own operation. A gdb backtrace showed madvise_wrapper called from libjemalloc, then the serializer crashing in std::string::_M_mutate. A re-entry guard around the buffer lock, and then around the whole wrapper, did not help, and an initial-exec TLS flag did not either. glibc's own allocator reaches these calls through internal aliases that no wrapper sees, so the failure only appears with another allocator.

Fix#

Do not allocate or take a lock inside a wrapper that an allocator can call. Either skip the call before anything allocates, for example by looking the address up in a table of file-backed mappings so allocator calls on anonymous memory are filtered, or write a fixed-size record into a preallocated lock-free ring and drain it from a normal traced call. The ring was designed but not built here. For a gdb run, set LD_PRELOAD with set environment inside gdb, because exporting it makes gdb load the preload library too and gdb itself crashes with Fatal signal: Segmentation fault.

Evidence#

8 threads that allocate and free 2 MB and 40 KB blocks under dftracer, arm64 container: glibc malloc rc=0, jemalloc default rc=0 with 8 madvise events, jemalloc purge-on-every-free rc=139 or rc=134. The control with the original build gave rc=0. The user chose to keep the wrappers unfiltered, so the risk was documented and left in.

Also found by searching

  • LD_PRELOAD tracer segfault when jemalloc purges memory with madvise
  • wrapper for madvise that allocates crashes in jemalloc thread exit tsd cleanup
  • logging inside munmap wrapper deadlocks or recurses
  • MALLOC_CONF dirty_decay_ms:0 crashes my preload library