#include #include #include #include #include #include #ifdef __APPLE__ #define LIBC "libc.dylib" #else #define LIBC "libc.so" #endif const char *libc_err = "Could not load " LIBC "\n"; static void*(*malloc_orig)(size_t); bool perturb = false; uint8_t perturb_byte = 0; void init() { static void *handle = 0; if (!handle) handle = dlopen(LIBC, RTLD_LOCAL); if (!handle) { write(STDERR_FILENO, libc_err, strlen(libc_err)); abort(); } *(void**)&malloc_orig = dlsym(handle, "malloc"); const char *s = getenv("MALLOC_PERTURB_"); if (s) { perturb = true; perturb_byte = atoi(s) % 256; } } #ifdef __cplusplus extern "C" #endif void *malloc(size_t size) { if (!malloc_orig) init(); void *ptr = malloc_orig(size); if (perturb) memset(ptr, perturb_byte, size); return ptr; }