malloc插桩

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

参考

如何截获linux的库函数--库打桩机制-CSDN博客

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值