dlsym() fails with an executable shared library

Ian Lance Taylor iant@google.com
Thu Dec 8 17:01:00 GMT 2011


Mayank Kaushik <mayank.utexas@gmail.com> writes:

>> > gcc -fPIC -fPIE -pie -o library.so test.c
>>
>> That does not make a shared library.
>
> I'm curious, why not? It's position independent. "file" says it's a
> shared object:
> $ file ./library.so
> ./library.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV),
> dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not
> stripped

Sorry, you're right, using -pie does create an ET_DYN file.  So I
suppose that technically it is a shared library.

>> > This can read arguments fine, but dlsym() fails:
>> >
>> > ./library.so: undefined symbol: my_func
>>
>> You can probably fix that problem by linking with -rdynamic.
>
> Didn't work, unfortunately, same problem.

Worked fine when I tried it.  I built your source code using

gcc -fPIE -pie -o foo.so foo.c -rdynamic

Then I created this file:

#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>

void
die (const char *msg)
{
  fprintf (stderr, "%s: %s\n", msg, dlerror ());
  exit (EXIT_FAILURE);
}

int
main()
{
  void *handle = dlopen ("./foo.so", RTLD_LAZY);
  if (handle == NULL)
    die ("dlopen");
  void *sym = dlsym (handle, "my_func");
  if (sym == NULL)
    die ("sym");
  void (*pfn)(int) = (void (*)(int)) sym;
  (*pfn) (3);
  return 0;
}

gcc -o foo2 foo2.c
./foo2

printed

Inside my_func: 3

Ian



More information about the Gcc-help mailing list