malloc插桩
1、编译时打桩
main.cpp
#include "hook.h" using namespace std; #define malloc(size) hookMalloc(size) int main() { printf("%d\n", __cplusplus); void *ptr = malloc(sizeof(char)); printf("ptr = %p\n", ptr); return 0; }
hook.h
#include <stdio.h> #include <stdlib.h> void *hookMalloc(size_t size) { printf("%s size = %d\n", __FUNCTION__, size); return malloc(size); }
编译命令
g++ main.cpp -o main.o
注意事项
1、替换的宏定义在 main.cpp 中,不对 hook.h 中的 malloc 做替换
2、链接时打桩
main.cpp
#include <stdio.h> #include <stdlib.h> using namespace std; extern "C" { void *__real_malloc(size_t); void *__wrap_malloc(size_t size); } void *__wrap_malloc(size_t size) { printf("%s size = %d\n", __FUNCTION__, size); return __real_malloc(size); } int main() { printf("%d\n", __cplusplus); void *ptr = malloc(sizeof(char)); printf("ptr = %p\n", ptr); return 0; }
编译命令
g++ main.cpp -Wl,--wrap=malloc -o main.o
注意事项
1、__real_malloc 和 __wrap_malloc 需要使用 extern "C" 修饰,因为 gcc 和 g++ 的函数重命名规则不一样(详见《程序员的自我修养--编译、链接和装载》)
3、运行时打桩
main.cpp
#include <stdio.h> #include <stdlib.h> using namespace std; int main() { void *ptr = malloc(sizeof(char)); // printf 会再调用一次 malloc printf("ptr = %p\n", ptr); return 0; }
hook.cpp
#include <stdio.h> #include <stdlib.h> #include <dlfcn.h> using namespace std; void *malloc(size_t size) { fputs("hook.cpp malloc\n", stderr); typedef void *(*funcPtr)(size_t); funcPtr pmalloc = NULL; pmalloc = (funcPtr)dlsym(RTLD_NEXT, "malloc"); if (pmalloc == NULL) { fputs("pmalloc is NULL\n", stderr); return NULL; } return pmalloc(size); }
编译命令
g++ hook.cpp -fpic -shared -g -ldl -o libhook.so g++ main.cpp -g -L -l ./libhook.so -o main.o LD_PRELOAD="./libhook.so" ./main.o
注意事项
1、malloc 函数中不能使用 printf,printf 会调用 malloc,使用 fputs 做替代 2、fputs 不能输出到 stdout,只能输出到 stderr,输出到 stdout 会调用 malloc
参考