问题描述:

I want to be able to call into an executable from a library that I have preloaded. To do this -

I have a simple executable

main.c

#include <stdio.h>

void callme()

{

printf("callme\n");

}

int main(int argc, char *argv[])

{

callme();

return 0;

};

This is compiled with

gcc -m32 main.c

I now want to preload a library so that callme is called before main.

preload.c

extern void callme();

void preload_init() __attribute__((constructor));

void preload_fini() __attribute__((destructor));

void preload_init()

{

callme();

}

void preload_fini()

{

callme();

}

This is compiled with

gcc -D_GNU_SOURCE -shared -o libpreload.so preload.c -fPIC -m32 -ldl

So now I have a.out and libpreload.so

When I try and run this

LD_PRELOAD=./libpreload.so ./a.out

./a.out: symbol lookup error: ./libpreload.so: undefined symbol: callme

To debug this I have tried

LD_DEBUG=symbols LD_PRELOAD=./libpreload.so ./a.out

The output from this includes this line

13184: symbol=callme; lookup in file=./a.out [0]

So it looks like its looking in the correct place for the callme symbol.

The output from nm a.out includes the following line

080483b4 T callme

Do I have to compile in such a way that makes callme externally accessible from outside of a.out ?

Any help would be appreciated.

网友答案:

Add -rdynamic to your program's compilation flags. By default, only shared libraries are linked with dynamic symbols table (table that dynamic linker (e.g. /lib/ld-linux.so.2) uses to lookup function address by its name).

Without dynamic symbols table, you can't use dlsym on self binary too.

相关阅读:
Top