alireza_fn alireza_fn - 2 months ago 9
Linux Question

how to self dlopen an executable binary

I wrote a program to dlopen itself

void hello()
{
printf("hello world\n");
}
int main(int argc, char **argv)
{
char *buf="hello";
void *hndl = dlopen(argv[0], RTLD_LAZY);
void (*fptr)(void) = dlsym(hndl, buf);
if (fptr != NULL)
fptr();
dlclose(hndl);
}


but I get "segemention fault" error
I tested this program with a .so library and it works but can not get it working with itself

Answer Source

You need to code:

  // file ds.c
  #include <stdio.h>
  #include <stdlib.h>
  #include <dlfcn.h>

  void hello ()
  {
    printf ("hello world\n");
  }

  int main (int argc, char **argv)
  {
    char *buf = "hello";
    void *hndl = dlopen (NULL, RTLD_LAZY);
    if (!hndl) { fprintf(stderr, "dlopen failed: %s\n", dlerror()); 
      exit (EXIT_FAILURE); };
    void (*fptr) (void) = dlsym (hndl, buf);
    if (fptr != NULL)
      fptr ();
    else
      fprintf(stderr, "dlsym %s failed: %s\n", buf, dlerror());
    dlclose (hndl);
  }    

Read carefully dlopen(3), always check the success of the dlopen & dlsym functions there, and use dlerror on failure.

and compile the above ds.c file with

  gcc -std=c99 -Wall -rdynamic ds.c -o ds -ldl

Don't forget the -Wall to get all warnings and the -rdynamic flag (to be able to dlsym your own symbols which should go into the dynamic table).

On my Debian/Sid/x86-64 system (with gcc version 4.8.2, and libc6 version 2.17-93 providing the -ldl, kernel 3.11.6 compiled by me, binutils package 2.23.90 providing ld), the execution of ./ds gives the expected output:

  % ./ds 
  hello world

and even:

  % ltrace ./ds
  __libc_start_main(0x4009b3, 1, 0x7fff1d0088b8, 0x400a50, 0x400ae0 <unfinished ...>
  dlopen(NULL, 1)                                = 0x7f1e06c9e1e8
  dlsym(0x7f1e06c9e1e8, "hello")                 = 0x004009a0
  puts("hello world"hello world
  )                            = 12
  dlclose(0x7f1e06c9e1e8)                        = 0
  +++ exited (status 0) +++