Debian Codegraph @

vendor/Heap-Layers/wrappers/heapredirect.h

raw symbols SCIP
1 /*
2
3 Heap Layers: An Extensible Memory Allocation Infrastructure
4
5 Copyright (C) 2000-2020 by Emery Berger
6 http://www.emeryberger.com
7 [email protected]
8
9 Heap Layers is distributed under the terms of the Apache 2.0 license.
10
11 You may obtain a copy of the License at
12 http://www.apache.org/licenses/LICENSE-2.0
13
14 */
15 #pragma once
16
17 #ifndef HL_HEAPREDIRECT_H
18 #define HL_HEAPREDIRECT_H
19
20 #if !defined(likely)
21 #define likely(x) __builtin_expect(!!(x), 1)
22 #endif
23 #if !defined(unlikely)
24 #define unlikely(x) __builtin_expect(!!(x), 0)
25 #endif
26 #if !defined ATTRIBUTE_EXPORT
27 #define ATTRIBUTE_EXPORT __attribute__((visibility("default")))
28 #endif
29
30 #include "printf.h"
31
32 namespace HL {
33
34 /**
35 * Redirects the system heap calls to a custom heap, using Heap-Layers' wrappers.
36 *
37 * In order to service ::malloc through a custom heap, the custom heap's constructor
38 * and its malloc method need to run; if either one of these, directly or indirectly,
39 * need to call ::malloc, that would lead to an infinite recursion. To avoid this, we
40 * detect such recursive ::malloc calls using a thread-local boolean variable and service
41 * them from a statically allocated heap.
42 *
43 * The thread-local variable's and the static heap's initialization must be done carefully
44 * so as not to require ::malloc when no heap is available to service it from. To further
45 * complicate things, ::malloc is/can be invoked early during executable startup, before
46 * C++ constructors for global objects. On MacOS, this seems to happen before thread
47 * initialization: attempts to use thread_local or __thread lead to an abort() in _tlv_bootstrap.
48 *
49 * To work around the C++ constructor issue, we use static initializers within functions;
50 * for the thread_local/__thread issue, we use POSIX thread-local data. We prefer __atomic
51 * calls to std::atomic because STL code feels more likely to invoke malloc.
52 * We use std::recursive_mutex and std::lock_guard to avoid introducing more code and because
53 * they don't seem to require malloc, but may need to move to pthread_mutex if that should change.
54 *
55 * The problem is really that "won't use malloc" AFAIK isn't part of most of these primitives'
56 * contracts, so we stand on shaky ground.
57 *
58 * @author Juan Altmayer Pizzorno
59 */
60
61 // NOTE: The static heap functionality is currently disabled (as of 8/27/2021).
62
63 template<typename CustomHeapType, int STATIC_HEAP_SIZE>
64 class HeapWrapper {
65 typedef LockedHeap<std::mutex, StaticBufferHeap<STATIC_HEAP_SIZE>> StaticHeapType;
66
67 // Using a static bool is not thread safe, but gives us a benchmarking
68 // baseline for this implementation.
69 #define HW_USE_STATIC_BOOL 0
70
71 static bool* getInMallocFlag() {
72 #if !HW_USE_STATIC_BOOL
73 // modified double-checked locking pattern (https://en.wikipedia.org/wiki/Double-checked_locking)
74 static enum {NEEDS_KEY=0, CREATING_KEY=1, DONE=2} inMallocKeyState{NEEDS_KEY};
75 static pthread_key_t inMallocKey;
76 static std::recursive_mutex m;
77
78 auto state = __atomic_load_n(&inMallocKeyState, __ATOMIC_ACQUIRE);
79 if (state != DONE) {
80 std::lock_guard<decltype(m)> g{m};
81
82 state = __atomic_load_n(&inMallocKeyState, __ATOMIC_RELAXED);
83 if (unlikely(state == CREATING_KEY)) {
84 return nullptr; // recursively invoked
85 }
86 else if (unlikely(state == NEEDS_KEY)) {
87 __atomic_store_n(&inMallocKeyState, CREATING_KEY, __ATOMIC_RELAXED);
88 if (pthread_key_create(&inMallocKey, 0) != 0) { // may call malloc/calloc/...
89 abort();
90 }
91 __atomic_store_n(&inMallocKeyState, DONE, __ATOMIC_RELEASE);
92 }
93 }
94
95 bool* flag = (bool*)pthread_getspecific(inMallocKey); // not expected to call malloc
96 if (unlikely(flag == nullptr)) {
97 std::lock_guard<decltype(m)> g{m};
98
99 static bool initializing = false;
100 if (initializing) {
101 return nullptr; // recursively invoked
102 }
103
104 initializing = true;
105 flag = (bool*)getHeap<StaticHeapType>()->malloc(sizeof(bool));
106 *flag = false;
107 if (pthread_setspecific(inMallocKey, flag) != 0) { // may call malloc/calloc/...
108 abort();
109 }
110 initializing = false;
111 }
112
113 return flag;
114 #else
115 static bool inMalloc = false;
116 return &inMalloc;
117 #endif
118 }
119
120 public:
121 template<class HEAP>
122 static inline HEAP* getHeap() {
123 // Allocate heap on first use and never destroy it, for malloc and such
124 // may still be used in atexit()
125 alignas(std::max_align_t) static char buffer[sizeof(HEAP)];
126 static HEAP* heap = new (buffer) HEAP;
127 return heap;
128 }
129
130 static inline void* malloc(size_t sz) {
131 auto ptr = getHeap<CustomHeapType>()->malloc(sz);
132 assert(isValid(ptr));
133 return ptr;
134 }
135
136 static inline void *memalign(size_t alignment, size_t sz) {
137 auto ptr = getHeap<CustomHeapType>()->memalign(alignment, sz);
138 assert(isValid(ptr));
139 return ptr;
140 }
141
142 #if HL_USE_XXREALLOC
143 static inline void* realloc(void * ptr, size_t sz) {
144 auto buf = getHeap<CustomHeapType>()->realloc(ptr, sz);
145 assert(isValid(buf));
146 return buf;
147 }
148 #endif
149
150 static inline bool isValid(void * ptr) {
151 #if !defined(__GLIBC__)
152 (void) ptr;
153 return true;
154 #else
155 // Special handling for glibc, adapted from
156 // https://sources.debian.org/src/glibc/2.31-17/malloc/malloc.c/
157 if (!ptr) {
158 return true;
159 }
160 enum {
161 PREV_INUSE = 0x01,
162 IS_MMAPPED = 0x02,
163 NON_MAIN_ARENA = 0x04 };
164 struct malloc_chunk {
165 size_t mchunk_prev_size;
166 size_t mchunk_size;
167 };
168 auto mchunk = (malloc_chunk *) ptr - 1;
169 auto size = mchunk->mchunk_size & ~(PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA);
170 if ((uintptr_t) ptr > (uintptr_t) -size) {
171 return false;
172 }
173 return true;
174 #endif
175 }
176
177 static inline void free(void* ptr) {
178 if (ptr) {
179 getHeap<CustomHeapType>()->free(ptr);
180 }
181 }
182
183 static inline size_t getSize(void *ptr) {
184 if (ptr) {
185 // if (isValid(ptr)) {
186 return getHeap<CustomHeapType>()->getSize(ptr);
187 }
188 return 0;
189 }
190
191 static inline void xxmalloc_lock() {
192 getHeap<CustomHeapType>()->lock();
193 }
194
195 static inline void xxmalloc_unlock() {
196 getHeap<CustomHeapType>()->unlock();
197 }
198
199 // For use with sampling allocation from https://github.com/plasma-umass/scalene
200 static inline void register_malloc(size_t sz, void * ptr) {
201 getHeap<CustomHeapType>()->register_malloc(sz, ptr);
202 }
203
204 static inline void register_free(size_t sz, void * ptr) {
205 if (ptr) {
206 getHeap<CustomHeapType>()->register_free(sz, ptr);
207 }
208 }
209
210 };
211
212 } // namespace
213
214 #if HL_USE_XXREALLOC
215 #define HEAP_REDIRECT(CustomHeap, staticSize)\
216 typedef HL::HeapWrapper<CustomHeap, staticSize> TheHeapWrapper;\
217 extern "C" {\
218 ATTRIBUTE_EXPORT void *xxmalloc(size_t sz) {\
219 return TheHeapWrapper::malloc(sz);\
220 }\
221 \
222 ATTRIBUTE_EXPORT void xxfree(void *ptr) {\
223 TheHeapWrapper::free(ptr);\
224 }\
225 \
226 ATTRIBUTE_EXPORT void *xxmemalign(size_t alignment, size_t sz) {\
227 return TheHeapWrapper::memalign(alignment, sz);\
228 }\
229 \
230 ATTRIBUTE_EXPORT size_t xxmalloc_usable_size(void *ptr) {\
231 return TheHeapWrapper::getSize(ptr); \
232 }\
233 \
234 ATTRIBUTE_EXPORT void xxmalloc_lock() {\
235 TheHeapWrapper::xxmalloc_lock();\
236 }\
237 \
238 ATTRIBUTE_EXPORT void xxmalloc_unlock() {\
239 TheHeapWrapper::xxmalloc_unlock();\
240 }\
241 ATTRIBUTE_EXPORT void* xxrealloc(void * ptr, size_t sz) {\
242 return TheHeapWrapper::realloc(ptr, sz); \
243 }\
244 }
245 #else
246 #define HEAP_REDIRECT(CustomHeap, staticSize)\
247 typedef HL::HeapWrapper<CustomHeap, staticSize> TheHeapWrapper;\
248 extern "C" {\
249 ATTRIBUTE_EXPORT void *xxmalloc(size_t sz) {\
250 return TheHeapWrapper::malloc(sz);\
251 }\
252 \
253 ATTRIBUTE_EXPORT void xxfree(void *ptr) {\
254 TheHeapWrapper::free(ptr);\
255 }\
256 \
257 ATTRIBUTE_EXPORT void *xxmemalign(size_t alignment, size_t sz) {\
258 return TheHeapWrapper::memalign(alignment, sz);\
259 }\
260 \
261 ATTRIBUTE_EXPORT size_t xxmalloc_usable_size(void *ptr) {\
262 return TheHeapWrapper::getSize(ptr); \
263 }\
264 \
265 ATTRIBUTE_EXPORT void xxmalloc_lock() {\
266 TheHeapWrapper::xxmalloc_lock();\
267 }\
268 \
269 ATTRIBUTE_EXPORT void xxmalloc_unlock() {\
270 TheHeapWrapper::xxmalloc_unlock();\
271 }\
272 }
273
274 #endif
275 #endif