| 1 | #pragma once |
| 2 | |
| 3 | #ifndef SAMPLEHEAP_H |
| 4 | #define SAMPLEHEAP_H |
| 5 | |
| 6 | #include <assert.h> |
| 7 | #include <dlfcn.h> |
| 8 | #include <fcntl.h> |
| 9 | #include <signal.h> |
| 10 | #include <stdlib.h> |
| 11 | #include <sys/errno.h> |
| 12 | #include <sys/mman.h> |
| 13 | #include <sys/stat.h> |
| 14 | #include <sys/syscall.h> |
| 15 | #include <sys/types.h> |
| 16 | #include <unistd.h> // for getpid() |
| 17 | |
| 18 | #include <atomic> |
| 19 | #include <random> |
| 20 | |
| 21 | // We're unable to use the limited API because, for example, |
| 22 | // there doesn't seem to be a function returning co_filename |
| 23 | // #define Py_LIMITED_API 0x03070000 |
| 24 | |
| 25 | #include "common.hpp" |
| 26 | #include "mallocrecursionguard.hpp" |
| 27 | #include "poissonsampler.hpp" |
| 28 | #include "printf.h" |
| 29 | #include "pywhere.hpp" |
| 30 | #include "samplefile.hpp" |
| 31 | #include "scaleneheader.hpp" |
| 32 | #include "thresholdsampler.hpp" |
| 33 | |
| 34 | static SampleFile& getSampleFile() { |
| 35 | static SampleFile mallocSampleFile("/tmp/scalene-malloc-signal%d", |
| 36 | "/tmp/scalene-malloc-lock%d", |
| 37 | "/tmp/scalene-malloc-init%d"); |
| 38 | |
| 39 | return mallocSampleFile; |
| 40 | } |
| 41 | |
| 42 | #define USE_ATOMICS 0 |
| 43 | #if USE_ATOMICS |
| 44 | typedef std::atomic<uint64_t> counterType; |
| 45 | #else |
| 46 | typedef uint64_t counterType; |
| 47 | #endif |
| 48 | |
| 49 | template <uint64_t DefaultAllocationSamplingRateBytes, class SuperHeap> |
| 50 | class SampleHeap : public SuperHeap { |
| 51 | constexpr static auto sampling_window_envname = |
| 52 | "SCALENE_ALLOCATION_SAMPLING_WINDOW"; |
| 53 | |
| 54 | public: |
| 55 | enum { Alignment = SuperHeap::Alignment }; |
| 56 | enum AllocSignal { MallocSignal = SIGXCPU, FreeSignal = SIGXFSZ }; |
| 57 | static constexpr uint64_t NEWLINE = |
| 58 | 98821; // Sentinel value denoting a new line has executed |
| 59 | |
| 60 | SampleHeap() |
| 61 | : _lastMallocTrigger(nullptr), |
| 62 | _freedLastMallocTrigger(false), |
| 63 | _allocationSampler(getenv(sampling_window_envname) |
| 64 | ? atol(getenv(sampling_window_envname)) |
| 65 | : DefaultAllocationSamplingRateBytes) { |
| 66 | getSampleFile(); // invoked here so the file gets initialized before python |
| 67 | // attempts to read from it |
| 68 | |
| 69 | get_signal_init_lock().lock(); |
| 70 | auto old_malloc = signal(MallocSignal, SIG_IGN); |
| 71 | if (old_malloc != SIG_DFL) { |
| 72 | signal(MallocSignal, old_malloc); |
| 73 | } |
| 74 | auto old_free = signal(FreeSignal, SIG_IGN); |
| 75 | if (old_free != SIG_DFL) { |
| 76 | signal(FreeSignal, old_free); |
| 77 | } |
| 78 | get_signal_init_lock().unlock(); |
| 79 | } |
| 80 | |
| 81 | ATTRIBUTE_ALWAYS_INLINE inline void* malloc(size_t sz) { |
| 82 | MallocRecursionGuard g; |
| 83 | auto ptr = SuperHeap::malloc(sz); |
| 84 | if (unlikely(ptr == nullptr)) { |
| 85 | return nullptr; |
| 86 | } |
| 87 | if (pythonDetected() && !g.wasInMalloc()) { |
| 88 | // All standard Python allocations pass through |
| 89 | // MakeLocalAllocator in libscalene.cpp . |
| 90 | // We don't want to double-count these allocations-- |
| 91 | // if we're in here and g.wasInMalloc is true, then |
| 92 | // we passed through MakeLocalAllocator and |
| 93 | // this allocation has already been counted |
| 94 | // |
| 95 | // We only want to count allocations here |
| 96 | // if `malloc` itself was called by client code. |
| 97 | auto realSize = SuperHeap::getSize(ptr); |
| 98 | if (realSize > 0) { |
| 99 | if (sz == NEWLINE + sizeof(ScaleneHeader)) { |
| 100 | // FIXME |
| 101 | // |
| 102 | // If we ourselves are allocating a NEWLINE, we're doing |
| 103 | // it through the Python allocator, so if it's an actual newline |
| 104 | // I don't think we should ever get here. I think our original intention |
| 105 | // is that we shouldn't count NEWLINE records that we already counted, |
| 106 | // but I think if we get to this line here, we didn't actually create a NEWLINE |
| 107 | // and should count it. |
| 108 | return ptr; |
| 109 | } |
| 110 | register_malloc(realSize, ptr, false); // false -> invoked from C/C++ |
| 111 | } |
| 112 | } |
| 113 | return ptr; |
| 114 | } |
| 115 | ATTRIBUTE_ALWAYS_INLINE inline void* realloc(void* ptr, size_t sz) { |
| 116 | MallocRecursionGuard g; |
| 117 | if (!ptr) { |
| 118 | ptr = SuperHeap::malloc(sz); |
| 119 | return ptr; |
| 120 | } |
| 121 | if (sz == 0) { |
| 122 | SuperHeap::free(ptr); |
| 123 | #if defined(__APPLE__) |
| 124 | // 0 size = free. We return a small object. This behavior is |
| 125 | // apparently required under Mac OS X and optional under POSIX. |
| 126 | return SuperHeap::malloc(1); |
| 127 | #else |
| 128 | // For POSIX, don't return anything. |
| 129 | return nullptr; |
| 130 | #endif |
| 131 | } |
| 132 | size_t objSize = SuperHeap::getSize(ptr); |
| 133 | |
| 134 | void* buf = SuperHeap::malloc(sz); |
| 135 | size_t buf_size = buf ? SuperHeap::getSize(buf) : 0; |
| 136 | if (buf) { |
| 137 | if (objSize == buf_size) { |
| 138 | // The objects are the same actual size. |
| 139 | // Free the new object and return the original. |
| 140 | SuperHeap::free(buf); |
| 141 | return ptr; |
| 142 | } |
| 143 | // Copy the contents of the original object |
| 144 | // up to the size of the new block. |
| 145 | size_t minSize = (objSize < sz) ? objSize : sz; |
| 146 | memcpy(buf, ptr, minSize); |
| 147 | } |
| 148 | |
| 149 | // Free the old block. |
| 150 | SuperHeap::free(ptr); |
| 151 | if (buf) { |
| 152 | if (sz < buf_size) { |
| 153 | register_malloc(buf_size - sz, buf, |
| 154 | false); // false -> invoked from C/C++ |
| 155 | } else if (sz > buf_size) { |
| 156 | register_free(sz - buf_size, ptr); |
| 157 | } |
| 158 | } |
| 159 | // Return a pointer to the new one. |
| 160 | return buf; |
| 161 | } |
| 162 | inline void register_malloc(size_t realSize, void* ptr, |
| 163 | bool inPythonAllocator = true) { |
| 164 | if (p_scalene_done) return; |
| 165 | assert(realSize); |
| 166 | // If this is the special NEWLINE value, trigger an update. |
| 167 | if (unlikely(realSize == NEWLINE)) { |
| 168 | std::string filename; |
| 169 | // Originally, we had the following check around this line: |
| 170 | // |
| 171 | // ``` |
| 172 | // if (where != nullptr && where(filename, lineno, bytei)) |
| 173 | // ``` |
| 174 | // |
| 175 | // This was to prevent a NEWLINE record from being accidentally triggered by |
| 176 | // non-Scalene code. |
| 177 | // |
| 178 | // However, by definition, we trigger a NEWLINE _after_ the line has |
| 179 | // been executed, specifically on a `PyTrace_Line` event. |
| 180 | // |
| 181 | // If the absolute last line of a program makes an allocation, |
| 182 | // the next PyTrace_Line will occur inside `scalene_profiler.py` and not any client |
| 183 | // code, since the line after the last line of the program is when Scalene starts its |
| 184 | // teardown. |
| 185 | // |
| 186 | // In this case. the `whereInPython` function will return 0, since whereInPython checks |
| 187 | // if the current frame is in client code and the Scalene profiler teardown code is by definition |
| 188 | // not. |
| 189 | // |
| 190 | // This risks letting allocations of length NEWLINE_TRIGGER_LENGTH that are not true NEWLINEs |
| 191 | // create a NEWLINE record, but we view this as incredibly improbable. |
| 192 | writeCount(MallocSignal, realSize, ptr, filename, -1, -1); |
| 193 | mallocTriggered()++; |
| 194 | return; |
| 195 | } |
| 196 | size_t sampleMallocSize; |
| 197 | auto sampleMalloc = |
| 198 | _allocationSampler.increment(realSize, ptr, sampleMallocSize); |
| 199 | if (inPythonAllocator) { |
| 200 | _pythonCount += realSize; |
| 201 | } else { |
| 202 | _cCount += realSize; |
| 203 | } |
| 204 | if (unlikely(sampleMalloc)) { |
| 205 | process_malloc(sampleMallocSize, ptr); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | private: |
| 210 | void process_malloc(size_t sampleMalloc, void* ptr) { |
| 211 | std::string filename; |
| 212 | int lineno; |
| 213 | int bytei; |
| 214 | |
| 215 | decltype(whereInPython)* where = p_whereInPython; |
| 216 | if (where != nullptr && where(filename, lineno, bytei)) { |
| 217 | writeCount(MallocSignal, sampleMalloc, ptr, filename, lineno, bytei); |
| 218 | #if !SCALENE_DISABLE_SIGNALS |
| 219 | raise(MallocSignal); |
| 220 | #endif |
| 221 | _lastMallocTrigger = ptr; |
| 222 | _freedLastMallocTrigger = false; |
| 223 | _pythonCount = 0; |
| 224 | _cCount = 0; |
| 225 | mallocTriggered()++; |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | public: |
| 230 | ATTRIBUTE_ALWAYS_INLINE inline void free(void* ptr) { |
| 231 | MallocRecursionGuard g; |
| 232 | if (unlikely(ptr == nullptr)) { |
| 233 | return; |
| 234 | } |
| 235 | auto realSize = SuperHeap::getSize(ptr); |
| 236 | SuperHeap::free(ptr); |
| 237 | if (pythonDetected() && !g.wasInMalloc()) { |
| 238 | register_free(realSize, ptr); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | inline void register_free(size_t realSize, void* ptr) { |
| 243 | if (p_scalene_done) return; |
| 244 | size_t sampleFreeSize; |
| 245 | auto sampleFree = |
| 246 | _allocationSampler.decrement(realSize, ptr, sampleFreeSize); |
| 247 | |
| 248 | if (unlikely(ptr && (ptr == _lastMallocTrigger))) { |
| 249 | _freedLastMallocTrigger = true; |
| 250 | } |
| 251 | if (unlikely(sampleFree)) { |
| 252 | process_free(sampleFreeSize); |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | private: |
| 257 | void process_free(size_t sampleFree) { |
| 258 | std::string filename; |
| 259 | int lineno = 1; |
| 260 | int bytei = 0; |
| 261 | |
| 262 | #if 1 |
| 263 | decltype(whereInPython)* where = p_whereInPython; |
| 264 | if (where != nullptr && where(filename, lineno, bytei)) { |
| 265 | ; |
| 266 | } |
| 267 | #endif |
| 268 | |
| 269 | writeCount(FreeSignal, sampleFree, nullptr, filename, lineno, bytei); |
| 270 | #if !SCALENE_DISABLE_SIGNALS |
| 271 | raise(FreeSignal); |
| 272 | #endif |
| 273 | freeTriggered()++; |
| 274 | } |
| 275 | |
| 276 | public: |
| 277 | void* memalign(size_t alignment, size_t sz) { |
| 278 | MallocRecursionGuard g; |
| 279 | auto ptr = SuperHeap::memalign(alignment, sz); |
| 280 | if (unlikely(ptr == nullptr)) { |
| 281 | return nullptr; |
| 282 | } |
| 283 | if (pythonDetected() && !g.wasInMalloc()) { |
| 284 | auto realSize = SuperHeap::getSize(ptr); |
| 285 | assert(realSize >= sz); |
| 286 | // EDB 4 June 2023, disabled below, possibly spurious assertion |
| 287 | // assert((sz < 16) || (realSize <= 2 * sz)); |
| 288 | register_malloc(realSize, ptr, false); // false -> invoked from C/C++ |
| 289 | } |
| 290 | return ptr; |
| 291 | } |
| 292 | |
| 293 | private: |
| 294 | // Prevent copying and assignment. |
| 295 | SampleHeap(const SampleHeap&) = delete; |
| 296 | SampleHeap& operator=(const SampleHeap&) = delete; |
| 297 | |
| 298 | static auto& mallocTriggered() { |
| 299 | static std::atomic<uint64_t> _mallocTriggered{0}; |
| 300 | return _mallocTriggered; |
| 301 | } |
| 302 | static auto& freeTriggered() { |
| 303 | static std::atomic<uint64_t> _freeTriggered{0}; |
| 304 | return _freeTriggered; |
| 305 | } |
| 306 | |
| 307 | counterType _pythonCount{0}; |
| 308 | counterType _cCount{0}; |
| 309 | |
| 310 | void* _lastMallocTrigger; |
| 311 | bool _freedLastMallocTrigger; |
| 312 | #if 0 |
| 313 | typedef PoissonSampler Sampler; |
| 314 | #warning "Experimental use only: Poisson sampler" |
| 315 | #else |
| 316 | typedef ThresholdSampler Sampler; |
| 317 | #endif |
| 318 | |
| 319 | Sampler _allocationSampler; |
| 320 | |
| 321 | static constexpr auto flags = O_RDWR | O_CREAT; |
| 322 | static constexpr auto perms = S_IRUSR | S_IWUSR; |
| 323 | |
| 324 | void writeCount(AllocSignal sig, uint64_t count, void* ptr, |
| 325 | const std::string& filename, int lineno, int bytei) { |
| 326 | char buf[SampleFile::MAX_BUFSIZE]; |
| 327 | if (_pythonCount == 0) { |
| 328 | _pythonCount = 1; // prevent 0/0 |
| 329 | } |
| 330 | snprintf_( |
| 331 | buf, sizeof(buf), |
| 332 | #if defined(__APPLE__) |
| 333 | "%c,%llu,%llu,%f,%d,%p,%s,%d,%d\n\n", |
| 334 | #else |
| 335 | "%c,%lu,%lu,%f,%d,%p,%s,%d,%d\n\n", |
| 336 | #endif |
| 337 | ((sig == MallocSignal) ? 'M' : ((_freedLastMallocTrigger) ? 'f' : 'F')), |
| 338 | mallocTriggered() + freeTriggered(), count, |
| 339 | (float)_pythonCount / (_pythonCount + _cCount), getpid(), |
| 340 | _freedLastMallocTrigger ? _lastMallocTrigger : ptr, filename.c_str(), |
| 341 | lineno, bytei); |
| 342 | // Ensure we don't report last-malloc-freed multiple times. |
| 343 | _freedLastMallocTrigger = false; |
| 344 | getSampleFile().writeToFile(buf); |
| 345 | } |
| 346 | |
| 347 | static HL::PosixLock& get_signal_init_lock() { |
| 348 | static HL::PosixLock signal_init_lock; |
| 349 | return signal_init_lock; |
| 350 | } |
| 351 | }; |
| 352 | |
| 353 | #endif |