Why different memory addresses for a function between direct linking and dlopen

爱⌒轻易说出口 提交于 2020-01-06 05:29:10

问题


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
#

回答1:


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 ....



来源:https://stackoverflow.com/questions/48109700/why-different-memory-addresses-for-a-function-between-direct-linking-and-dlopen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!