Last active
August 29, 2015 14:23
-
-
Save lethosor/a52112b23fe13849a134 to your computer and use it in GitHub Desktop.
OS X MALLOC_PERTURB_ implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <dlfcn.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int main() { | |
typedef unsigned char uint; | |
size_t size = 5; | |
uint *s = (uint*)malloc(size * sizeof(uint)); | |
for (int i = 0; i < size; i++) | |
printf("%02x ", s[i]); | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment