Jason Yu
Jason Yu

Reputation: 2038

Why shared libraries are implemented using GOT (Global Offset Table)?

I have looked up tons of articles about GOT, dynamic linking and shared libraries. But I still can't figure out why shared library can't be implemented by dynamic linker directly modifying addresses of "mov" instructions in ".text" section to "fix" symbol relocations?

Upvotes: 2

Views: 539

Answers (2)

yugr
yugr

Reputation: 21955

This would be much less efficient. Here's what comes to mind, there might be more:

  • this breaks code sharing across different processes which load same shared library
  • there will typically be lots of calls that require updating (rather than just updating single address in GOT)
  • loader would need to remap code pages as writable and then map them again as read-only; that's 2*num_pages system calls so quite slow
  • static linker would need to reserve maximum number of bytes in call instructions to accomodate for largest possible address (8 on x86_64) which would increase code size

You also loose lazy symbol resolution.

Upvotes: 1

Luis Colorado
Luis Colorado

Reputation: 12698

The reason is that the .text section of a shared library is indeed shared (by all processes using that shared object) and if you modify it, it gets modified in all instances of it (so you are actually modifying the code of other processes). This is the reason shared libraries have to be compiled in PIC (Position Independent Code) mode, because all instances of the same shared text load at different addresses, depending on the final executable that is going to use them.

Only in systems where the kernel (e.g. freebsd allows this) Allows .text segments to load in copy on write mode this is permissible. But think in the overhead of copying a full page of code for process private access only because you have touched (only once) several pointers on it.

Normal binaries have their code read only or execute only, so you can share the same pages of code between all processes that use them. Think that the kernel normally doesn't use even swap space to store those pages, as it can go to the executable file to reload the page in case it gets swapped out (It isn't, the page is just discarded from memory)

Upvotes: 0

Related Questions