#include "gwp_asan/guarded_pool_allocator.h"
#include "gwp_asan/crash_handler.h"
#include "gwp_asan/options.h"
#include "gwp_asan/utilities.h"
#include <assert.h>
#include <stddef.h>
using AllocationMetadata = gwp_asan::AllocationMetadata;
using Error = gwp_asan::Error;
namespace gwp_asan {
namespace {
GuardedPoolAllocator *SingletonPtr = nullptr;
size_t roundUpTo(size_t Size, size_t Boundary) {
return (Size + Boundary - 1) & ~(Boundary - 1);
}
uintptr_t getPageAddr(uintptr_t Ptr, uintptr_t PageSize) {
return Ptr & ~(PageSize - 1);
}
bool isPowerOfTwo(uintptr_t X) { return (X & (X - 1)) == 0; }
}
GuardedPoolAllocator *GuardedPoolAllocator::getSingleton() {
return SingletonPtr;
}
void GuardedPoolAllocator::init(const options::Options &Opts) {
if (!Opts.Enabled || Opts.SampleRate == 0 ||
Opts.MaxSimultaneousAllocations == 0)
return;
check(Opts.SampleRate >= 0, "GWP-ASan Error: SampleRate is < 0.");
check(Opts.SampleRate < (1 << 30), "GWP-ASan Error: SampleRate is >= 2^30.");
check(Opts.MaxSimultaneousAllocations >= 0,
"GWP-ASan Error: MaxSimultaneousAllocations is < 0.");
check(SingletonPtr == nullptr,
"There's already a live GuardedPoolAllocator!");
SingletonPtr = this;
Backtrace = Opts.Backtrace;
State.VersionMagic = {{AllocatorVersionMagic::kAllocatorVersionMagic[0],
AllocatorVersionMagic::kAllocatorVersionMagic[1],
AllocatorVersionMagic::kAllocatorVersionMagic[2],
AllocatorVersionMagic::kAllocatorVersionMagic[3]},
AllocatorVersionMagic::kAllocatorVersion,
0};
State.MaxSimultaneousAllocations = Opts.MaxSimultaneousAllocations;
const size_t PageSize = getPlatformPageSize();
assert((PageSize & (PageSize - 1)) == 0);
State.PageSize = PageSize;
size_t PoolBytesRequired =
PageSize * (2 + State.MaxSimultaneousAllocations) +
State.MaxSimultaneousAllocations * State.maximumAllocationSize();
assert(PoolBytesRequired % PageSize == 0);
void *GuardedPoolMemory = reserveGuardedPool(PoolBytesRequired);
size_t BytesRequired =
roundUpTo(State.MaxSimultaneousAllocations * sizeof(*Metadata), PageSize);
Metadata = reinterpret_cast<AllocationMetadata *>(
map(BytesRequired, kGwpAsanMetadataName));
BytesRequired = roundUpTo(
State.MaxSimultaneousAllocations * sizeof(*FreeSlots), PageSize);
FreeSlots =
reinterpret_cast<size_t *>(map(BytesRequired, kGwpAsanFreeSlotsName));
if (Opts.SampleRate != 1)
AdjustedSampleRatePlusOne = static_cast<uint32_t>(Opts.SampleRate) * 2 + 1;
else
AdjustedSampleRatePlusOne = 2;
initPRNG();
getThreadLocals()->NextSampleCounter =
((getRandomUnsigned32() % (AdjustedSampleRatePlusOne - 1)) + 1) &
ThreadLocalPackedVariables::NextSampleCounterMask;
State.GuardedPagePool = reinterpret_cast<uintptr_t>(GuardedPoolMemory);
State.GuardedPagePoolEnd =
reinterpret_cast<uintptr_t>(GuardedPoolMemory) + PoolBytesRequired;
if (Opts.InstallForkHandlers)
installAtFork();
}
void GuardedPoolAllocator::disable() {
PoolMutex.lock();
BacktraceMutex.lock();
}
void GuardedPoolAllocator::enable() {
PoolMutex.unlock();
BacktraceMutex.unlock();
}
void GuardedPoolAllocator::iterate(void *Base, size_t Size, iterate_callback Cb,
void *Arg) {
uintptr_t Start = reinterpret_cast<uintptr_t>(Base);
for (size_t i = 0; i < State.MaxSimultaneousAllocations; ++i) {
const AllocationMetadata &Meta = Metadata[i];
if (Meta.Addr && !Meta.IsDeallocated && Meta.Addr >= Start &&
Meta.Addr < Start + Size)
Cb(Meta.Addr, Meta.RequestedSize, Arg);
}
}
void GuardedPoolAllocator::uninitTestOnly() {
if (State.GuardedPagePool) {
unreserveGuardedPool();
State.GuardedPagePool = 0;
State.GuardedPagePoolEnd = 0;
}
if (Metadata) {
unmap(Metadata,
roundUpTo(State.MaxSimultaneousAllocations * sizeof(*Metadata),
State.PageSize));
Metadata = nullptr;
}
if (FreeSlots) {
unmap(FreeSlots,
roundUpTo(State.MaxSimultaneousAllocations * sizeof(*FreeSlots),
State.PageSize));
FreeSlots = nullptr;
}
*getThreadLocals() = ThreadLocalPackedVariables();
SingletonPtr = nullptr;
}
size_t GuardedPoolAllocator::getRequiredBackingSize(size_t Size,
size_t Alignment,
size_t PageSize) {
assert(isPowerOfTwo(Alignment) && "Alignment must be a power of two!");
assert(Alignment != 0 && "Alignment should be non-zero");
assert(Size != 0 && "Size should be non-zero");
if (Alignment <= PageSize)
return Size;
return Size + Alignment - PageSize;
}
uintptr_t GuardedPoolAllocator::alignUp(uintptr_t Ptr, size_t Alignment) {
assert(isPowerOfTwo(Alignment) && "Alignment must be a power of two!");
assert(Alignment != 0 && "Alignment should be non-zero");
if ((Ptr & (Alignment - 1)) == 0)
return Ptr;
Ptr += Alignment - (Ptr & (Alignment - 1));
return Ptr;
}
uintptr_t GuardedPoolAllocator::alignDown(uintptr_t Ptr, size_t Alignment) {
assert(isPowerOfTwo(Alignment) && "Alignment must be a power of two!");
assert(Alignment != 0 && "Alignment should be non-zero");
if ((Ptr & (Alignment - 1)) == 0)
return Ptr;
Ptr -= Ptr & (Alignment - 1);
return Ptr;
}
void *GuardedPoolAllocator::allocate(size_t Size, size_t Alignment) {
if (State.GuardedPagePoolEnd == 0) {
getThreadLocals()->NextSampleCounter =
(AdjustedSampleRatePlusOne - 1) &
ThreadLocalPackedVariables::NextSampleCounterMask;
return nullptr;
}
if (Size == 0)
Size = 1;
if (Alignment == 0)
Alignment = alignof(max_align_t);
if (!isPowerOfTwo(Alignment) || Alignment > State.maximumAllocationSize() ||
Size > State.maximumAllocationSize())
return nullptr;
size_t BackingSize = getRequiredBackingSize(Size, Alignment, State.PageSize);
if (BackingSize > State.maximumAllocationSize())
return nullptr;
if (getThreadLocals()->RecursiveGuard)
return nullptr;
ScopedRecursiveGuard SRG;
size_t Index;
{
ScopedLock L(PoolMutex);
Index = reserveSlot();
}
if (Index == kInvalidSlotID)
return nullptr;
uintptr_t SlotStart = State.slotToAddr(Index);
AllocationMetadata *Meta = addrToMetadata(SlotStart);
uintptr_t SlotEnd = State.slotToAddr(Index) + State.maximumAllocationSize();
uintptr_t UserPtr;
if (getRandomUnsigned32() % 2 == 0)
UserPtr = alignUp(SlotStart, Alignment);
else
UserPtr = alignDown(SlotEnd - Size, Alignment);
assert(UserPtr >= SlotStart);
assert(UserPtr + Size <= SlotEnd);
const size_t PageSize = State.PageSize;
allocateInGuardedPool(
reinterpret_cast<void *>(getPageAddr(UserPtr, PageSize)),
roundUpTo(Size, PageSize));
Meta->RecordAllocation(UserPtr, Size);
{
ScopedLock UL(BacktraceMutex);
Meta->AllocationTrace.RecordBacktrace(Backtrace);
}
return reinterpret_cast<void *>(UserPtr);
}
void GuardedPoolAllocator::raiseInternallyDetectedError(uintptr_t Address,
Error E) {
disable();
State.FailureType = E;
State.FailureAddress = Address;
volatile char *p =
reinterpret_cast<char *>(State.internallyDetectedErrorFaultAddress());
*p = 0;
assert(State.FailureType == Error::UNKNOWN);
assert(State.FailureAddress == 0u);
deallocateInGuardedPool(
reinterpret_cast<void *>(getPageAddr(
State.internallyDetectedErrorFaultAddress(), State.PageSize)),
State.PageSize);
enable();
}
void GuardedPoolAllocator::deallocate(void *Ptr) {
assert(pointerIsMine(Ptr) && "Pointer is not mine!");
uintptr_t UPtr = reinterpret_cast<uintptr_t>(Ptr);
size_t Slot = State.getNearestSlot(UPtr);
uintptr_t SlotStart = State.slotToAddr(Slot);
AllocationMetadata *Meta = addrToMetadata(UPtr);
if (Meta->HasCrashed)
return;
if (Meta->Addr != UPtr) {
raiseInternallyDetectedError(UPtr, Error::INVALID_FREE);
return;
}
if (Meta->IsDeallocated) {
raiseInternallyDetectedError(UPtr, Error::DOUBLE_FREE);
return;
}
{
ScopedLock L(PoolMutex);
Meta->RecordDeallocation();
if (!getThreadLocals()->RecursiveGuard) {
ScopedRecursiveGuard SRG;
ScopedLock UL(BacktraceMutex);
Meta->DeallocationTrace.RecordBacktrace(Backtrace);
}
}
deallocateInGuardedPool(reinterpret_cast<void *>(SlotStart),
State.maximumAllocationSize());
ScopedLock L(PoolMutex);
freeSlot(Slot);
}
static bool PreviousRecursiveGuard;
void GuardedPoolAllocator::preCrashReport(void *Ptr) {
assert(pointerIsMine(Ptr) && "Pointer is not mine!");
uintptr_t InternalCrashAddr = __gwp_asan_get_internal_crash_address(
&State, reinterpret_cast<uintptr_t>(Ptr));
if (!InternalCrashAddr)
disable();
PreviousRecursiveGuard = getThreadLocals()->RecursiveGuard;
getThreadLocals()->RecursiveGuard = true;
}
void GuardedPoolAllocator::postCrashReportRecoverableOnly(void *SignalPtr) {
uintptr_t SignalUPtr = reinterpret_cast<uintptr_t>(SignalPtr);
uintptr_t InternalCrashAddr =
__gwp_asan_get_internal_crash_address(&State, SignalUPtr);
uintptr_t ErrorUptr = InternalCrashAddr ?: SignalUPtr;
AllocationMetadata *Metadata = addrToMetadata(ErrorUptr);
Metadata->HasCrashed = true;
allocateInGuardedPool(
reinterpret_cast<void *>(getPageAddr(SignalUPtr, State.PageSize)),
State.PageSize);
if (InternalCrashAddr) {
State.FailureType = Error::UNKNOWN;
State.FailureAddress = 0;
}
size_t Slot = State.getNearestSlot(ErrorUptr);
for (size_t i = 0; i < FreeSlotsLength; ++i) {
if (FreeSlots[i] == Slot) {
FreeSlots[i] = FreeSlots[FreeSlotsLength - 1];
FreeSlotsLength -= 1;
break;
}
}
getThreadLocals()->RecursiveGuard = PreviousRecursiveGuard;
if (!InternalCrashAddr)
enable();
}
size_t GuardedPoolAllocator::getSize(const void *Ptr) {
assert(pointerIsMine(Ptr));
ScopedLock L(PoolMutex);
AllocationMetadata *Meta = addrToMetadata(reinterpret_cast<uintptr_t>(Ptr));
assert(Meta->Addr == reinterpret_cast<uintptr_t>(Ptr));
return Meta->RequestedSize;
}
AllocationMetadata *GuardedPoolAllocator::addrToMetadata(uintptr_t Ptr) const {
return &Metadata[State.getNearestSlot(Ptr)];
}
size_t GuardedPoolAllocator::reserveSlot() {
if (NumSampledAllocations < State.MaxSimultaneousAllocations)
return NumSampledAllocations++;
if (FreeSlotsLength == 0)
return kInvalidSlotID;
size_t ReservedIndex = getRandomUnsigned32() % FreeSlotsLength;
size_t SlotIndex = FreeSlots[ReservedIndex];
FreeSlots[ReservedIndex] = FreeSlots[--FreeSlotsLength];
return SlotIndex;
}
void GuardedPoolAllocator::freeSlot(size_t SlotIndex) {
assert(FreeSlotsLength < State.MaxSimultaneousAllocations);
FreeSlots[FreeSlotsLength++] = SlotIndex;
}
uint32_t GuardedPoolAllocator::getRandomUnsigned32() {
uint32_t RandomState = getThreadLocals()->RandomState;
RandomState ^= RandomState << 13;
RandomState ^= RandomState >> 17;
RandomState ^= RandomState << 5;
getThreadLocals()->RandomState = RandomState;
return RandomState;
}
}