Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dlopen()/dlsym() on the main executable: how portable is it?

Tags:

unix

dll

dlopen

I'm building a compiler and a virtual machine for executing my byte code. The language allows to bind external C functions, which may be defined in some external shared object, as well as the main compiler/VM binary (some essential language built-ins).

I know I can dynamically bind symbols within the main executable with dlopen(NULL, ...), however NOT after I run strip on the binary. I have the following questions then:

  1. Is there a way to do this on a strip'ed binary?
  2. How portable is this feature across UNIX systems in general?
  3. Is it possible to do the same trick on Windows somehow?
  4. Any alternatives ways of binding dynamically within the main executable?
like image 448
mojuba Avatar asked Nov 15 '10 11:11

mojuba


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 does Dlopen do in Linux?

dlopen() The function dlopen() loads the dynamic shared object (shared library) file named by the null-terminated string filename and returns an opaque "handle" for the loaded object. This handle is employed with other functions in the dlopen API, such as dlsym(3), dladdr(3), dlinfo(3), and dlclose().

What happens if Dlopen is called twice?

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.

What is Dlopen in C?

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


1 Answers

  1. Use strip -d instead to only strip debug symbols.

  2. The dlopen(3) man page says:

    CONFORMING TO
           POSIX.1-2001 describes dlclose(), dlerror(), dlopen(), and dlsym().
    

    So, very portable across *nix.

  3. Windows uses LoadLibrary() and GetProcAddress() instead.

  4. No.

like image 147
Ignacio Vazquez-Abrams Avatar answered Oct 12 '22 12:10

Ignacio Vazquez-Abrams