Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 266
agrudzinski Avatar asked May 11 '26 12:05

agrudzinski


1 Answers

Can you create a function pointer by doing a typedef and use 'dlsym()' to get the address of the symbol. 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.

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");
like image 73
0xdky Avatar answered May 13 '26 04:05

0xdky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!