使用dlsym使用自定义方法Hook库函数
我最近开始寻找从C ++代码挂接的库。
符号表的创建有些混乱。
以下是我的代码(从某些在线资源中选择,我用C ++编译了C代码)
hook_main.cpp
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
int main()
{
int *p;
p = (int *) malloc(10);
free(p);
return 0;
}
Hook_lib.cpp
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
void *malloc(size_t _size)
{
static void* (*my_malloc)(size_t) = NULL;
printf("Custom malloc called\n");
if(!my_malloc)
my_malloc = dlsym(RTLD_NEXT,"malloc");
void *p = my_malloc(_size);
return p;
}
I使用C ++编译两个文件,但是它没有提供所需的输出。 在调试时,我在hook_lib.cpp中添加
#include <iostream>
,突然我的符号表变化了(库开始显示malloc的定义),
请有人对此行为有所了解。这与名称杂交有关吗?
I am recently started looking in hooking into library from C++ code.
There is a slight confusion with the symbol table creation.
Below is my code (Picked from some online resource, I compiled C code with C++)
hook_main.cpp
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
int main()
{
int *p;
p = (int *) malloc(10);
free(p);
return 0;
}
hook_lib.cpp
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
void *malloc(size_t _size)
{
static void* (*my_malloc)(size_t) = NULL;
printf("Custom malloc called\n");
if(!my_malloc)
my_malloc = dlsym(RTLD_NEXT,"malloc");
void *p = my_malloc(_size);
return p;
}
I am compiling both the files using c++, however it doesn't give the desired output.
While debugging, I added
#include <iostream>
in hook_lib.cpp and suddenly my symbol table got changed (library started showing the definition of malloc)
Can somebody please put some light on this behavior. Is this something to do with name mangling ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
hook_lib.cpp
不编译。可能是这样的:Your
hook_lib.cpp
doesn't compile. It could be something like this:这是由于 C++ 的名称修改而发生的。
目标文件中的函数名称被修改为 _Z6malloc,这是损坏的 C++ 名称。现在,当我包含 iostream 时,也许它包含提供 malloc 外部声明的标头链。
声明,我们会得到相同的预期行为。
本质上,如果我们只在 hook_lib.cpp 中
如果我们在此之后检查目标文件,函数名称仍为 malloc 并且 dlsym 能够找到我们的函数。
It is happening because of name mangling by C++.
The function name in object file get modified to _Z6malloc which is the mangled C++ name. Now, when I included iostream, maybe it included the chain of headers which provided the extern declaration of malloc.
Essentially, we get the same expected behavior if we just declare
in hook_lib.cpp
If we inspect the object file after this, the function name stays as malloc and dlsym is able to locate our function.