Skip to content
StraylightRunMOOPublic

About

Memento the memory allocator

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

25 Commits

Folders and files

Repository files navigation

Memento

A single-header C11 allocator for people who have to debug memory problems, not just allocate fast. Drop-in malloc shim included.

cc -O2 -shared -fPIC -Iinclude shim/memento_malloc.c -o memento_malloc.so -lpthread
LD_PRELOAD=./memento_malloc.so ./your_program          # nothing to recompile
kill -USR1 <pid>                                        # live heap report on stderr

That shim is the whole pitch in miniature: point memento at a running process and it starts telling you things — per-thread heaps, live bytes, top allocation sites if you go through the proxy, what got cached, what got returned to the kernel. The allocator underneath is a thread-caching span allocator in the rpmalloc/mimalloc family, and it is fast (see the numbers, and the caveats, below). But the reason to reach for memento over the famous ones is that it doubles as a diagnostic instrument.

#define MEMENTO_IMPLEMENTATION
#include "memento.h"

int main(void) {
    memento_init();
    void* p = memento_malloc(1024);   // sized API: no size bookkeeping
    memento_free(p);                  // header knows everything
    memento_shutdown();
    return 0;
}

MIT licensed. C11, C++17 wrapper included, Linux/macOS/Windows, and Wasm/Emscripten (MEMENTO_PLATFORM_WASM: malloc-backed spans, no virtual reserve, no mprotect guard pages, no fork).


What's in the box

Piece What it is
include/memento.h The allocator. One header, #define MEMENTO_IMPLEMENTATION in one TU
include/memento.hpp C++17 wrapper: RAII context, STL allocator, construct/destroy
shim/memento_malloc.c LD_PRELOAD malloc interposition with SIGUSR1 heap dumps
Proxies Wrap any heap/pool/arena in a call-site-tracking, leak-reporting layer
Pools, arenas, stacks, slabs Fixed-size object pools (they grow), rewindable arenas, LIFO stacks, type-size slabs
bench/ Microbench + comparative suite vs. mimalloc/rpmalloc/glibc
tools/ LUT generator, reproducible coverage script

Two modes: sized and exact

There are two ways to talk to memento, and you should pick deliberately.

The sized API (memento_malloc, memento_free, memento_calloc, memento_realloc, …) stamps a 16-byte header on every allocation and never asks you for a size again. This is the default at the generic API surface, and it's what the shim uses. The header costs you 16 bytes per allocation and buys you memento_usable_size(), safe realloc, and frees that can't be wrong about the size.

The exact API (memento_thread_heap_alloc(heap, size) / memento_thread_heap_free(heap, ptr, size)) skips the header entirely and is the fastest thing memento has — but the contract is on you: the size you free with must be the size you allocated with. A wrong size mis-files the block in the wrong size class. Memento won't crash (release builds never abort on a bad free), but the heap will quietly drift. This is the same contract rpmalloc's sized-free API has; we just say it out loud.

When another thread holds the pointer and the allocating heap is not in hand, memento_thread_heap_free_owned(ptr, size) looks up the owner from the span (small blocks) or the large-block header (page-run / huge) and routes the free home. memento_thread_heap_of(ptr, size) returns that heap.

Which should you use? If you're wrapping memento in a data structure or a language runtime where sizes are statically known — exact. If you're doing general-purpose "replace malloc" work — sized. Pick a mode and stay in it: memento_free is sized-only. Exact pointers go through memento_thread_heap_free(heap, ptr, size) or memento_thread_heap_free_owned(ptr, size). Passing an exact pointer to memento_free is not mixed-mode cleverness — it is a no-op in release (the block leaks) and a debug failure.

malloc(0) returns a unique, freeable pointer in both modes, because real code depends on that and the standard allows it.

How it works (the five-minute version)

Small allocations (≤ 8 KiB) come out of 2 MiB spans — self-aligned mappings, so the owning span of any pointer is one AND away. Inside each span sit 32 × 64 KiB pages (MEMENTO_PAGE_SIZE). Each page is one size class; the page header (including the free list and nused) lives in the same 64 KiB as the blocks, so the hit path does not dirty a span header 2 MiB away. A fresh page bump-carves slots (no store into the payload); recycled blocks sit on the page freelist. In front of the active page is a per-class LIFO tcache (MEMENTO_TCACHE_DEPTH, default 32) so churn is an indexed load off a hot line. Tcache overflow lands in a per-class pointer stash (no store into the payload) until the next miss or flush. Spans stay single-class. There are 29 size classes: 16-byte granularity up to 256 B, then steps of at most ~28% up to 8 KiB.

A page's nused counts blocks in user hands. When every page in a span is empty, the span is parked for reuse. That's the reclamation design.

Foreign frees of small blocks CAS onto the page's thread_free stack (same exchange-all drain, now sharded). Large/page-run frees still use the heap-wide stack. Push is a CAS loop, drain is a single atomic_exchange, and the drained batch is bucketed by size class so the owner walks each class's freelist once. Blocks in foreign flight count as live until drained, so reclamation never sees a span as empty while a free is still in transit. No ABA problem: the push side never re-reads the head after a failed CAS expecting it to be stable, and the drain side is an exchange, which is immune by construction.

The madvise ping-pong, and how we don't do it. When a span empties, the naive move is MADV_DONTNEED on its pages — great for RSS, terrible when the very next allocation re-faults 512 pages at ~1 µs each. mimalloc learned this lesson years ago; we copied the homework. Empty spans are parked with a purge deadline (10 ms, MEMENTO_SPAN_PURGE_MS). A span recycled inside the window costs zero page faults. One that stays empty past the deadline gets its pages discarded on the next reclamation event. There's a backstop (MEMENTO_SPAN_CACHE_MAX, 16 spans = 32 MiB per heap) so a giant burst can't sit fully mapped forever. If you want deterministic, right-now release, memento_heap_release_caches() unmaps everything. memento_malloc_trim() (and the shim's malloc_trim) only discards parked empty spans and the process-wide span cache — live allocations stay mapped. Runtime tcache depth is memento_ctl(MEMENTO_CTL_SET_TCACHE_DEPTH, &n) or env MEMENTO_TCACHE_DEPTH.

Medium allocations (8 KiB – 256 KiB) are page runs: whole pages, per-page-count free lists, MADV_FREE on the cold cache entries so the kernel can reclaim them under pressure while the hot entries stay instantly reusable.

Large allocations (> 256 KiB) are their own mappings, with a small cache keyed by page count — because realloc(p, 1000000) → realloc(p, 1000001) must hit the same slot, and page count is the granularity the OS actually charges you in.

Threads get their own heaps — zero atomics, zero locks on the local hot path. When a thread is done, it can memento_heap_park() its heap instead of letting it die; the next thread to call memento_heap_adopt() inherits it, warm caches and all. On NUMA machines adopt prefers a heap that was born on your node. Thread exit parks automatically via the TLS destructor.

fork(): the child gets a fresh heap, not a copy-on-write snapshot of the parent's. The atfork handler retires every heap (including the forking thread's), clears the parked list, reinitializes the global lock, and bumps a generation counter (memento_fork_generation_current()) so embedders can detect the epoch change. Blocks allocated before the fork and freed after it route to a retired heap and die with it — correct, if not free. Register with memento_atfork_register() (the shim does this for you).

The debugging toolkit

This is the part the famous allocators mostly leave to valgrind.

Proxies. Wrap any heap, pool, or arena in a proxy and every allocation through it gets logged with the call site:

memento_proxy_t* px = memento_proxy_wrap_heap(heap,
    MEMENTO_PROXY_SITE | MEMENTO_PROXY_WATERMARK);
Order* o = memento_proxy_alloc(px, sizeof(Order));   // file:line captured
/* ... later ... */
memento_proxy_report(px, stderr);
//   top sites (outstanding):
//     src/orders.c:84 — 3 blocks, 144 bytes

Release builds keep the site table and leak accounting (it's cheap); debug builds add per-block cookies and owner-thread checks. Untracked frees print a warning and are skipped — diagnostics should never take your process down. There is no abort() on a bad free anywhere in memento; debug builds fail loudly at the point of the bug, release builds refuse quietly and keep going. Your call which one you ship.

Heap reports. memento_thread_heap_report(heap, stderr) prints alloc/free totals, live and peak bytes, span counts (and how many were reclaimed), cache occupancy, and the top size classes by live bytes. memento_report_all(stderr) does every heap. From the shim, kill -USR1 dumps this from a live process; MEMENTO_DUMP_ATEXIT=1 dumps at exit.

Stats. Counters live behind MEMENTO_STATS (default on). They cost a few ns per alloc/free pair on the hot loop (see the benchmark table: churn 64 B, 21.7 → 15.2 ns on the capture box), so production builds that want the last drop of speed can -DMEMENTO_STATS=0 and lose nothing else.

Sanitizers. ASan and UBSan runs are clean across the test suite, and memento poisons freelist blocks properly so use-after-free under ASan points at your bug, not our freelist. Valgrind memcheck annotations (MALLOCLIKE/FREELIKE) are in. Debug builds (MEMENTO_DEBUG=1) add fill patterns, double-free detection in pools/stacks/slabs, and owner-thread enforcement on the single-threaded container types.

The small print (a.k.a. honest limitations)

  • Pools, arenas, stacks, and slabs are owner-thread-only. No internal locking. Debug builds enforce it; release builds trust it. Share them across threads and you get exactly the corruption you deserve.
  • Pools grow. memento_pool_alloc doubles the backing chunk when exhausted rather than returning NULL. If you wanted a hard cap, that's not what "pool" means here — check count yourself if you care.
  • Exact mode requires exact sizes. Already said it. Saying it again.
  • Thread exit parks the heap; it does not return its memory. Blocks still live at thread exit stay accounted to that heap until someone adopts it or the process ends. Long-lived processes that spawn thousands of threads should call memento_heap_release_caches() before parking.
  • We don't defragment. Spans are single-class and blocks don't move. If your workload pins one byte in every span, RSS stays high. That's the price of not moving memory behind your back.
  • Windows gets less love. It works (VirtualAlloc spans, FLS destructors, InitOnceExecuteOnce init), but the aligned-reservation dance on Windows has a genuine race window we retry around (32 attempts) rather than eliminate — MEM_RELEASE can't split a reservation, and we chose the race over permanently pinned address space. The README table below was measured on Linux.
  • The first-touch cost is real. Fresh spans fault pages in lazily on purpose (no MADV_WILLNEED, no prefaulting — prefaulting 2 MiB to hand out 2 KB is how benchmarks lie). A workload touching tens of fresh megabytes pays ~1 µs per 4 KiB page, once. After that the pages are warm. calloc knows which parts of a span are guaranteed kernel-zero and skips its memset there.

Benchmarks, with the caveats baked in

Head-to-head, one harness (bench/compare.c), one machine, min of three runs, ns per alloc+free pair (lower is better). Captured on a 6-core Cortex-A78AE at 1.73 GHz (aarch64, Clang 22, -O3 -march=native) — treat the absolutes as machine-specific and the ordering as the finding. Full write-up, the raw CSV, and how to pull in mimalloc-bench: BENCHMARKS.md.

compare.c ns/op

workload memento 3.0 3.0 STATS=0 mimalloc 2.1.7 rpmalloc 1.4.5 glibc
churn 64 B 21.3 14.8 19.8 9.0 21.6
churn 1 KiB 21.2 14.7 25.3 12.1 21.9
bulk 64 B 49.5 41.7 28.9 45.0 81.9
bulk 4 KiB 690 683 584 1045 1958
mixed 16–256 B 100 93.4 28.3 33.8 91.1
churn 16 KiB 27.3 22.0 39.0 18.4 74.2
4-thread churn 64 B 6.0 3.6 5.6 2.5 5.9

How to read this without lying to yourself:

  • Against the field: rpmalloc still owns the hit path (churn, 16 KiB, threads). STATS=0 memento beats mimalloc and glibc on those three. bulk-64 B now beats rpmalloc and glibc and sits behind mimalloc's unbounded page freelist (41.7 vs 28.9). Mixed sizes is the remaining gap — about 3× the leading pair on this box (93 vs 28), down from 4–5×. That row is a cold burst across 11 classes: lazy page reset plus bump-carve, not the tcache. If nanoseconds are all you want, take rpmalloc. What it won't give you is the rest of this README: heap reports, allocation-site attribution, guard-page arenas, proxy layers, and a shim that catches your leaks in a running process.
  • Against 2.2.1 (earlier x86 capture): mixed sizes went 200 → 41 on that machine (the madvise ping-pong — empty spans now keep their pages for MEMENTO_SPAN_PURGE_MS before the MADV_DONTNEED). Four threads went 13.6 → 5.8. 16 KiB churn is the page-run cache doing its job.
  • The churn cost of reclamation is the occupancy accounting that lets v3 notice a span is empty and hand its pages back at all. 2.2.1 was faster here partly because it never returned memory to the OS. You can have that row or you can have RSS that comes back; we chose RSS. -DMEMENTO_STATS=0 is the other lever (21.3 → 14.8 ns here).
  • bulk-4 KiB is mostly first-touch. Once spans sit on 2 MiB-aligned VA (so THP can actually collapse), memento lands next to mimalloc (690 vs 584 ns) and ahead of rpmalloc and glibc. Before that fix this row was a 4K-fault costume at ~1.9 µs.

Run it yourself:

./bench/run_compare.sh                 # 3 runs, min, CSV + PNG
./bench/run_mimalloc_bench.sh          # optional: daanx/mimalloc-bench subset
python3 bench/plot.py                  # regenerate graphs from captured CSV

cc -O2 -Iinclude bench/microbench.c -o microbench -lpthread covers the memento-only patterns. cmake --build build-bench --target run_compare is the one-shot CMake path.

Configuration knobs

All are -D defines; the defaults are the product of the benchmarks above, not vibes.

Knob Default What it does
MEMENTO_SIZED 0 1 = every thread_heap_* alloc carries a size header
MEMENTO_STATS 1 0 = drop all counters (saves ~2 ns/op)
MEMENTO_DEBUG 0 Fill patterns, canaries, owner-thread checks, double-free detection
MEMENTO_SPAN_SIZE 2 MiB Span size; must be a power of two
MEMENTO_PAGE_SIZE 64 KiB Pages inside each span; must divide span size
MEMENTO_TCACHE_DEPTH 32 Per-class LIFO tcache slots (RSS vs churn)
MEMENTO_STASH_MAX 262144 Per-class overflow stash (0 = free straight to the page)
MEMENTO_SIMD_AVX2 / AVX512 / NEON auto Packed tcache fill + optional bmp_first; compile-time only
MEMENTO_SIGNAL 1 Shim: 0 = do not install SIGUSR1
MEMENTO_VA_RESERVE 256 MiB Process-wide reserved VA for span bump (no overmap)
MEMENTO_GLOBAL_PAGE_CACHE 64 Process-wide empty-span cache
MEMENTO_CPU_HEAPS 1 Park/adopt prefers this CPU's heap
MEMENTO_TCACHE_DEPTH_MAX 64 Compile-time cap; live depth is memento_ctl / env
MEMENTO_SPAN_PURGE_MS 10 How long an empty span keeps its pages
MEMENTO_SPAN_CACHE_MAX 16 Backstop: parked spans past this discard eagerly
MEMENTO_PAGE_RUN_HOT 2 Cached page runs per size kept fully backed
MEMENTO_REFILL_BATCH 32 Blocks carved per freelist refill
MEMENTO_FLUSH_BATCH 64 Foreign frees drained per batch
MEMENTO_ENABLE_THP 1 MADV_HUGEPAGE on fresh ≥2 MiB mappings
MEMENTO_LARGE_CACHE_SLOTS 8 Huge-mapping cache size

C++

#define MEMENTO_IMPLEMENTATION
#include "memento.hpp"

memento::context ctx;                    // RAII init/shutdown
memento::heap h;                         // this thread's heap
std::vector<Foo, memento::allocator<Foo>> v{ memento::allocator<Foo>{h} };
auto* obj = h.construct<Foo>(args);
h.destroy(obj);

C++20 concepts constrain the allocator when available; C++17 works fine without. The wrapper needs the v3 header (#errors otherwise).

Testing

Twelve ctest suites: core API, threads, sized mode, exact mode, proxies (debug and release builds — they differ), lifecycle (fork, thread churn), debug enforcement, MEMENTO_STATS=0, C++ wrapper, the shim, and the USR1 dump path. ASan+UBSan clean. Union line coverage is 83% on memento.h and 89% across the library, reproducible with tools/coverage.py. The number we're proudest of is that the proxy tests run against the release build — the bug class where release-only corruption ate two days of our lives is now pinned by a test.

Roadmap

Things we'd take patches for, in rough order of our own interest:

  • Per-CPU heaps and a proper cross-thread ownership-transfer API
  • Expose the per-class freelist cap (64 blocks) as a knob — it's the dial between bulk-recycle speed and RSS coming back (see the benchmark table)
  • A MADV_COLLAPSE pass for long-lived heaps on Linux 6.1+. Flush tries each span once; EINVAL/ENOSYS disables it for the process (5.15 does not have the flag).
  • Guard-page arenas everywhere, not just where they're cheap
  • A Windows citizen who cares (the aligned-reservation race deserves better)
  • eBPF hook points in the shim, because why should the kernel have all the fun

License

MIT. Do what you like; tell us if it eats your process, and send the backtrace.

About

Memento the memory allocator

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages