研究了一下__malloc_hook, 你可以用man __malloc_hook 获取它的第一认识.
原来它是glibc 定义的一组变量(函数指针), 由此而去调用对应的函数, 这就叫hook. 把这个hook 定义到哪里,它就会调用到哪里,于是就理解了这个hook, 下面给出 一个完成的示例加深理解, 是参考手册写出的代码,调试通过.
可以理解为也是一种代码注入手段. 用以检查内存泄露等!
源码:
cat main.cpp
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
/*prototype define for us*/
static void my_init_hook(void);
static void *my_malloc_hook(size_t, const void *);
static void my_free_hook(void *,const void *);
/*save old hook variable*/
static void *(*old_malloc_hook)(size_t, const void *);
static void (*old_free_hook)(void *, const void *);
static void save_orighook_to_old();
static void restore_oldhook_to_hook();
static void save_myaddr_to_hook();
/*initialize hook*/ // 这个变量从glibc2.24 就放弃了. 所以要自己主动调用my_init_hook
void (*__malloc_initialize_hook) (void) = my_init_hook;
/*init function*/
static void my_init_hook(void)
{
save_orighook_to_old();
save_myaddr_to_hook();
}
static void save_orighook_to_old()
{
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
}
static void restore_oldhook_to_hook()
{
__malloc_hook = old_malloc_hook;
__free_hook = old_free_hook;
}
static void save_myaddr_to_hook()
{
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
}
/*my alloc hook*/
static void * my_malloc_hook(size_t size, const void * caller)
{
void *result; /*malloc's return*/
restore_oldhook_to_hook();
result = malloc(size);
/*printf might call malloc, so protect it too*/
printf("malloc(%u)| call from %p, return %p\n",(unsigned int)size, caller, result);
save_orighook_to_old();
save_myaddr_to_hook();
return result;
}
/*free hook is same like malloc*/
static void my_free_hook(void *ptr,const void *caller)
{
restore_oldhook_to_hook();
free(ptr);
printf("free(%p)| called from %p\n",ptr, caller);
}
/*main*/
int main(void)
{
char *p;
my_init_hook(); // 主动调用一次
p = (char *)malloc(10);
free(p);
return 0;
}
结果:
$ ./malloc-hook
malloc(10)| call from 0x55823ce748c7, return 0x55823dce7260
free(0x55823dce7260)| called from 0x55823ce748d7
|