0

When same library is linked and used with dlopen, same function (sqrt in this example) has different memory addresses. Can you please explain why it is so? Is there some indirection?

# cat dl-test.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <math.h>
#include <inttypes.h>

int main()
{
        void *dl, *dl_sqrt;

        dl = dlopen("/lib/x86_64-linux-gnu/libm.so.6", RTLD_LAZY);
        if (!dl) {
                fprintf(stderr, "%s\n", dlerror());
                exit(1);
        }

        dl_sqrt = dlsym(dl,"sqrt");
        if (!dl_sqrt) {
                fprintf(stderr, "%s\n", dlerror());
                exit(1);
        }

        printf("Address of sqrt %p\n", (void*) sqrt);
        printf("Address of (dl)sqrt %p\n", (void*) dl_sqrt);
        return 0;
}
#
# gcc dl-test.c -lm -ldl -o dl-test
# ldd dl-test
        linux-vdso.so.1 =>  (0x00007fff9132b000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f4caee90000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f4caec8c000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f4cae8c1000)
        /lib64/ld-linux-x86-64.so.2 (0x0000559a02daa000)
# ./dl-test
Address of sqrt 0x4006d0
Address of (dl)sqrt 0x7fa7ce6f7250
#
Aditi
  • 1
  • Why do you ask, and what is the real use-case? Please **edit your question** to motivate it and give more context. Most of the time, what you observe does not matter. – Basile Starynkevitch Jan 05 '18 at 08:29
  • Thanks for the reply. I'm in early stages of exploring ways to make a shared library as linkable as well as plug-in. I'm trying to see if this is achievable without recompilation. One follow up question: Is there a way to get address of function or symbol (that is already linked to the application) without dlopen context. – Aditi Jan 05 '18 at 09:40

1 Answers1

3

Read Drepper's (long) paper How To Write Shared Libraries and study carefully the ELF format. See elf(5), objdump(1), ldd(1), readelf(1), ld-linux(8), dlopen(3), dlsym(3)

Is there some indirection?

Yes, the Procedure Linkage Table, see this.

Notice also the special case of dlopen with a NULL file path (to get a handle to your entire program), and the various flags to dlopen ....

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547