diff --git a/src/common/mem_pool.h b/src/common/mem_pool.h index f81f10d2..1b39d8a6 100644 --- a/src/common/mem_pool.h +++ b/src/common/mem_pool.h @@ -27,6 +27,52 @@ namespace zen::common { #include "common/mem_pool_log.def" +#ifdef ZEN_ENABLE_EVM +// Custom allocator that uses malloc/free to avoid alloc-dealloc-mismatch +// across shared library boundaries +template struct MallocAllocator { + using value_type = T; + using pointer = T *; + using const_pointer = const T *; + using reference = T &; + using const_reference = const T &; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + + template struct rebind { + using other = MallocAllocator; + }; + + MallocAllocator() noexcept = default; + template MallocAllocator(const MallocAllocator &) noexcept {} + + T *allocate(std::size_t n) { + if (n == 0 || n > (std::numeric_limits::max() / sizeof(T))) { + ZEN_ABORT(); + return nullptr; + } + void *p = std::malloc(n * sizeof(T)); + if (!p) { + ZEN_ABORT(); + return nullptr; + } + return static_cast(p); + } + + void deallocate(T *p, std::size_t) noexcept { std::free(p); } +}; + +template +bool operator==(const MallocAllocator &, const MallocAllocator &) { + return true; +} + +template +bool operator!=(const MallocAllocator &, const MallocAllocator &) { + return false; +} +#endif // ZEN_ENABLE_EVM + enum MemPoolKind { SYS_POOL, // system malloc/free ALLOC_ONLY_POOL, // allocate only pool @@ -200,7 +246,14 @@ template <> class MemPool { std::atomic NumAllocs{0}; std::atomic AllocSize{0}; SharedMutex AllocMutex; +#ifdef ZEN_ENABLE_EVM + std::unordered_map, + std::equal_to, + MallocAllocator>> + AllocTypeNames; +#else std::unordered_map AllocTypeNames; +#endif // ZEN_ENABLE_EVM #endif };