From 0ec12657f46b28ab427490de3d6fd7ac4a63d93a Mon Sep 17 00:00:00 2001 From: lethosor Date: Tue, 18 Feb 2020 00:31:49 -0500 Subject: [PATCH] sizecheck: add MALLOC_PERTURB_ support on non-Linux --- depends/sizecheck/sizecheck.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/depends/sizecheck/sizecheck.cpp b/depends/sizecheck/sizecheck.cpp index 5bb5a665c..6366edd68 100644 --- a/depends/sizecheck/sizecheck.cpp +++ b/depends/sizecheck/sizecheck.cpp @@ -11,8 +11,22 @@ using namespace std; const uint32_t MAGIC = 0xdfdf4ac8; +bool initialized = false; +int perturb = -1; + +void init() { +#ifndef _LINUX + if (getenv("MALLOC_PERTURB_")) { + perturb = atoi(getenv("MALLOC_PERTURB_")); + } +#endif + initialized = true; +} void* alloc(size_t n) { + if (!initialized) { + init(); + } void* addr; if (posix_memalign(&addr, 32, n + 16) != 0) { return addr; @@ -20,12 +34,19 @@ void* alloc(size_t n) { memset(addr, 0, 16); *(size_t*)addr = n; *(uint32_t*)((uint8_t*)addr + 8) = MAGIC; + if (perturb > 0) { + memset((uint8_t*)addr + 16, ~(perturb & 0xff), n); + } return (uint8_t*)addr + 16; } void dealloc(void* addr) { + if (!initialized) { + init(); + } if (uintptr_t(addr) % 32 == 16 && *(uint32_t*)((uint8_t*)addr - 8) == MAGIC) { addr = (void*)((uint8_t*)addr - 16); + memset((uint8_t*)addr + 16, perturb & 0xff, *(size_t*)addr); } free(addr); }