如何查看共享库加载顺序

How to see the order of shared library loading

给定一个 ELF 二进制文件或共享对象,我如何才能最轻松地查看所需共享库的加载顺序?

它们是否按照 readelf -d 列出的顺序加载?

how can I most easily see the order in which the needed shared libraries will be loaded?

使用LD_DEBUG:

LD_DEBUG=files /bin/ls
13444:
13444:     file=libc.so.6 [0];  needed by who [0]
...
13444:     file=libnss_files.so.2 [0];  needed by who [0]
...

有关更多信息的人 ld.so。

Are they loaded in the order they are listed by readelf -d?

不一定它会受到预加载的影响 (LD_PRELOAD, /etc/ld.so.preload).

使用 LD_DEBUG=files 可以查看库的搜索顺序, 库的初始化顺序。后者可能与前者不同。

Are they loaded in the order they are listed by readelf -d

取决于您所说的 "loaded" 是什么意思。一旦返回初始化程序,库就是 "fully loaded"。

根据该定义,否:readelf -d中列出的NEEDED个依赖的顺序和加载的顺序不一样

考虑 a.out 这取决于 libA.solibB.so:

readelf -d a.out | grep NEEDED
 0x0000000000000001 (NEEDED)             Shared library: [libA.so]
 0x0000000000000001 (NEEDED)             Shared library: [libB.so]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]

此外,libA.so 本身依赖于 libC.solibD.so:

readelf -d libA.so | grep NEEDED
 0x0000000000000001 (NEEDED)             Shared library: [libC.so]
 0x0000000000000001 (NEEDED)             Shared library: [libD.so]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]

搜索库的顺序:

LD_DEBUG=files ./a.out |& grep 'needed by'
     49169: file=libA.so [0];  needed by ./a.out [0]
     49169: file=libB.so [0];  needed by ./a.out [0]
     49169: file=libc.so.6 [0];  needed by ./a.out [0]
     49169: file=libC.so [0];  needed by ./libA.so [0]
     49169: file=libD.so [0];  needed by ./libA.so [0]

图书馆的顺序"fully loaded":

 LD_DEBUG=files ./a.out |& grep 'calling init'
     69038: calling init: /lib/x86_64-linux-gnu/libc.so.6
     69038: calling init: ./libD.so
     69038: calling init: ./libC.so
     69038: calling init: ./libB.so
     69038: calling init: ./libA.so

其他可能影响加载顺序的因素:

  1. LD_PRELOAD/etc/ld.so.preload.
  2. 任何库都可以在其初始化程序中执行 dlopen