| 1 | #pragma once |
| 2 | #ifndef MALLOCRECURSIONGUARD_H |
| 3 | #define MALLOCRECURSIONGUARD_H |
| 4 | |
| 5 | #include <pthread.h> |
| 6 | |
| 7 | #include <mutex> |
| 8 | |
| 9 | #include "common.hpp" |
| 10 | |
| 11 | /** |
| 12 | * Implements a thread-specific flag to guard against inadvertent recursions |
| 13 | * when interposing heap functions. |
| 14 | */ |
| 15 | class MallocRecursionGuard { |
| 16 | static pthread_key_t* getKey() { |
| 17 | static pthread_key_t _inMallocKey; |
| 18 | return &_inMallocKey; |
| 19 | } |
| 20 | |
| 21 | enum { NEEDS_KEY = 0, CREATING_KEY = 1, DONE = 2 }; |
| 22 | |
| 23 | static inline bool isInMalloc() { |
| 24 | // modified double-checked locking pattern |
| 25 | // (https://en.wikipedia.org/wiki/Double-checked_locking) |
| 26 | static std::recursive_mutex m; |
| 27 | static int inMallocKeyState{NEEDS_KEY}; |
| 28 | |
| 29 | // We create the thread-specific data store the pthread way because the C++ |
| 30 | // language based ones all seem to fail when interposing on malloc et al., |
| 31 | // as they are invoked early from within library initialization. |
| 32 | |
| 33 | auto state = __atomic_load_n(&inMallocKeyState, __ATOMIC_ACQUIRE); |
| 34 | if (state != DONE) { |
| 35 | if (slowPathInMalloc(m, inMallocKeyState) == CREATING_KEY) { |
| 36 | // this happens IFF pthread_key_create allocates memory |
| 37 | return true; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | return pthread_getspecific(*getKey()) != 0; |
| 42 | } |
| 43 | |
| 44 | static int slowPathInMalloc(std::recursive_mutex& m, int& inMallocKeyState) { |
| 45 | std::lock_guard<decltype(m)> g{m}; |
| 46 | |
| 47 | auto state = __atomic_load_n(&inMallocKeyState, __ATOMIC_RELAXED); |
| 48 | |
| 49 | if (unlikely(state == NEEDS_KEY)) { |
| 50 | __atomic_store_n(&inMallocKeyState, CREATING_KEY, __ATOMIC_RELAXED); |
| 51 | if (pthread_key_create(getKey(), 0) != 0) { // may call [cm]alloc |
| 52 | abort(); |
| 53 | } |
| 54 | __atomic_store_n(&inMallocKeyState, DONE, __ATOMIC_RELEASE); |
| 55 | return DONE; |
| 56 | } |
| 57 | |
| 58 | return state; |
| 59 | } |
| 60 | |
| 61 | static inline void setInMalloc(bool state) { |
| 62 | pthread_setspecific(*getKey(), state ? (void*)1 : (void*)0); |
| 63 | } |
| 64 | |
| 65 | bool _wasInMalloc; |
| 66 | |
| 67 | MallocRecursionGuard(const MallocRecursionGuard&) = delete; |
| 68 | MallocRecursionGuard& operator=(const MallocRecursionGuard&) = delete; |
| 69 | |
| 70 | public: |
| 71 | inline MallocRecursionGuard() { |
| 72 | if (!(_wasInMalloc = isInMalloc())) { |
| 73 | setInMalloc(true); |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | inline ~MallocRecursionGuard() { |
| 78 | if (!_wasInMalloc) { |
| 79 | setInMalloc(false); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | inline bool wasInMalloc() const { return _wasInMalloc; } |
| 84 | }; |
| 85 | |
| 86 | #endif |