8

What is the search order for symbol lookup when resolving dynamic relocations?

When resolving symbols for a shared library does the loader first search in the 'main executable' (to let the main executable override definitions...) or what?

JohnTortugo
  • 6,356
  • 7
  • 36
  • 69

2 Answers2

12

Per my understanding, each executable object has its own "lookup scope":

  • The main executable is usually the first object in the "global" lookup scope. This means that symbols defined in the main executable would override those in dependent shared libraries. Shared objects that are added using the LD_PRELOAD facility are added to the global lookup scope, right after the main executable.
  • However, if the shared object being loaded uses the DF_SYMBOLIC flag, then symbol references that originate within that object will look for definitions within the object before searching in the global lookup scope.
  • Shared objects opened using dlopen() may have their own dependencies. If the RTLD_GLOBAL flag was not set during the call to dlopen(), these dependencies are added to the lookup scope for that object, but do not affect the global lookup scope. If the RTLD_GLOBAL flag was passed to dlopen(), then the shared object (and its dependencies) will be added to the "global" lookup scope, changing the behavior of subsequent symbol lookups.

Ulrich Drepper's guide "How to Write Shared Libraries" is recommended reading on this topic.

jkoshy
  • 1,793
  • 15
  • 23
  • 1
    For completeness: There are symbols of the main executable that wont be exported to the dynamic symbol table unless you compile it with rdynamic option (or similar) – debuti Feb 19 '18 at 14:44
  • linking flag "-rdynamic" solves as @debuti pointed out. I tried the dlopen flag RTLD_GLOBAL or RTLD_DEEPBIND, neither works. – ZFY Apr 09 '18 at 05:49
4

When resolving symbols for a shared library does the loader first search in the 'main executable' (to let the main executable override definitions...) or what?

Yes, exactly. The dynamic loader has a linked list of loaded ELF objects (the head of the list is _r_dynamic.r_map) and searches dynamic symbol tables of objects in that list linearly, until it finds the symbol definition it is looking for.

The head of the list always points to the main executable. If a given symbol is exported from the main executable, then it (almost) always "wins" (overrides other definitions).

However, note that -Bsymbolic linker flag changes the picture a bit.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362