3

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.

  • possible duplicate of [how to call function in executable from my library?](http://stackoverflow.com/questions/6292473/how-to-call-function-in-executable-from-my-library) – ninjalj Nov 01 '11 at 19:03
  • No, my question is a bit different since I don't have the main executable's source. – agrudzinski Nov 01 '11 at 19:53

2 Answers2

3

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");
deepsnore
  • 976
  • 5
  • 13
0
gcc -Wl,--export-dynamic

...should do the trick.

Documentation on --export-dynamic

Nemo
  • 70,042
  • 10
  • 116
  • 153