Issue
While reading this blogpost, I came across the following while the author tries to justify the need of PIC for shared libraries.
If your shared library is built to only work when loaded at one particular address everything may be fine — until another library comes along that was built also using that address.
If the start address of the library determines where the library goes into memory, what is virtual memory management doing here? I mean memory mapping should be able to determine that something is already in this physical address space, so we could possibly place the next shared library elsewhere.
Moreover the loading address that the library specifies is the virtual address space right? so why does it even create a problem if both of the libraries have the same virtual address space load address.
So I have basically this question:
- When using non-PIC, the problem of two libraries having something in the same address makes less sense to me currently. Does this have to do with the first library overlapping with addresses of the second library? but again the OS memory management should be able to put things into spaces where physical memory is free then where is even the conflict?
Solution
The problem has nothing to do with physical addresses. It solely relies on one thing: in the virtual address space, two libraries cannot reside at the same address.
Virtual memory maps each allocated virtual page to a physical page (or frame). Let us say that for process P1, VA 0x10000 maps to PA 0xff000. Thanks to virtual memory, though, a separate process P2 can also have a different page at the same address. So, P2 can have VA 0x10000 map to PA 0xee000. There is no conflict since they are two separate virtual address spaces.
However, the problem stated in the post applies to a single process, and its address space. Therefore, for process P1, the VA 0x10000 cannot map to both PA 0xff000 and 0xee000. Suppose you have two libraries (libX and libY) which are non-PIC, and are compiled to only work at VA 0x10000. If P1 wants to load both libraries, it has a problem since it has to load both of them into the same virtual address space, and they both want to use the same VA. The VA 0x10000 can only map to a physical page for one of the libraries.
With PIC libraries, this is not a problem since P1 can place libX at VA 0x10000 and libY at VA 0x20000. The virtual memory mapping can then map the two libraries' VAs to their respective PAs.
Answered By - TSG