共享库中R_386_32重定位机制咨询:跨库全局变量引用场景
Let’s walk through exactly how the dynamic linker handles relocation for libbigshr.so and its dependency on libfunlib.so—this is core shared library linking behavior.
1. Initial Library Loading
When your program (or another library) tries to load libbigshr.so, the dynamic linker (e.g., ld-linux.so on Linux) first parses its dynamic section and discovers it depends on libfunlib.so. The linker:
- Loads
libfunlib.sointo the process’s virtual address space (at a random base address thanks to ASLR, Address Space Layout Randomization). - Resolves
libfunlib.so’s own relocations first (if any) so its symbols—including the global variablefoo—have valid memory addresses.
2. Symbol Resolution for foo
Next, the linker turns its attention to libbigshr.so’s .rel.dyn section, which lists all data symbols that need relocation. Let’s break down each entry in your .rel.dyn output:
- Offset: The memory offset within
libbigshr.so’s loaded image where the reference tofoolives (e.g.,000005a5). - Info: A 32-bit value split into two parts: the upper 16 bits are the index of
fooinlibbigshr.so’s dynamic symbol table (.dynsym), and the lower 16 bits specify the relocation type (01=R_386_32). - Type (
R_386_32): This tells the linker to write the 32-bit absolute address offoodirectly into the memory location at the given offset. - Sym.Value:
00000000here is a placeholder—this was the "fake" address used at link time, sincefoowasn’t defined inlibbigshr.so. - Sym.Name:
foo, the symbol the linker needs to find.
The linker looks up foo in the dependency chain: it checks libfunlib.so’s dynamic symbol table (.dynsym) and retrieves the actual virtual address of foo (now set because libfunlib.so was loaded).
3. Executing the Relocations
For each of the three foo entries in .rel.dyn:
- Calculate the full memory address to modify:
libbigshr.so’s loaded base address + the entry’s offset (e.g.,base + 0x5a5). - Write the actual 32-bit address of
foo(fromlibfunlib.so) into that memory location. - Repeat this for
0x5aband0x5c7—each offset corresponds to a separate place inlibbigshr.sowherefoois referenced (e.g., three different variable assignments or code lines that usefoo).
Key Notes
- The three entries mean
libbigshr.sohas three distinct direct references tofoo’s absolute address—each requires its own relocation. .rel.dynis used for data symbols (like global variables) because these are typically resolved immediately at load time, unlike function symbols which often use.rel.pltfor lazy (on-first-call) binding.- ASLR ensures that each library loads at a unique address every time the program runs, making dynamic relocation mandatory—static linking wouldn’t need this because addresses are fixed at compile time.
内容的提问来源于stack exchange,提问作者ultimate cause

