1

I'm a bit curious about the internal of ELF file. And I have this question:

Why we need to compile a shared library (.so) with the flag -fPIC?

While theoretically, we can dynamically link an executable with a statically linked elf file. This is because the GOT and PLT table in the executable need to be updated while the dynamically link executable can be left unchanged.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
Boehm
  • 11
  • 2
  • I understand that the shared library is supposed to be shared by multiple processes to save physical memory and disk space. But I still don't understand why we need a shared library (.so) file be compiled with -fPIC. – Boehm Jul 16 '13 at 13:24

2 Answers2

3

The idea of shared library is that the same code can be shared by several program in memory. However, one cannot ensure that the two running program expect the library to be at the same address of their memory layout (think of the collisions if the program use different shared libraries). So the shared library is only stored once in physical memory but thanks to the Memory Management Unit, the same physical memory is seen as being in two different address by the two programs. Of course for this to work you need the code to be independent of its real address (See eg http://eli.thegreenplace.net/2011/11/03/position-independent-code-pic-in-shared-libraries/ for more precise explanations)

This moreover allows you to randomize the address of the shared memory which is good for security reason (http://fr.wikipedia.org/wiki/Return-to-libc_attack)

hivert
  • 10,579
  • 3
  • 31
  • 56
  • when you say "shared library is only stored once in physical memory", i have some questions here. Where does a shared library gets stored in phy mem? How does kernel figure out the address of a shared library? – badmad Nov 18 '15 at 07:32
  • First of all, if you have another question, you should open another question. Second, I'm tempted to ask "Why do you care ?". Now here is my short answer: The kernel doesn't know. It just choose some random free physical memory to store the shared lib the first time the lib is used, and then, thanks to the MMU, maps this mem where it should be in each process. – hivert Nov 18 '15 at 22:18
0

PIC simply means position independent code. Think of jump addresses in your code, which need to be relative to the location of your shared library code in memory.

Also have a look at:

Community
  • 1
  • 1
tuxdna
  • 8,257
  • 4
  • 43
  • 61