Skip to content

Instantly share code, notes, and snippets.

@christianparpart
Created May 24, 2012 18:06
Show Gist options
  • Save christianparpart/2783169 to your computer and use it in GitHub Desktop.
Save christianparpart/2783169 to your computer and use it in GitHub Desktop.
Monkey-Patching in C/C++ :-)
// compile me: g++ -shared -fPIC -ldl -o monkeypatchor.so monkeypatchor.cpp
// use me: LD_PRELOAD=`pwd`/monkeypatchor.so /bin/ls
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
void* (*malloc_super)(size_t);
void (*free_super)(void*);
__attribute__((constructor))
void my_init() {
printf("Monkey-patching into malloc() and free()\n");
malloc_super = (void* (*)(size_t)) dlsym(RTLD_NEXT, "malloc");
free_super = (void (*)(void*)) dlsym(RTLD_NEXT, "free");
}
void* malloc(size_t n) {
void *result = malloc_super(n);
if (result) {
printf("Protected addr space: %p\n", result);
mlock(result, n);
}
return result;
}
void free(void *p) {
//munlock(p);
free_super(p);
}
@omegacoleman
Copy link

thanks! you're a life saver

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment