Debian Codegraph @

src/source/libscalene.cpp

raw symbols SCIP
1 #define SCALENE_DISABLE_SIGNALS 0 // for debugging only
2
3 #if !defined(_WIN32)
4 #include <unistd.h>
5 #endif
6
7 #include <heaplayers.h>
8 #include <signal.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 #include <cstddef>
13
14 #include "common.hpp"
15 #include "heapredirect.h"
16 #include "memcpysampler.hpp"
17 #include "sampleheap.hpp"
18 #include "scaleneheader.hpp"
19
20 #if defined(__APPLE__)
21 #include "macinterpose.h"
22 #endif
23
24 // Allocate exactly one system heap.
25 using BaseHeap = HL::OneHeap<HL::SysMallocHeap>;
26
27 // For use by the replacement printf routines (see
28 // https://github.com/mpaland/printf)
29 extern "C" void _putchar(char ch) { ::write(1, (void *)&ch, 1); }
30
31 constexpr uint64_t DefaultAllocationSamplingRate =
32 1 * 10485767ULL; // was 1 * 1549351ULL;
33 constexpr uint64_t MemcpySamplingRate = DefaultAllocationSamplingRate * 7;
34
35 /**
36 * @brief the replacement heap for sampling purposes
37 *
38 */
39 class CustomHeapType
40 : public HL::ThreadSpecificHeap<
41 SampleHeap<DefaultAllocationSamplingRate, BaseHeap>> {
42 using super = HL::ThreadSpecificHeap<
43 SampleHeap<DefaultAllocationSamplingRate, BaseHeap>>;
44
45 public:
46 void lock() {}
47 void unlock() {}
48 };
49
50 HEAP_REDIRECT(CustomHeapType, 8 * 1024 * 1024);
51
52 /**
53 * @brief Get the static MemcpySampler object
54 *
55 * @return auto& the singleton sampling object
56 */
57 auto &getSampler() {
58 static MemcpySampler<MemcpySamplingRate> msamp;
59 return msamp;
60 }
61
62 #if defined(__APPLE__)
63 #define LOCAL_PREFIX(x) xx##x
64 #else
65 #define LOCAL_PREFIX(x) x
66 #endif
67
68 extern "C" ATTRIBUTE_EXPORT void *LOCAL_PREFIX(memcpy)(void *dst,
69 const void *src,
70 size_t n) {
71 auto result = getSampler().memcpy(dst, src, n);
72 return result;
73 }
74
75 extern "C" ATTRIBUTE_EXPORT void *LOCAL_PREFIX(memmove)(void *dst,
76 const void *src,
77 size_t n) {
78 auto result = getSampler().memmove(dst, src, n);
79 return result;
80 }
81
82 extern "C" ATTRIBUTE_EXPORT char *LOCAL_PREFIX(strcpy)(char *dst,
83 const char *src) {
84 auto result = getSampler().strcpy(dst, src);
85 return result;
86 }
87
88 // Intercept local allocation for tracking when using the (fast, built-in)
89 // pymalloc allocator.
90
91 #if !defined(_WIN32)
92
93 #include <Python.h>
94
95 #define DL_FUNCTION(name) \
96 static decltype(name) *dl##name = (decltype(name) *)dlsym(RTLD_DEFAULT, #name)
97
98 // Maximum size allocated internally by pymalloc;
99 // aka "SMALL_REQUEST_THRESHOLD" in cpython/Objects/obmalloc.c
100 #define PYMALLOC_MAX_SIZE 512
101
102 /**
103 * @brief replace local Python allocators with our own sampling variants
104 *
105 * @tparam Domain the Python domain of allocator we replace
106 */
107
108 template <PyMemAllocatorDomain Domain>
109 class MakeLocalAllocator {
110 public:
111 MakeLocalAllocator() {
112 localAlloc = {.ctx = nullptr,
113 .malloc = local_malloc,
114 .calloc = local_calloc,
115 .realloc = local_realloc,
116 .free = local_free};
117
118 DL_FUNCTION(PyMem_GetAllocator);
119 DL_FUNCTION(PyMem_SetAllocator);
120
121 if (dlPyMem_GetAllocator != nullptr && dlPyMem_SetAllocator != nullptr) {
122 // if these aren't found, chances are we were preloaded onto something
123 // other than Python
124 dlPyMem_GetAllocator(Domain, get_original_allocator());
125 dlPyMem_SetAllocator(Domain, &localAlloc);
126 }
127 }
128
129 private:
130 /// @brief the actual allocator we use to satisfy object allocations
131 PyMemAllocatorEx localAlloc;
132
133 static inline PyMemAllocatorEx *get_original_allocator() {
134 // poor man's "static inline" member
135 static PyMemAllocatorEx original_allocator;
136 return &original_allocator;
137 }
138
139 static inline void *local_malloc(void *ctx, size_t len) {
140 MallocRecursionGuard m;
141 #if 1
142 // Ensure all allocation requests are multiples of eight,
143 // mirroring the actual allocation sizes employed by pymalloc
144 // (See https://github.com/python/cpython/blob/main/Objects/obmalloc.c#L807)
145 if (len <= PYMALLOC_MAX_SIZE) {
146 if (unlikely(len == 0)) {
147 // Handle 0.
148 len = 8;
149 }
150 len = (len + 7) & ~7;
151 }
152 #endif
153 #if USE_HEADERS
154 void *buf = nullptr;
155 const auto allocSize = len + sizeof(ScaleneHeader);
156 buf = get_original_allocator()->malloc(get_original_allocator()->ctx,
157 allocSize);
158 auto *header = new (buf) ScaleneHeader(len);
159 class Nada {};
160 #else
161 auto *header = (ScaleneHeader *)get_original_allocator()->malloc(
162 get_original_allocator()->ctx, len);
163 #endif
164 assert(header); // We expect this to always succeed.
165 if (!m.wasInMalloc()) {
166 TheHeapWrapper::register_malloc(len, ScaleneHeader::getObject(header));
167 }
168
169 static_assert(
170 SampleHeap<1, HL::NullHeap<Nada>>::NEWLINE > PYMALLOC_MAX_SIZE,
171 "NEWLINE must be greater than PYMALLOC_MAX_SIZE.");
172 #if USE_HEADERS
173 assert((size_t)ScaleneHeader::getObject(header) - (size_t)header >=
174 sizeof(ScaleneHeader));
175 #ifndef NDEBUG
176 if (ScaleneHeader::getSize(ScaleneHeader::getObject(header)) < len) {
177 printf_("Size mismatch: %lu %lu\n",
178 ScaleneHeader::getSize(ScaleneHeader::getObject(header)), len);
179 }
180 #endif
181 assert(ScaleneHeader::getSize(ScaleneHeader::getObject(header)) >= len);
182 #endif
183 return ScaleneHeader::getObject(header);
184 }
185
186 static inline void local_free(void *ctx, void *ptr) {
187 // ignore nullptr
188 if (ptr) {
189 MallocRecursionGuard m;
190 const auto sz = ScaleneHeader::getSize(ptr);
191
192 if (!m.wasInMalloc()) {
193 TheHeapWrapper::register_free(sz, ptr);
194 }
195 get_original_allocator()->free(get_original_allocator()->ctx,
196 ScaleneHeader::getHeader(ptr));
197 }
198 }
199
200 static inline void *local_realloc(void *ctx, void *ptr, size_t new_size) {
201 if (new_size < 8) {
202 new_size = 8;
203 }
204 if (!ptr) {
205 return local_malloc(ctx, new_size);
206 }
207 MallocRecursionGuard m;
208 const auto sz = ScaleneHeader::getSize(ptr);
209 void *p = nullptr;
210 const auto allocSize = new_size + sizeof(ScaleneHeader);
211 void *buf = get_original_allocator()->realloc(get_original_allocator()->ctx,
212 ScaleneHeader::getHeader(ptr),
213 allocSize);
214 ScaleneHeader *result = new (buf) ScaleneHeader(new_size);
215 if (result && !m.wasInMalloc()) {
216 if (sz < new_size) {
217 TheHeapWrapper::register_malloc(new_size - sz,
218 ScaleneHeader::getObject(result));
219 } else if (sz > new_size) {
220 TheHeapWrapper::register_free(sz - new_size, ptr);
221 }
222 }
223 ScaleneHeader::setSize(ScaleneHeader::getObject(result), new_size);
224 p = ScaleneHeader::getObject(result);
225 return p;
226 }
227
228 static inline void *local_calloc(void *ctx, size_t nelem, size_t elsize) {
229 const auto nbytes = nelem * elsize;
230 void *obj = local_malloc(ctx, nbytes);
231 if (true) { // obj) {
232 memset(obj, 0, nbytes);
233 }
234 return obj;
235 }
236
237 private:
238 static constexpr size_t MAGIC_NUMBER = 0x01020304;
239 };
240
241 // from pywhere.hpp
242 decltype(p_whereInPython)
243 __attribute((visibility("default"))) p_whereInPython{nullptr};
244
245 std::atomic_bool __attribute((visibility("default"))) p_scalene_done{true};
246
247 static MakeLocalAllocator<PYMEM_DOMAIN_MEM> l_mem;
248 static MakeLocalAllocator<PYMEM_DOMAIN_OBJ> l_obj;
249
250 #if defined(__APPLE__)
251 MAC_INTERPOSE(xxmemcpy, memcpy);
252 MAC_INTERPOSE(xxmemmove, memmove);
253 MAC_INTERPOSE(xxstrcpy, strcpy);
254 #endif
255
256 #endif