14

I am reading this article on PLT (Process Linkage Table) and GOT (Global Offset Table). While the purpose of PLT is clear to me, I'm still confused about GOT. What I've understood from the article is that GOT is only necessary for variables declared as extern in a shared library. For global variables declared as static in a shared library code, it is not required.

Is my understanding right, or am I completely missing the point.

MetallicPriest
  • 29,191
  • 52
  • 200
  • 356

1 Answers1

19

Perhaps your confusion is with the meaning of extern. Since the default linkage is extern, any variable declared outside function scope without the static keyword is extern.

The reason the GOT is necessary is because the address of variables accessed by the shared library code is not known at the time the shared library is generated. It depends either on the load address the library gets loaded at (if the definition is in the library itself) or the third-party code the variable is defined in (if the definition is elsewhere). So rather than putting the address inline in the code, the compiler generates code to read the shared library's GOT and then loads the address from the GOT at runtime.

If the variable is known to be defined within the same shared library (either because it's static or the hidden or protected visibility attribute it used) then the address relative to the code in the library can be fixed at the time the shared library file is generated. In this case, rather than performing a lookup through the GOT, the compiler just generates code to access the variable with program-counter-relative addressing. This is less expensive both at runtime and at load time (because the whole symbol lookup and relocation process can be skipped at load time).

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • Any idea how to force gcc to perform lookup through the GOT for static variables? – Violet Giraffe Sep 19 '13 at 06:51
  • I'm trying to make my application for an ARM processor as a position-independent executable and everything works fine except for the static variables. The problem is that .text section and .data/.bss sections have different relocation offsets, so pc-relative access to static variables doesn't work while access through the GOT works fine. – Violet Giraffe Sep 19 '13 at 07:20
  • 2
    How do you expect the code to find the GOT if it's not at a fixed offset from the `.text` section? On normal systems, the offset between text and data is fixed at link time and the loader ensures that it's preserved when loading the program. – R.. GitHub STOP HELPING ICE Sep 19 '13 at 14:08
  • It is possible by using SBR-relative addressing, see http://stackoverflow.com/a/24408631/779419 – schieferstapel Jun 25 '14 at 12:34