From 524cafb0e3c95665e2c1c6fe82afc696e2e84b80 Mon Sep 17 00:00:00 2001 From: Jaya Kasa Date: Fri, 4 Dec 2026 07:11:10 -0500 Subject: [PATCH 1/2] feat(secondary): add SecondaryAllocatorChain, lookup, and ownership checks Allow two secondary allocators (such as GWP-ASan and a future profiling store) to compose cleanly, and keep main-heap pointers off secondary ownership checks: - Add SecondaryAllocatorChain (mem/secondary/chain.h) and optional-member helpers (mem/secondary/optional.h) for has_pending, cancel_pending, lookup, and debug_is_empty - Add owns() to DefaultSecondaryAllocator and GwpAsanSecondaryAllocator - Add secondary_owns() and secondary_object() in globalalloc.h, gated by a pagemap ownership check so main-heap pointers never query the secondary - Check sizeclass before secondary_owns() in libc::realloc and rust_realloc, and include secondary emptiness in debug_check_empty() - Make Pool::iterate() lock the head read (ds/pool.h) and const-qualify GNU Atomic::load() (stl/gnu/atomic.h) - Add unit tests: secondary_chain and secondary_owns --- src/snmalloc/ds/pool.h | 15 +- src/snmalloc/global/globalalloc.h | 68 ++++++++- src/snmalloc/global/libc.h | 2 +- src/snmalloc/mem/secondary/chain.h | 73 +++++++++ src/snmalloc/mem/secondary/default.h | 6 + src/snmalloc/mem/secondary/gwp_asan.h | 6 + src/snmalloc/mem/secondary/optional.h | 59 ++++++++ src/snmalloc/override/rust.cc | 3 +- src/snmalloc/stl/gnu/atomic.h | 10 +- .../func/secondary_chain/secondary_chain.cc | 138 ++++++++++++++++++ .../func/secondary_owns/secondary_owns.cc | 69 +++++++++ 11 files changed, 439 insertions(+), 10 deletions(-) create mode 100644 src/snmalloc/mem/secondary/chain.h create mode 100644 src/snmalloc/mem/secondary/optional.h create mode 100644 src/test/func/secondary_chain/secondary_chain.cc create mode 100644 src/test/func/secondary_owns/secondary_owns.cc diff --git a/src/snmalloc/ds/pool.h b/src/snmalloc/ds/pool.h index 2a94ec440..447be94f7 100644 --- a/src/snmalloc/ds/pool.h +++ b/src/snmalloc/ds/pool.h @@ -9,9 +9,8 @@ namespace snmalloc * Pool of a particular type of object. * * This pool will never return objects to the OS. It maintains a list of all - * objects ever allocated that can be iterated (not concurrency safe). Pooled - * types can be acquired from the pool, and released back to the pool. This is - * concurrency safe. + * objects ever allocated that can be iterated. Pooled types can be acquired + * from the pool, and released back to the pool. This is concurrency safe. * * This is used to bootstrap the allocation of allocators. */ @@ -210,7 +209,15 @@ namespace snmalloc static T* iterate(T* p = nullptr) { if (p == nullptr) - return get_state().list.unsafe_ptr(); + { + // Read the head under the lock that `acquire` publishes it with. A + // node's `list_next` never changes after that, so the rest of the + // walk needs no lock. + PoolState& pool = get_state(); + T* result; + with(pool.lock, [&]() { result = pool.list.unsafe_ptr(); }); + return result; + } return p->list_next.unsafe_ptr(); } diff --git a/src/snmalloc/global/globalalloc.h b/src/snmalloc/global/globalalloc.h index ca9aaf509..8c3f60544 100644 --- a/src/snmalloc/global/globalalloc.h +++ b/src/snmalloc/global/globalalloc.h @@ -1,6 +1,7 @@ #pragma once #include "../mem/mem.h" +#include "../mem/secondary/optional.h" #include "threadalloc.h" namespace snmalloc @@ -32,6 +33,34 @@ namespace snmalloc AllocPool::restore(first, last); } + namespace detail + { + /** + * If a secondary allocator that tracks object bounds owns `p`, set + * `start` and `size` to its object. Main-heap pointers return false + * after one pagemap read. + */ + template + SNMALLOC_FAST_PATH_INLINE bool secondary_object( + address_t p, + const typename Config_::PagemapEntry& entry, + address_t& start, + size_t& size) + { + if constexpr (Config_::SecondaryAllocator::pass_through) + { + UNUSED(p, entry, start, size); + return false; + } + else + { + return !entry.is_owned() && + secondary::lookup( + p, start, size, 0); + } + } + } // namespace detail + /** If you pass a pointer to a bool, then it returns whether all the allocators are empty. If you don't pass a pointer to a bool, then will @@ -84,12 +113,19 @@ namespace snmalloc } } + const bool secondary_okay = + secondary::debug_is_empty(0); + okay = okay && secondary_okay; + if (result != nullptr) { *result = okay; return; } + if (!secondary_okay) + error("debug_check_empty: secondary allocator still has live objects"); + // Redo check so abort is on allocator with allocation left. if (!okay) { @@ -138,6 +174,10 @@ namespace snmalloc size_t SNMALLOC_FAST_PATH_INLINE remaining_bytes(address_t p) { const auto& entry = Config_::Backend::template get_metaentry(p); + address_t start; + size_t size; + if (detail::secondary_object(p, entry, start, size)) + return start + size - p; auto sizeclass = entry.get_sizeclass(); return snmalloc::remaining_bytes(sizeclass, p); @@ -159,6 +199,10 @@ namespace snmalloc static inline size_t index_in_object(address_t p) { const auto& entry = Config_::Backend::template get_metaentry(p); + address_t start; + size_t size; + if (detail::secondary_object(p, entry, start, size)) + return p - start; auto sizeclass = entry.get_sizeclass(); return snmalloc::index_in_object(sizeclass, p); @@ -302,15 +346,35 @@ namespace snmalloc UNUSED(p, size); } + template + SNMALLOC_FAST_PATH_INLINE bool secondary_owns(const void* p) + { + if constexpr (Config_::SecondaryAllocator::pass_through) + { + UNUSED(p); + return false; + } + else + { + // Main-heap pointers never belong to the secondary allocator. + if ( + p == nullptr || + Config_::Backend::template get_metaentry(address_cast(p)) + .is_owned()) + return false; + return Config_::SecondaryAllocator::owns(p); + } + } + template SNMALLOC_FAST_PATH_INLINE size_t alloc_size(const void* p_raw) { const auto& entry = Config_::Backend::get_metaentry(address_cast(p_raw)); if (SNMALLOC_UNLIKELY( - !Config::SecondaryAllocator::pass_through && !entry.is_owned() && + !Config_::SecondaryAllocator::pass_through && !entry.is_owned() && p_raw != nullptr)) - return Config::SecondaryAllocator::alloc_size(p_raw); + return Config_::SecondaryAllocator::alloc_size(p_raw); // TODO What's the domestication policy here? At the moment we just // probe the pagemap with the raw address, without checks. There could // be implicit domestication through the `Config::Pagemap` or diff --git a/src/snmalloc/global/libc.h b/src/snmalloc/global/libc.h index caa61f010..6e4335cb3 100644 --- a/src/snmalloc/global/libc.h +++ b/src/snmalloc/global/libc.h @@ -106,7 +106,7 @@ namespace snmalloc::libc size_t sz = alloc_size(ptr); // Keep the current allocation if the given size is in the same sizeclass. - if (sz == round_size(size)) + if (sz == round_size(size) && !secondary_owns(ptr)) { return ptr; } diff --git a/src/snmalloc/mem/secondary/chain.h b/src/snmalloc/mem/secondary/chain.h new file mode 100644 index 000000000..96eb3bb3d --- /dev/null +++ b/src/snmalloc/mem/secondary/chain.h @@ -0,0 +1,73 @@ +#pragma once + +#include "snmalloc/ds_core/defines.h" +#include "snmalloc/mem/secondary/optional.h" + +#include + +namespace snmalloc +{ + template + class SecondaryAllocatorChain + { + public: + static constexpr inline bool pass_through = false; + + static void initialize() noexcept + { + First::initialize(); + Second::initialize(); + } + + template + SNMALLOC_FAST_PATH static void* allocate(SizeAlign&& getter) + { + // A member holding work for this allocation goes first, so the other + // cannot take the allocation and drop that work. + if (SNMALLOC_UNLIKELY(secondary::has_pending(0))) + { + if (void* p = Second::allocate(getter)) + return p; + return First::allocate(getter); + } + if (void* p = First::allocate(getter)) + { + secondary::cancel_pending(0); + return p; + } + return Second::allocate(getter); + } + + SNMALLOC_FAST_PATH static bool owns(const void* pointer) + { + return First::owns(pointer) || Second::owns(pointer); + } + + SNMALLOC_FAST_PATH static void deallocate(void* pointer) + { + if (First::owns(pointer)) + First::deallocate(pointer); + else + Second::deallocate(pointer); + } + + SNMALLOC_FAST_PATH static size_t alloc_size(const void* pointer) + { + if (First::owns(pointer)) + return First::alloc_size(pointer); + return Second::alloc_size(pointer); + } + + static bool lookup(address_t a, address_t& start, size_t& size) + { + return secondary::lookup(a, start, size, 0) || + secondary::lookup(a, start, size, 0); + } + + static bool debug_is_empty() + { + return secondary::debug_is_empty(0) && + secondary::debug_is_empty(0); + } + }; +} // namespace snmalloc diff --git a/src/snmalloc/mem/secondary/default.h b/src/snmalloc/mem/secondary/default.h index 1fc86af46..d04a720b6 100644 --- a/src/snmalloc/mem/secondary/default.h +++ b/src/snmalloc/mem/secondary/default.h @@ -43,5 +43,11 @@ namespace snmalloc "secondary alloc_size should never be invoked with default setup"); return 0; } + + SNMALLOC_FAST_PATH + static bool owns(const void*) + { + return false; + } }; } // namespace snmalloc diff --git a/src/snmalloc/mem/secondary/gwp_asan.h b/src/snmalloc/mem/secondary/gwp_asan.h index 716c57935..eeae34426 100644 --- a/src/snmalloc/mem/secondary/gwp_asan.h +++ b/src/snmalloc/mem/secondary/gwp_asan.h @@ -67,5 +67,11 @@ namespace snmalloc { return singleton.getSize(pointer); } + + SNMALLOC_FAST_PATH + static bool owns(const void* pointer) + { + return singleton.pointerIsMine(pointer); + } }; } // namespace snmalloc diff --git a/src/snmalloc/mem/secondary/optional.h b/src/snmalloc/mem/secondary/optional.h new file mode 100644 index 000000000..a684cce84 --- /dev/null +++ b/src/snmalloc/mem/secondary/optional.h @@ -0,0 +1,59 @@ +#pragma once + +#include "../../aal/aal.h" + +#include + +namespace snmalloc::secondary +{ + // Optional secondary-allocator members. Each helper calls the member when + // `SA` has it and otherwise returns the default. + + template + auto cancel_pending(int) noexcept -> decltype(SA::cancel_pending(), void()) + { + SA::cancel_pending(); + } + + template + void cancel_pending(long) noexcept + {} + + template + auto has_pending(int) noexcept -> decltype(SA::has_pending()) + { + return SA::has_pending(); + } + + template + bool has_pending(long) noexcept + { + return false; + } + + /// Bounds of the object containing `a`, for allocators that track them. + template + auto lookup(address_t a, address_t& start, size_t& size, int) + -> decltype(SA::lookup(a, start, size)) + { + return SA::lookup(a, start, size); + } + + template + bool lookup(address_t, address_t&, size_t&, long) + { + return false; + } + + template + auto debug_is_empty(int) -> decltype(SA::debug_is_empty()) + { + return SA::debug_is_empty(); + } + + template + bool debug_is_empty(long) + { + return true; + } +} // namespace snmalloc::secondary diff --git a/src/snmalloc/override/rust.cc b/src/snmalloc/override/rust.cc index f07e51073..49d8e69d9 100644 --- a/src/snmalloc/override/rust.cc +++ b/src/snmalloc/override/rust.cc @@ -40,7 +40,8 @@ extern "C" SNMALLOC_EXPORT void* SNMALLOC_NAME_MANGLE(rust_realloc)( aligned_new_size = aligned_size(alignment, new_size); if ( size_to_sizeclass_full(aligned_old_size).raw() == - size_to_sizeclass_full(aligned_new_size).raw()) + size_to_sizeclass_full(aligned_new_size).raw() && + !secondary_owns(ptr)) return ptr; void* p = alloc(aligned_new_size); if (p) diff --git a/src/snmalloc/stl/gnu/atomic.h b/src/snmalloc/stl/gnu/atomic.h index 7a193972e..f0b8432e2 100644 --- a/src/snmalloc/stl/gnu/atomic.h +++ b/src/snmalloc/stl/gnu/atomic.h @@ -63,6 +63,11 @@ namespace snmalloc return __builtin_addressof(ref); } + SNMALLOC_FAST_PATH static const T* addressof(const T& ref) + { + return __builtin_addressof(ref); + } + // From libc++: // require types that are 1, 2, 4, 8, or 16 bytes in length to be aligned // to at least their size to be potentially @@ -84,12 +89,13 @@ namespace snmalloc SNMALLOC_FAST_PATH Atomic& operator=(const Atomic&) = delete; // Atomic load. - SNMALLOC_FAST_PATH operator T() + SNMALLOC_FAST_PATH operator T() const { return load(); } - SNMALLOC_FAST_PATH T load(MemoryOrder mem_ord = MemoryOrder::SEQ_CST) + SNMALLOC_FAST_PATH T + load(MemoryOrder mem_ord = MemoryOrder::SEQ_CST) const { T res; __atomic_load(addressof(val), addressof(res), order(mem_ord)); diff --git a/src/test/func/secondary_chain/secondary_chain.cc b/src/test/func/secondary_chain/secondary_chain.cc new file mode 100644 index 000000000..ed0e25dd4 --- /dev/null +++ b/src/test/func/secondary_chain/secondary_chain.cc @@ -0,0 +1,138 @@ +#include +#include +#include + +namespace +{ + struct FirstSuccess + { + static void initialize() noexcept {} + + template + static void* allocate(Getter&&) + { + return reinterpret_cast(0x1000); + } + + static bool owns(const void* p) + { + return p == reinterpret_cast(0x1000); + } + + static void deallocate(void*) {} + + static size_t alloc_size(const void*) + { + return 16; + } + }; + + struct CancelSecond + { + static inline size_t cancellations = 0; + + static void initialize() noexcept {} + + static void cancel_pending() noexcept + { + cancellations++; + } + + template + static void* allocate(Getter&&) + { + return nullptr; + } + + static bool owns(const void*) + { + return false; + } + + static void deallocate(void*) {} + + static size_t alloc_size(const void*) + { + return 0; + } + }; + + struct NoCancelSecond : CancelSecond + { + static void cancel_pending() = delete; + }; + + struct CountingFirst : FirstSuccess + { + static inline size_t calls = 0; + + template + static void* allocate(Getter&&) + { + calls++; + return reinterpret_cast(0x1000); + } + }; + + struct PendingSecond : CancelSecond + { + static inline bool pending = false; + + static bool has_pending() noexcept + { + return pending; + } + + template + static void* allocate(Getter&&) + { + if (!pending) + return nullptr; + pending = false; + return reinterpret_cast(0x2000); + } + }; +} + +int main() +{ + using CancelChain = + snmalloc::SecondaryAllocatorChain; + void* p = CancelChain::allocate([] { return 0; }); + if (p != reinterpret_cast(0x1000) || CancelSecond::cancellations != 1) + { + std::cerr << "first-success did not cancel second pending state\n"; + return 1; + } + + using PlainChain = + snmalloc::SecondaryAllocatorChain; + if (PlainChain::allocate([] { return 0; }) != reinterpret_cast(0x1000)) + { + std::cerr << "chain without cancellation hook failed\n"; + return 1; + } + + // Work pending in the second member is served there, not dropped. + using PendingChain = + snmalloc::SecondaryAllocatorChain; + PendingSecond::pending = true; + const size_t cancels = CancelSecond::cancellations; + if ( + PendingChain::allocate([] { return 0; }) != + reinterpret_cast(0x2000) || + CountingFirst::calls != 0 || CancelSecond::cancellations != cancels) + { + std::cerr << "pending second member was not served first\n"; + return 1; + } + if ( + PendingChain::allocate([] { return 0; }) != + reinterpret_cast(0x1000) || + CountingFirst::calls != 1) + { + std::cerr << "chain without pending work skipped the first member\n"; + return 1; + } + return 0; +} diff --git a/src/test/func/secondary_owns/secondary_owns.cc b/src/test/func/secondary_owns/secondary_owns.cc new file mode 100644 index 000000000..1cb63384d --- /dev/null +++ b/src/test/func/secondary_owns/secondary_owns.cc @@ -0,0 +1,69 @@ +// Main-heap pointers must not reach a secondary allocator's ownership check: +// for a profiling secondary that check can take a global lock. + +#include "test/setup.h" + +#include +#include +#include +#include + +namespace +{ + struct CountingSecondary + { + static constexpr inline bool pass_through = false; + static inline size_t owns_calls = 0; + + static void initialize() noexcept {} + + template + static void* allocate(Getter&&) + { + return nullptr; + } + + static bool owns(const void*) + { + owns_calls++; + return false; + } + + static void deallocate(void*) {} + + static size_t alloc_size(const void*) + { + return 0; + } + }; +} + +namespace snmalloc +{ + using Config = + StandardConfigClientMeta; +} + +#define SNMALLOC_PROVIDE_OWN_CONFIG +#include + +int main() +{ + void* p = snmalloc::libc::malloc(40); + for (size_t i = 0; i < 1000; i++) + p = snmalloc::libc::realloc(p, 40 + (i & 7)); + if (CountingSecondary::owns_calls != 0) + { + std::cerr << "main-heap realloc asked the secondary allocator " + << CountingSecondary::owns_calls << " times\n"; + return 1; + } + int local = 0; + if (snmalloc::secondary_owns(&local) || CountingSecondary::owns_calls != 1) + { + std::cerr << "foreign pointer did not reach the secondary allocator\n"; + return 1; + } + snmalloc::libc::free(p); + return 0; +} From 72784703ac5ebcda9802edb528c30e0a8ab3d934 Mon Sep 17 00:00:00 2001 From: Jaya Kasa Date: Fri, 4 Dec 2026 09:11:05 -0500 Subject: [PATCH 2/2] fix(secondary): guard backend-owned entries before is_owned() MetaEntryBase::is_owned() calls get_remote(), which asserts !is_backend_owned() in Debug builds. Check is_backend_owned() first in detail::secondary_object() and secondary_owns() so external_pointer(), remaining_bytes(), and secondary_owns() handle freed main-heap chunks without aborting under non-passthrough secondary allocators (e.g. GWP-ASan). Extend func-secondary_owns to assert that backend-owned chunks neither abort nor reach SecondaryAllocator::owns(). --- src/snmalloc/global/globalalloc.h | 17 +++++--- .../func/secondary_owns/secondary_owns.cc | 39 +++++++++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/src/snmalloc/global/globalalloc.h b/src/snmalloc/global/globalalloc.h index 8c3f60544..77d9dfab2 100644 --- a/src/snmalloc/global/globalalloc.h +++ b/src/snmalloc/global/globalalloc.h @@ -54,7 +54,9 @@ namespace snmalloc } else { - return !entry.is_owned() && + // Backend-owned chunks belong to snmalloc's backend, never to a + // secondary allocator, and `is_owned()` asserts `!is_backend_owned()`. + return !entry.is_backend_owned() && !entry.is_owned() && secondary::lookup( p, start, size, 0); } @@ -356,11 +358,14 @@ namespace snmalloc } else { - // Main-heap pointers never belong to the secondary allocator. - if ( - p == nullptr || - Config_::Backend::template get_metaentry(address_cast(p)) - .is_owned()) + if (p == nullptr) + return false; + // Main-heap (frontend or backend) pointers never belong to the secondary + // allocator. Check `is_backend_owned()` first because `is_owned()` + // asserts `!is_backend_owned()`. + const auto& entry = + Config_::Backend::template get_metaentry(address_cast(p)); + if (entry.is_backend_owned() || entry.is_owned()) return false; return Config_::SecondaryAllocator::owns(p); } diff --git a/src/test/func/secondary_owns/secondary_owns.cc b/src/test/func/secondary_owns/secondary_owns.cc index 1cb63384d..7a56a15ef 100644 --- a/src/test/func/secondary_owns/secondary_owns.cc +++ b/src/test/func/secondary_owns/secondary_owns.cc @@ -65,5 +65,44 @@ int main() return 1; } snmalloc::libc::free(p); + + // Freed main-heap chunks returned to the backend must neither trip the + // `!is_backend_owned()` assertion in `is_owned()` nor query the secondary + // allocator during external-pointer / remaining-bytes / ownership queries. + constexpr size_t count = snmalloc::MIN_CHUNK_SIZE; + void* allocs[count]; + for (size_t i = 0; i < count; i++) + allocs[i] = snmalloc::alloc(snmalloc::MIN_CHUNK_BITS / 2); + for (size_t i = 1; i < count; i++) + snmalloc::dealloc(allocs[i]); + + bool saw_backend_owned = false; + const size_t calls_before = CountingSecondary::owns_calls; + for (size_t i = 0; i < count; i++) + { + if (snmalloc::Config::Backend::template get_metaentry( + snmalloc::address_cast(allocs[i])) + .is_backend_owned()) + saw_backend_owned = true; + (void)snmalloc::external_pointer(allocs[i]); + (void)snmalloc::remaining_bytes(allocs[i]); + if (snmalloc::secondary_owns(allocs[i])) + { + std::cerr << "freed main-heap pointer reported as secondary-owned\n"; + return 1; + } + } + if (!saw_backend_owned) + { + std::cerr << "expected at least one freed chunk to be backend-owned\n"; + return 1; + } + if (CountingSecondary::owns_calls != calls_before) + { + std::cerr << "freed main-heap pointer reached the secondary allocator " + << (CountingSecondary::owns_calls - calls_before) << " times\n"; + return 1; + } + snmalloc::dealloc(allocs[0]); return 0; }