简体   繁体   English

从共享对象中调用主可执行文件中的函数

[英]Call functions in the main executable from a shared object

I have to call functions in the main executable from a shared library loaded with LD_PRELOAD. 我必须从加载了LD_PRELOAD的共享库中调用主可执行文件中的函数。

The executable exports all symbols and contains debug information. 可执行文件导出所有符号并包含调试信息。 Unfortunately I don't have access to it's source code. 不幸的是我没有访问它的源代码。

Currently I'm getting undefined symbol errors when trying to load that shared library. 目前,我在尝试加载该共享库时遇到了未定义的符号错误。 Is there a way to do this? 有没有办法做到这一点?

PS: Target platform is FreeBSD/x86. PS:目标平台是FreeBSD / x86。

Can you create a function pointer by doing a typedef and use 'dlsym()' to get the address of the symbol. 你可以通过执行一个typedef创建一个函数指针,并使用'dlsym()'来获取符号的地址。 You can then invoke the function through the function pointer like a normal function call. 然后,您可以像通常的函数调用一样通过函数指针调用该函数。 Note: You do not need dlopen() since the main executable with symbols exported is loaded into process address space. 注意:您不需要dlopen(),因为带有符号导出的主可执行文件会加载到进程地址空间中。

Prototype: 原型:

void *dlsym(void *handle, const char *symbol);

Assume the exported function is: 假设导出的函数是:

int foo(char *arg);

Your function pointer: 你的函数指针:

typedef (int)(*fooPtr)(char *);

In you code: 在你的代码中:

/* You can send NULL for first argument */
fooPtr fp = dlsym(NULL, "foo");
assert(0 != fp);
int ret = fp("hello world");
gcc -Wl,--export-dynamic

...should do the trick. ......应该做的伎俩。

Documentation on --export-dynamic 有关--export-dynamic的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM