Linux – Questions about how loader locates libraries at runtime

Questions about how loader locates libraries at runtime… here is a solution to the problem.

Questions about how loader locates libraries at runtime

Only a minimum amount of work is done
at compile time by the linker; it only
records what library routines the
program needs and the index names or
numbers of the routines in the
library. (source)

So this means that ld.so will not check all the libraries in its database, only those libraries documented by the application itself, that is, only those specified by gcc -lxxx.

This contradicts my previous understanding that ld.so would check all the libraries in its database one by one until they found them.

What is the specifics?

Solution

I will try to answer this question….

At link time, the linker (not the ld.so) ensures that all symbols of the .o files that are linked together are satisfied by the library to which the program links. If any of these libraries are dynamic, it also checks the libraries they depend on (they do not need to be included in the -l list) to ensure that all symbols in these libraries are satisfied. It will do this recursively.

Only libraries that the executable directly depends on when linking via the -l parameter are documented in the executable. If the libraries themselves declare dependencies, those dependencies will not be documented in the executable unless the libraries are also specified with the -l flag at link time.

The link occurs when you run the linker. For gcc, this is usually similar to gcc a.o b.o c.o -lm -o myprogram. This usually happens at the end of the compilation process. Behind the scenes, it usually runs a program called ld. But ld is quite different from ld.so (runtime loader). Although they are different entities, they have similar names because they do similar work at different times.

Loading is the step that occurs when you run a program. For dynamic libraries, if you use a static library, the loader does a lot of the work that a linker would do.

When the program runs, ld.so (runtime loader) actually associates the symbols on the executable with the definition hooks in the shared library. If that shared library depends on other shared libraries (facts documented in the library), it also loads those libraries and connects them. If all this is done and there are still unresolved symbols, the loader aborts the program.

Thus, the executable illustrates which dynamic libraries it directly depends on. Each of these libraries illustrates which dynamic libraries they directly depend on, and so on. The loader (ld.so) uses it to decide which libraries to look for symbols. It does not randomly search other libraries in the Database for suitable symbols. They must be in libraries in the dependency chain.

Related Problems and Solutions