#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
typedef void *(*malloc_t)(size_t size);
malloc_t malloc_f = NULL;
typedef void (*free_t)(void* p);
free_t free_f = NULL;
//定义一个hook函数的标志 使内部逻辑只执行一次
int enable_malloc_hook = 1;
int enable_free_hook = 1;
//要hook的同名函数
void * malloc(size_t size)
{
if(enable_malloc_hook) //对第三方调用导致的递归进行规避
{
enable_malloc_hook = 0;
printf("exec malloc \n");
enable_malloc_hook = 1;
}
return malloc_f(size);
}
void free(void * p){
if(enable_free_hook)
{
enable_free_hook = 0;
printf("exec free \n");
enable_free_hook = 1;
}
free_f(p);
}
//通过dlsym 对malloc和free使用前进行hook
static void init_malloc_free_hook()
{
//只需要执行一次
if(malloc_f == NULL)
{
malloc_f = dlsym(RTLD_NEXT, "malloc"); //除了RTLD_NEXT 还有一个参数RTLD_DEFAULT
}
if(free_f == NULL)
{
free_f = dlsym(RTLD_NEXT, "free");
}
return ;
}
int main()
{
init_malloc_free_hook(); //执行一次
void * ptr1 = malloc(10);
void * ptr2 = malloc(20);
free(ptr1);
void * ptr3 = malloc(30);
free(ptr3);
return 0;
}
执行结果:
xuanmiao@linux:~/Test$ gcc hook.c -o hook -ldl -g
xuanmiao@linux:~/Test$ ls
hook hook.c
xuanmiao@linux:~/Test$ ./hook
exec malloc
exec malloc
exec free
exec malloc
exec free
内存泄漏与hook函数
浙公网安备 33010602011771号