How does the dynamic linker find external functions at runtime?

0
0
Asked By MellowPine42 On

With static linking, the required function code is included in the executable and the linker can resolve calls directly. Dynamic linking is less clear to me: if a function lives in a shared library, where is that library stored in the process's address space, and how does the program discover the function's address? I assume the operating system maps shared libraries into the process's virtual memory, but I'd like a practical explanation of how loading, symbol lookup, and external function calls work.

3 Answers

Answered By SilverCactus3 On

A shared library contains exported symbols and information describing where their code or data is located relative to the library's loaded base address. Once the loader knows that base address, it can combine it with the symbol's offset to calculate the function's runtime address. The process can access the library because its code and data pages have been mapped into that process, even though the library is not physically embedded in the executable.

Answered By CedarFox7 On

Yes—the shared library is mapped into the process's virtual address space by the dynamic loader, usually before the program's main entry point runs. The loader reads the executable's dependency information, maps each required library (often using memory-mapping facilities), and performs relocations. Address-space layout randomization may cause the library's base address to differ on each run. The loader then uses the library's dynamic symbol table and relocation information to resolve imported functions and variables.

QuietHarbor18 -

The loader is sometimes called the runtime linker or link loader. The ordinary linker leaves placeholders or stubs for external references, and those references are completed when the program is loaded.

Answered By NimbleKite56 On

On systems using ELF and position-independent code, external calls commonly go through the PLT and GOT. The call reaches a stub that obtains the function pointer from the GOT. With lazy binding, the first call may enter the dynamic loader's resolver; the resolver finds the symbol, writes its address into the GOT, and subsequent calls go directly through the now-updated entry. Eager binding can resolve everything during startup instead. Older or non-position-independent code may require relocations that modify code or data locations directly, sometimes causing private copy-on-write pages.

BriskWalrus21 -

You can inspect this behavior on a typical ELF system with tools such as objdump, which shows PLT entries, or with the loader's binding-debugging options. The exact mechanisms differ between operating systems, but mapping libraries and resolving exported symbols at load time are the general ideas.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.