Skip to content

Commit 087fec3

Browse files
committed
fix(evm): fix alloc-dealloc-mismatch in debug memory tracking
1 parent a4015aa commit 087fec3

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

src/common/mem_pool.h

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,52 @@ namespace zen::common {
2727

2828
#include "common/mem_pool_log.def"
2929

30+
#ifdef ZEN_ENABLE_EVM
31+
// Custom allocator that uses malloc/free to avoid alloc-dealloc-mismatch
32+
// across shared library boundaries
33+
template <typename T> struct MallocAllocator {
34+
using value_type = T;
35+
using pointer = T *;
36+
using const_pointer = const T *;
37+
using reference = T &;
38+
using const_reference = const T &;
39+
using size_type = std::size_t;
40+
using difference_type = std::ptrdiff_t;
41+
42+
template <class U> struct rebind {
43+
using other = MallocAllocator<U>;
44+
};
45+
46+
MallocAllocator() noexcept = default;
47+
template <class U> MallocAllocator(const MallocAllocator<U> &) noexcept {}
48+
49+
T *allocate(std::size_t n) {
50+
if (n == 0 || n > (std::numeric_limits<std::size_t>::max() / sizeof(T))) {
51+
ZEN_ABORT();
52+
return nullptr;
53+
}
54+
void *p = std::malloc(n * sizeof(T));
55+
if (!p) {
56+
ZEN_ABORT();
57+
return nullptr;
58+
}
59+
return static_cast<T *>(p);
60+
}
61+
62+
void deallocate(T *p, std::size_t) noexcept { std::free(p); }
63+
};
64+
65+
template <typename T, typename U>
66+
bool operator==(const MallocAllocator<T> &, const MallocAllocator<U> &) {
67+
return true;
68+
}
69+
70+
template <typename T, typename U>
71+
bool operator!=(const MallocAllocator<T> &, const MallocAllocator<U> &) {
72+
return false;
73+
}
74+
#endif // ZEN_ENABLE_EVM
75+
3076
enum MemPoolKind {
3177
SYS_POOL, // system malloc/free
3278
ALLOC_ONLY_POOL, // allocate only pool
@@ -200,7 +246,14 @@ template <> class MemPool<SYS_POOL> {
200246
std::atomic<size_t> NumAllocs{0};
201247
std::atomic<size_t> AllocSize{0};
202248
SharedMutex AllocMutex;
249+
#ifdef ZEN_ENABLE_EVM
250+
std::unordered_map<uintptr_t, const char *, std::hash<uintptr_t>,
251+
std::equal_to<uintptr_t>,
252+
MallocAllocator<std::pair<const uintptr_t, const char *>>>
253+
AllocTypeNames;
254+
#else
203255
std::unordered_map<uintptr_t, const char *> AllocTypeNames;
256+
#endif // ZEN_ENABLE_EVM
204257
#endif
205258
};
206259

0 commit comments

Comments
 (0)