13cab2bb3Spatrick //===-- guarded_pool_allocator.cpp ------------------------------*- C++ -*-===//
23cab2bb3Spatrick //
33cab2bb3Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
43cab2bb3Spatrick // See https://llvm.org/LICENSE.txt for license information.
53cab2bb3Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63cab2bb3Spatrick //
73cab2bb3Spatrick //===----------------------------------------------------------------------===//
83cab2bb3Spatrick
93cab2bb3Spatrick #include "gwp_asan/guarded_pool_allocator.h"
103cab2bb3Spatrick
11*810390e3Srobert #include "gwp_asan/crash_handler.h"
123cab2bb3Spatrick #include "gwp_asan/options.h"
131f9cb04fSpatrick #include "gwp_asan/utilities.h"
143cab2bb3Spatrick
153cab2bb3Spatrick #include <assert.h>
16d89ec533Spatrick #include <stddef.h>
173cab2bb3Spatrick
181f9cb04fSpatrick using AllocationMetadata = gwp_asan::AllocationMetadata;
191f9cb04fSpatrick using Error = gwp_asan::Error;
203cab2bb3Spatrick
213cab2bb3Spatrick namespace gwp_asan {
223cab2bb3Spatrick namespace {
233cab2bb3Spatrick // Forward declare the pointer to the singleton version of this class.
243cab2bb3Spatrick // Instantiated during initialisation, this allows the signal handler
253cab2bb3Spatrick // to find this class in order to deduce the root cause of failures. Must not be
263cab2bb3Spatrick // referenced by users outside this translation unit, in order to avoid
273cab2bb3Spatrick // init-order-fiasco.
283cab2bb3Spatrick GuardedPoolAllocator *SingletonPtr = nullptr;
293cab2bb3Spatrick
roundUpTo(size_t Size,size_t Boundary)30d89ec533Spatrick size_t roundUpTo(size_t Size, size_t Boundary) {
31d89ec533Spatrick return (Size + Boundary - 1) & ~(Boundary - 1);
32d89ec533Spatrick }
333cab2bb3Spatrick
getPageAddr(uintptr_t Ptr,uintptr_t PageSize)34d89ec533Spatrick uintptr_t getPageAddr(uintptr_t Ptr, uintptr_t PageSize) {
35d89ec533Spatrick return Ptr & ~(PageSize - 1);
36d89ec533Spatrick }
37d89ec533Spatrick
isPowerOfTwo(uintptr_t X)38d89ec533Spatrick bool isPowerOfTwo(uintptr_t X) { return (X & (X - 1)) == 0; }
393cab2bb3Spatrick } // anonymous namespace
403cab2bb3Spatrick
413cab2bb3Spatrick // Gets the singleton implementation of this class. Thread-compatible until
423cab2bb3Spatrick // init() is called, thread-safe afterwards.
getSingleton()431f9cb04fSpatrick GuardedPoolAllocator *GuardedPoolAllocator::getSingleton() {
441f9cb04fSpatrick return SingletonPtr;
453cab2bb3Spatrick }
463cab2bb3Spatrick
init(const options::Options & Opts)473cab2bb3Spatrick void GuardedPoolAllocator::init(const options::Options &Opts) {
483cab2bb3Spatrick // Note: We return from the constructor here if GWP-ASan is not available.
493cab2bb3Spatrick // This will stop heap-allocation of class members, as well as mmap() of the
503cab2bb3Spatrick // guarded slots.
513cab2bb3Spatrick if (!Opts.Enabled || Opts.SampleRate == 0 ||
523cab2bb3Spatrick Opts.MaxSimultaneousAllocations == 0)
533cab2bb3Spatrick return;
543cab2bb3Spatrick
551f9cb04fSpatrick Check(Opts.SampleRate >= 0, "GWP-ASan Error: SampleRate is < 0.");
56d89ec533Spatrick Check(Opts.SampleRate < (1 << 30), "GWP-ASan Error: SampleRate is >= 2^30.");
571f9cb04fSpatrick Check(Opts.MaxSimultaneousAllocations >= 0,
581f9cb04fSpatrick "GWP-ASan Error: MaxSimultaneousAllocations is < 0.");
593cab2bb3Spatrick
603cab2bb3Spatrick SingletonPtr = this;
611f9cb04fSpatrick Backtrace = Opts.Backtrace;
623cab2bb3Spatrick
63*810390e3Srobert State.VersionMagic = {{AllocatorVersionMagic::kAllocatorVersionMagic[0],
64*810390e3Srobert AllocatorVersionMagic::kAllocatorVersionMagic[1],
65*810390e3Srobert AllocatorVersionMagic::kAllocatorVersionMagic[2],
66*810390e3Srobert AllocatorVersionMagic::kAllocatorVersionMagic[3]},
67*810390e3Srobert AllocatorVersionMagic::kAllocatorVersion,
68*810390e3Srobert 0};
69*810390e3Srobert
701f9cb04fSpatrick State.MaxSimultaneousAllocations = Opts.MaxSimultaneousAllocations;
713cab2bb3Spatrick
72d89ec533Spatrick const size_t PageSize = getPlatformPageSize();
73d89ec533Spatrick // getPageAddr() and roundUpTo() assume the page size to be a power of 2.
74d89ec533Spatrick assert((PageSize & (PageSize - 1)) == 0);
75d89ec533Spatrick State.PageSize = PageSize;
763cab2bb3Spatrick
77*810390e3Srobert // Number of pages required =
78*810390e3Srobert // + MaxSimultaneousAllocations * maximumAllocationSize (N pages per slot)
79*810390e3Srobert // + MaxSimultaneousAllocations (one guard on the left side of each slot)
80*810390e3Srobert // + 1 (an extra guard page at the end of the pool, on the right side)
81*810390e3Srobert // + 1 (an extra page that's used for reporting internally-detected crashes,
82*810390e3Srobert // like double free and invalid free, to the signal handler; see
83*810390e3Srobert // raiseInternallyDetectedError() for more info)
843cab2bb3Spatrick size_t PoolBytesRequired =
85*810390e3Srobert PageSize * (2 + State.MaxSimultaneousAllocations) +
861f9cb04fSpatrick State.MaxSimultaneousAllocations * State.maximumAllocationSize();
87d89ec533Spatrick assert(PoolBytesRequired % PageSize == 0);
88d89ec533Spatrick void *GuardedPoolMemory = reserveGuardedPool(PoolBytesRequired);
893cab2bb3Spatrick
90d89ec533Spatrick size_t BytesRequired =
91d89ec533Spatrick roundUpTo(State.MaxSimultaneousAllocations * sizeof(*Metadata), PageSize);
921f9cb04fSpatrick Metadata = reinterpret_cast<AllocationMetadata *>(
93d89ec533Spatrick map(BytesRequired, kGwpAsanMetadataName));
943cab2bb3Spatrick
953cab2bb3Spatrick // Allocate memory and set up the free pages queue.
96d89ec533Spatrick BytesRequired = roundUpTo(
97d89ec533Spatrick State.MaxSimultaneousAllocations * sizeof(*FreeSlots), PageSize);
98d89ec533Spatrick FreeSlots =
99d89ec533Spatrick reinterpret_cast<size_t *>(map(BytesRequired, kGwpAsanFreeSlotsName));
1003cab2bb3Spatrick
1013cab2bb3Spatrick // Multiply the sample rate by 2 to give a good, fast approximation for (1 /
1023cab2bb3Spatrick // SampleRate) chance of sampling.
1033cab2bb3Spatrick if (Opts.SampleRate != 1)
1041f9cb04fSpatrick AdjustedSampleRatePlusOne = static_cast<uint32_t>(Opts.SampleRate) * 2 + 1;
1053cab2bb3Spatrick else
1061f9cb04fSpatrick AdjustedSampleRatePlusOne = 2;
1073cab2bb3Spatrick
1081f9cb04fSpatrick initPRNG();
109d89ec533Spatrick getThreadLocals()->NextSampleCounter =
110d89ec533Spatrick ((getRandomUnsigned32() % (AdjustedSampleRatePlusOne - 1)) + 1) &
111d89ec533Spatrick ThreadLocalPackedVariables::NextSampleCounterMask;
1121f9cb04fSpatrick
1131f9cb04fSpatrick State.GuardedPagePool = reinterpret_cast<uintptr_t>(GuardedPoolMemory);
1141f9cb04fSpatrick State.GuardedPagePoolEnd =
1153cab2bb3Spatrick reinterpret_cast<uintptr_t>(GuardedPoolMemory) + PoolBytesRequired;
1163cab2bb3Spatrick
1171f9cb04fSpatrick if (Opts.InstallForkHandlers)
1181f9cb04fSpatrick installAtFork();
1191f9cb04fSpatrick }
1201f9cb04fSpatrick
disable()121d89ec533Spatrick void GuardedPoolAllocator::disable() {
122d89ec533Spatrick PoolMutex.lock();
123d89ec533Spatrick BacktraceMutex.lock();
124d89ec533Spatrick }
1251f9cb04fSpatrick
enable()126d89ec533Spatrick void GuardedPoolAllocator::enable() {
127d89ec533Spatrick PoolMutex.unlock();
128d89ec533Spatrick BacktraceMutex.unlock();
129d89ec533Spatrick }
1301f9cb04fSpatrick
iterate(void * Base,size_t Size,iterate_callback Cb,void * Arg)1311f9cb04fSpatrick void GuardedPoolAllocator::iterate(void *Base, size_t Size, iterate_callback Cb,
1321f9cb04fSpatrick void *Arg) {
1331f9cb04fSpatrick uintptr_t Start = reinterpret_cast<uintptr_t>(Base);
1341f9cb04fSpatrick for (size_t i = 0; i < State.MaxSimultaneousAllocations; ++i) {
1351f9cb04fSpatrick const AllocationMetadata &Meta = Metadata[i];
1361f9cb04fSpatrick if (Meta.Addr && !Meta.IsDeallocated && Meta.Addr >= Start &&
1371f9cb04fSpatrick Meta.Addr < Start + Size)
138d89ec533Spatrick Cb(Meta.Addr, Meta.RequestedSize, Arg);
1391f9cb04fSpatrick }
1401f9cb04fSpatrick }
1411f9cb04fSpatrick
uninitTestOnly()1421f9cb04fSpatrick void GuardedPoolAllocator::uninitTestOnly() {
1431f9cb04fSpatrick if (State.GuardedPagePool) {
144d89ec533Spatrick unreserveGuardedPool();
1451f9cb04fSpatrick State.GuardedPagePool = 0;
1461f9cb04fSpatrick State.GuardedPagePoolEnd = 0;
1471f9cb04fSpatrick }
1481f9cb04fSpatrick if (Metadata) {
149d89ec533Spatrick unmap(Metadata,
150d89ec533Spatrick roundUpTo(State.MaxSimultaneousAllocations * sizeof(*Metadata),
151d89ec533Spatrick State.PageSize));
1521f9cb04fSpatrick Metadata = nullptr;
1531f9cb04fSpatrick }
1541f9cb04fSpatrick if (FreeSlots) {
155d89ec533Spatrick unmap(FreeSlots,
156d89ec533Spatrick roundUpTo(State.MaxSimultaneousAllocations * sizeof(*FreeSlots),
157d89ec533Spatrick State.PageSize));
1581f9cb04fSpatrick FreeSlots = nullptr;
1591f9cb04fSpatrick }
160d89ec533Spatrick *getThreadLocals() = ThreadLocalPackedVariables();
1611f9cb04fSpatrick }
1621f9cb04fSpatrick
163d89ec533Spatrick // Note, minimum backing allocation size in GWP-ASan is always one page, and
164d89ec533Spatrick // each slot could potentially be multiple pages (but always in
165d89ec533Spatrick // page-increments). Thus, for anything that requires less than page size
166d89ec533Spatrick // alignment, we don't need to allocate extra padding to ensure the alignment
167d89ec533Spatrick // can be met.
getRequiredBackingSize(size_t Size,size_t Alignment,size_t PageSize)168d89ec533Spatrick size_t GuardedPoolAllocator::getRequiredBackingSize(size_t Size,
169d89ec533Spatrick size_t Alignment,
170d89ec533Spatrick size_t PageSize) {
171d89ec533Spatrick assert(isPowerOfTwo(Alignment) && "Alignment must be a power of two!");
172d89ec533Spatrick assert(Alignment != 0 && "Alignment should be non-zero");
173d89ec533Spatrick assert(Size != 0 && "Size should be non-zero");
174d89ec533Spatrick
175d89ec533Spatrick if (Alignment <= PageSize)
176d89ec533Spatrick return Size;
177d89ec533Spatrick
178d89ec533Spatrick return Size + Alignment - PageSize;
1793cab2bb3Spatrick }
1803cab2bb3Spatrick
alignUp(uintptr_t Ptr,size_t Alignment)181d89ec533Spatrick uintptr_t GuardedPoolAllocator::alignUp(uintptr_t Ptr, size_t Alignment) {
182d89ec533Spatrick assert(isPowerOfTwo(Alignment) && "Alignment must be a power of two!");
183d89ec533Spatrick assert(Alignment != 0 && "Alignment should be non-zero");
184d89ec533Spatrick if ((Ptr & (Alignment - 1)) == 0)
185d89ec533Spatrick return Ptr;
186d89ec533Spatrick
187d89ec533Spatrick Ptr += Alignment - (Ptr & (Alignment - 1));
188d89ec533Spatrick return Ptr;
189d89ec533Spatrick }
190d89ec533Spatrick
alignDown(uintptr_t Ptr,size_t Alignment)191d89ec533Spatrick uintptr_t GuardedPoolAllocator::alignDown(uintptr_t Ptr, size_t Alignment) {
192d89ec533Spatrick assert(isPowerOfTwo(Alignment) && "Alignment must be a power of two!");
193d89ec533Spatrick assert(Alignment != 0 && "Alignment should be non-zero");
194d89ec533Spatrick if ((Ptr & (Alignment - 1)) == 0)
195d89ec533Spatrick return Ptr;
196d89ec533Spatrick
197d89ec533Spatrick Ptr -= Ptr & (Alignment - 1);
198d89ec533Spatrick return Ptr;
199d89ec533Spatrick }
200d89ec533Spatrick
allocate(size_t Size,size_t Alignment)201d89ec533Spatrick void *GuardedPoolAllocator::allocate(size_t Size, size_t Alignment) {
2023cab2bb3Spatrick // GuardedPagePoolEnd == 0 when GWP-ASan is disabled. If we are disabled, fall
2033cab2bb3Spatrick // back to the supporting allocator.
204d89ec533Spatrick if (State.GuardedPagePoolEnd == 0) {
205d89ec533Spatrick getThreadLocals()->NextSampleCounter =
206d89ec533Spatrick (AdjustedSampleRatePlusOne - 1) &
207d89ec533Spatrick ThreadLocalPackedVariables::NextSampleCounterMask;
208d89ec533Spatrick return nullptr;
209d89ec533Spatrick }
210d89ec533Spatrick
211d89ec533Spatrick if (Size == 0)
212d89ec533Spatrick Size = 1;
213d89ec533Spatrick if (Alignment == 0)
214d89ec533Spatrick Alignment = alignof(max_align_t);
215d89ec533Spatrick
216d89ec533Spatrick if (!isPowerOfTwo(Alignment) || Alignment > State.maximumAllocationSize() ||
217d89ec533Spatrick Size > State.maximumAllocationSize())
218d89ec533Spatrick return nullptr;
219d89ec533Spatrick
220d89ec533Spatrick size_t BackingSize = getRequiredBackingSize(Size, Alignment, State.PageSize);
221d89ec533Spatrick if (BackingSize > State.maximumAllocationSize())
2223cab2bb3Spatrick return nullptr;
2233cab2bb3Spatrick
2243cab2bb3Spatrick // Protect against recursivity.
225d89ec533Spatrick if (getThreadLocals()->RecursiveGuard)
2263cab2bb3Spatrick return nullptr;
227d89ec533Spatrick ScopedRecursiveGuard SRG;
2283cab2bb3Spatrick
2293cab2bb3Spatrick size_t Index;
2303cab2bb3Spatrick {
2313cab2bb3Spatrick ScopedLock L(PoolMutex);
2323cab2bb3Spatrick Index = reserveSlot();
2333cab2bb3Spatrick }
2343cab2bb3Spatrick
2353cab2bb3Spatrick if (Index == kInvalidSlotID)
2363cab2bb3Spatrick return nullptr;
2373cab2bb3Spatrick
238d89ec533Spatrick uintptr_t SlotStart = State.slotToAddr(Index);
239d89ec533Spatrick AllocationMetadata *Meta = addrToMetadata(SlotStart);
240d89ec533Spatrick uintptr_t SlotEnd = State.slotToAddr(Index) + State.maximumAllocationSize();
241d89ec533Spatrick uintptr_t UserPtr;
242d89ec533Spatrick // Randomly choose whether to left-align or right-align the allocation, and
243d89ec533Spatrick // then apply the necessary adjustments to get an aligned pointer.
244d89ec533Spatrick if (getRandomUnsigned32() % 2 == 0)
245d89ec533Spatrick UserPtr = alignUp(SlotStart, Alignment);
246d89ec533Spatrick else
247d89ec533Spatrick UserPtr = alignDown(SlotEnd - Size, Alignment);
248d89ec533Spatrick
249d89ec533Spatrick assert(UserPtr >= SlotStart);
250d89ec533Spatrick assert(UserPtr + Size <= SlotEnd);
2513cab2bb3Spatrick
2523cab2bb3Spatrick // If a slot is multiple pages in size, and the allocation takes up a single
2533cab2bb3Spatrick // page, we can improve overflow detection by leaving the unused pages as
2543cab2bb3Spatrick // unmapped.
255d89ec533Spatrick const size_t PageSize = State.PageSize;
256d89ec533Spatrick allocateInGuardedPool(
257d89ec533Spatrick reinterpret_cast<void *>(getPageAddr(UserPtr, PageSize)),
258d89ec533Spatrick roundUpTo(Size, PageSize));
2593cab2bb3Spatrick
260d89ec533Spatrick Meta->RecordAllocation(UserPtr, Size);
261d89ec533Spatrick {
262d89ec533Spatrick ScopedLock UL(BacktraceMutex);
2631f9cb04fSpatrick Meta->AllocationTrace.RecordBacktrace(Backtrace);
264d89ec533Spatrick }
2653cab2bb3Spatrick
266d89ec533Spatrick return reinterpret_cast<void *>(UserPtr);
2673cab2bb3Spatrick }
2683cab2bb3Spatrick
raiseInternallyDetectedError(uintptr_t Address,Error E)269*810390e3Srobert void GuardedPoolAllocator::raiseInternallyDetectedError(uintptr_t Address,
270*810390e3Srobert Error E) {
271*810390e3Srobert // Disable the allocator before setting the internal failure state. In
272*810390e3Srobert // non-recoverable mode, the allocator will be permanently disabled, and so
273*810390e3Srobert // things will be accessed without locks.
274*810390e3Srobert disable();
275*810390e3Srobert
276*810390e3Srobert // Races between internally- and externally-raised faults can happen. Right
277*810390e3Srobert // now, in this thread we've locked the allocator in order to raise an
278*810390e3Srobert // internally-detected fault, and another thread could SIGSEGV to raise an
279*810390e3Srobert // externally-detected fault. What will happen is that the other thread will
280*810390e3Srobert // wait in the signal handler, as we hold the allocator's locks from the
281*810390e3Srobert // disable() above. We'll trigger the signal handler by touching the
282*810390e3Srobert // internal-signal-raising address below, and the signal handler from our
283*810390e3Srobert // thread will get to run first as we will continue to hold the allocator
284*810390e3Srobert // locks until the enable() at the end of this function. Be careful though, if
285*810390e3Srobert // this thread receives another SIGSEGV after the disable() above, but before
286*810390e3Srobert // touching the internal-signal-raising address below, then this thread will
287*810390e3Srobert // get an "externally-raised" SIGSEGV while *also* holding the allocator
288*810390e3Srobert // locks, which means this thread's signal handler will deadlock. This could
289*810390e3Srobert // be resolved with a re-entrant lock, but asking platforms to implement this
290*810390e3Srobert // seems unnecessary given the only way to get a SIGSEGV in this critical
291*810390e3Srobert // section is either a memory safety bug in the couple lines of code below (be
292*810390e3Srobert // careful!), or someone outside uses `kill(this_thread, SIGSEGV)`, which
293*810390e3Srobert // really shouldn't happen.
294*810390e3Srobert
2951f9cb04fSpatrick State.FailureType = E;
2961f9cb04fSpatrick State.FailureAddress = Address;
2971f9cb04fSpatrick
298*810390e3Srobert // Raise a SEGV by touching a specific address that identifies to the crash
299*810390e3Srobert // handler that this is an internally-raised fault. Changing this address?
300*810390e3Srobert // Don't forget to update __gwp_asan_get_internal_crash_address.
301*810390e3Srobert volatile char *p =
302*810390e3Srobert reinterpret_cast<char *>(State.internallyDetectedErrorFaultAddress());
3031f9cb04fSpatrick *p = 0;
3041f9cb04fSpatrick
305*810390e3Srobert // This should never be reached in non-recoverable mode. Ensure that the
306*810390e3Srobert // signal handler called handleRecoverablePostCrashReport(), which was
307*810390e3Srobert // responsible for re-setting these fields.
308*810390e3Srobert assert(State.FailureType == Error::UNKNOWN);
309*810390e3Srobert assert(State.FailureAddress == 0u);
310*810390e3Srobert
311*810390e3Srobert // In recoverable mode, the signal handler (after dumping the crash) marked
312*810390e3Srobert // the page containing the InternalFaultSegvAddress as read/writeable, to
313*810390e3Srobert // allow the second touch to succeed after returning from the signal handler.
314*810390e3Srobert // Now, we need to mark the page as non-read/write-able again, so future
315*810390e3Srobert // internal faults can be raised.
316*810390e3Srobert deallocateInGuardedPool(
317*810390e3Srobert reinterpret_cast<void *>(getPageAddr(
318*810390e3Srobert State.internallyDetectedErrorFaultAddress(), State.PageSize)),
319*810390e3Srobert State.PageSize);
320*810390e3Srobert
321*810390e3Srobert // And now we're done with patching ourselves back up, enable the allocator.
322*810390e3Srobert enable();
3231f9cb04fSpatrick }
3241f9cb04fSpatrick
deallocate(void * Ptr)3253cab2bb3Spatrick void GuardedPoolAllocator::deallocate(void *Ptr) {
3263cab2bb3Spatrick assert(pointerIsMine(Ptr) && "Pointer is not mine!");
3273cab2bb3Spatrick uintptr_t UPtr = reinterpret_cast<uintptr_t>(Ptr);
3281f9cb04fSpatrick size_t Slot = State.getNearestSlot(UPtr);
3291f9cb04fSpatrick uintptr_t SlotStart = State.slotToAddr(Slot);
3303cab2bb3Spatrick AllocationMetadata *Meta = addrToMetadata(UPtr);
331*810390e3Srobert
332*810390e3Srobert // If this allocation is responsible for crash, never recycle it. Turn the
333*810390e3Srobert // deallocate() call into a no-op.
334*810390e3Srobert if (Meta->HasCrashed)
335*810390e3Srobert return;
336*810390e3Srobert
3373cab2bb3Spatrick if (Meta->Addr != UPtr) {
338*810390e3Srobert raiseInternallyDetectedError(UPtr, Error::INVALID_FREE);
339*810390e3Srobert return;
340*810390e3Srobert }
341*810390e3Srobert if (Meta->IsDeallocated) {
342*810390e3Srobert raiseInternallyDetectedError(UPtr, Error::DOUBLE_FREE);
343*810390e3Srobert return;
3443cab2bb3Spatrick }
3453cab2bb3Spatrick
3463cab2bb3Spatrick // Intentionally scope the mutex here, so that other threads can access the
3473cab2bb3Spatrick // pool during the expensive markInaccessible() call.
3483cab2bb3Spatrick {
3493cab2bb3Spatrick ScopedLock L(PoolMutex);
3503cab2bb3Spatrick
3513cab2bb3Spatrick // Ensure that the deallocation is recorded before marking the page as
3523cab2bb3Spatrick // inaccessible. Otherwise, a racy use-after-free will have inconsistent
3533cab2bb3Spatrick // metadata.
3541f9cb04fSpatrick Meta->RecordDeallocation();
3551f9cb04fSpatrick
3561f9cb04fSpatrick // Ensure that the unwinder is not called if the recursive flag is set,
3571f9cb04fSpatrick // otherwise non-reentrant unwinders may deadlock.
358d89ec533Spatrick if (!getThreadLocals()->RecursiveGuard) {
359d89ec533Spatrick ScopedRecursiveGuard SRG;
360d89ec533Spatrick ScopedLock UL(BacktraceMutex);
3611f9cb04fSpatrick Meta->DeallocationTrace.RecordBacktrace(Backtrace);
3621f9cb04fSpatrick }
3633cab2bb3Spatrick }
3643cab2bb3Spatrick
365d89ec533Spatrick deallocateInGuardedPool(reinterpret_cast<void *>(SlotStart),
366d89ec533Spatrick State.maximumAllocationSize());
3673cab2bb3Spatrick
3683cab2bb3Spatrick // And finally, lock again to release the slot back into the pool.
3693cab2bb3Spatrick ScopedLock L(PoolMutex);
3701f9cb04fSpatrick freeSlot(Slot);
3713cab2bb3Spatrick }
3723cab2bb3Spatrick
373*810390e3Srobert // Thread-compatible, protected by PoolMutex.
374*810390e3Srobert static bool PreviousRecursiveGuard;
375*810390e3Srobert
preCrashReport(void * Ptr)376*810390e3Srobert void GuardedPoolAllocator::preCrashReport(void *Ptr) {
377*810390e3Srobert assert(pointerIsMine(Ptr) && "Pointer is not mine!");
378*810390e3Srobert uintptr_t InternalCrashAddr = __gwp_asan_get_internal_crash_address(
379*810390e3Srobert &State, reinterpret_cast<uintptr_t>(Ptr));
380*810390e3Srobert if (!InternalCrashAddr)
381*810390e3Srobert disable();
382*810390e3Srobert
383*810390e3Srobert // If something in the signal handler calls malloc() while dumping the
384*810390e3Srobert // GWP-ASan report (e.g. backtrace_symbols()), make sure that GWP-ASan doesn't
385*810390e3Srobert // service that allocation. `PreviousRecursiveGuard` is protected by the
386*810390e3Srobert // allocator locks taken in disable(), either explicitly above for
387*810390e3Srobert // externally-raised errors, or implicitly in raiseInternallyDetectedError()
388*810390e3Srobert // for internally-detected errors.
389*810390e3Srobert PreviousRecursiveGuard = getThreadLocals()->RecursiveGuard;
390*810390e3Srobert getThreadLocals()->RecursiveGuard = true;
391*810390e3Srobert }
392*810390e3Srobert
postCrashReportRecoverableOnly(void * SignalPtr)393*810390e3Srobert void GuardedPoolAllocator::postCrashReportRecoverableOnly(void *SignalPtr) {
394*810390e3Srobert uintptr_t SignalUPtr = reinterpret_cast<uintptr_t>(SignalPtr);
395*810390e3Srobert uintptr_t InternalCrashAddr =
396*810390e3Srobert __gwp_asan_get_internal_crash_address(&State, SignalUPtr);
397*810390e3Srobert uintptr_t ErrorUptr = InternalCrashAddr ?: SignalUPtr;
398*810390e3Srobert
399*810390e3Srobert AllocationMetadata *Metadata = addrToMetadata(ErrorUptr);
400*810390e3Srobert Metadata->HasCrashed = true;
401*810390e3Srobert
402*810390e3Srobert allocateInGuardedPool(
403*810390e3Srobert reinterpret_cast<void *>(getPageAddr(SignalUPtr, State.PageSize)),
404*810390e3Srobert State.PageSize);
405*810390e3Srobert
406*810390e3Srobert // Clear the internal state in order to not confuse the crash handler if a
407*810390e3Srobert // use-after-free or buffer-overflow comes from a different allocation in the
408*810390e3Srobert // future.
409*810390e3Srobert if (InternalCrashAddr) {
410*810390e3Srobert State.FailureType = Error::UNKNOWN;
411*810390e3Srobert State.FailureAddress = 0;
412*810390e3Srobert }
413*810390e3Srobert
414*810390e3Srobert size_t Slot = State.getNearestSlot(ErrorUptr);
415*810390e3Srobert // If the slot is available, remove it permanently.
416*810390e3Srobert for (size_t i = 0; i < FreeSlotsLength; ++i) {
417*810390e3Srobert if (FreeSlots[i] == Slot) {
418*810390e3Srobert FreeSlots[i] = FreeSlots[FreeSlotsLength - 1];
419*810390e3Srobert FreeSlotsLength -= 1;
420*810390e3Srobert break;
421*810390e3Srobert }
422*810390e3Srobert }
423*810390e3Srobert
424*810390e3Srobert getThreadLocals()->RecursiveGuard = PreviousRecursiveGuard;
425*810390e3Srobert if (!InternalCrashAddr)
426*810390e3Srobert enable();
427*810390e3Srobert }
428*810390e3Srobert
getSize(const void * Ptr)4293cab2bb3Spatrick size_t GuardedPoolAllocator::getSize(const void *Ptr) {
4303cab2bb3Spatrick assert(pointerIsMine(Ptr));
4313cab2bb3Spatrick ScopedLock L(PoolMutex);
4323cab2bb3Spatrick AllocationMetadata *Meta = addrToMetadata(reinterpret_cast<uintptr_t>(Ptr));
4333cab2bb3Spatrick assert(Meta->Addr == reinterpret_cast<uintptr_t>(Ptr));
434d89ec533Spatrick return Meta->RequestedSize;
4353cab2bb3Spatrick }
4363cab2bb3Spatrick
addrToMetadata(uintptr_t Ptr) const4373cab2bb3Spatrick AllocationMetadata *GuardedPoolAllocator::addrToMetadata(uintptr_t Ptr) const {
4381f9cb04fSpatrick return &Metadata[State.getNearestSlot(Ptr)];
4393cab2bb3Spatrick }
4403cab2bb3Spatrick
reserveSlot()4413cab2bb3Spatrick size_t GuardedPoolAllocator::reserveSlot() {
4423cab2bb3Spatrick // Avoid potential reuse of a slot before we have made at least a single
4433cab2bb3Spatrick // allocation in each slot. Helps with our use-after-free detection.
4441f9cb04fSpatrick if (NumSampledAllocations < State.MaxSimultaneousAllocations)
4453cab2bb3Spatrick return NumSampledAllocations++;
4463cab2bb3Spatrick
4473cab2bb3Spatrick if (FreeSlotsLength == 0)
4483cab2bb3Spatrick return kInvalidSlotID;
4493cab2bb3Spatrick
4503cab2bb3Spatrick size_t ReservedIndex = getRandomUnsigned32() % FreeSlotsLength;
4513cab2bb3Spatrick size_t SlotIndex = FreeSlots[ReservedIndex];
4523cab2bb3Spatrick FreeSlots[ReservedIndex] = FreeSlots[--FreeSlotsLength];
4533cab2bb3Spatrick return SlotIndex;
4543cab2bb3Spatrick }
4553cab2bb3Spatrick
freeSlot(size_t SlotIndex)4563cab2bb3Spatrick void GuardedPoolAllocator::freeSlot(size_t SlotIndex) {
4571f9cb04fSpatrick assert(FreeSlotsLength < State.MaxSimultaneousAllocations);
4583cab2bb3Spatrick FreeSlots[FreeSlotsLength++] = SlotIndex;
4593cab2bb3Spatrick }
4603cab2bb3Spatrick
getRandomUnsigned32()461d89ec533Spatrick uint32_t GuardedPoolAllocator::getRandomUnsigned32() {
462d89ec533Spatrick uint32_t RandomState = getThreadLocals()->RandomState;
463d89ec533Spatrick RandomState ^= RandomState << 13;
464d89ec533Spatrick RandomState ^= RandomState >> 17;
465d89ec533Spatrick RandomState ^= RandomState << 5;
466d89ec533Spatrick getThreadLocals()->RandomState = RandomState;
467d89ec533Spatrick return RandomState;
468d89ec533Spatrick }
4693cab2bb3Spatrick } // namespace gwp_asan
470