Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dlopen() on an executable

I need to call a function from another program. If the other program were a library, I could simply use dlopen and dlsym to get a handle to the function. Unfortunately, the other program is a Unix Executable, and building it as a library is not an option. Trying dlopen() on the executable gives this error message:

dlopen([...]/testprogram, 1): no suitable image found. Did find: [...]/testprogram: can't map

This isn't surprising, as dlopen is meant for use with libraries, not executables. Is there any way to get dlopen and dlsym to work with executables? If not, is there an alternative way of achieving the same thing?

like image 739
Jeff Avatar asked Jul 07 '11 22:07

Jeff


People also ask

Can you Dlopen an executable?

On some ELF systems (notably Linux), you can dlopen() PIE executables. When using GCC, just compile the executable with -fpie or -fPIE , and link it with -pie , and export the appropriate symbols using --dynamic-list or -rdynamic (explained in more detail in this other SO answer.

What is dlopen()?

The dlopen() function shall make an executable object file specified by file available to the calling program.

What happens if Dlopen is called twice?

1 Answer. Show activity on this post. If the same library is loaded again with dlopen(), the same file handle is returned. The dl library maintains reference counts for library handles, so a dynamic library is not deallocated until dlclose() has been called on it as many times as dlopen() has succeeded on it.


2 Answers

You can't open executables as libraries. The entry point of an executable will attempt to re-initialize the C library, and take over the brk pointer. This will corrupt your malloc heap. Additionally, the executable is likely to be mapped at a fixed address with no relocations, and if this address overlaps with anything already loaded, it's not possible to map it for that reason as well.

You need to refactor the other program into a library, or add a RPC interface to the other program.

Note that this does not necessarily apply for PIE executables. However, unless the executable is specifically designed for being dlopen()ed, this is unsafe, as main() will not be run, and any initialization done in main() therefore will not occur.

like image 68
bdonlan Avatar answered Sep 27 '22 20:09

bdonlan


On some ELF systems (notably Linux), you can dlopen() PIE executables. When using GCC, just compile the executable with -fpie or -fPIE, and link it with -pie, and export the appropriate symbols using --dynamic-list or -rdynamic (explained in more detail in this other SO answer.

like image 41
ninjalj Avatar answered Sep 27 '22 20:09

ninjalj