I read this post on PIC and it seems that it always be good to use PIC (whenever it is exe / static / share llibrary).
So what are the disadvantages?
Are there examples elaborating when not to use PIC?
Position-independent code is recommended for the creation of shared objects. The compiler can generate position-independent code under the -K pic option. If a shared object is built from position-dependent code, the text segment can require modification at runtime.
Consequently, PIC objects are usually slightly larger and slower at runtime than the equivalent non-PIC object.
fPIC option in GCC enables the address of shared libraries to be relative so that the executable is independent of the position of libraries. This enables one to share built library which has dependencies on other shared libraries. fPIC stands for "force Position Independent Code".
Position-independent code (PIC) is code that uses no hard-coded addresses for either code or data. Shellcode is PIC.
The accepted answer in the linked question is very simplistic, and only brings up one thing that differs between PIC and non-PIC code, generation of jumps that are relative instead of absolute.
When you make PIC code, it's not only the code that's position independent, it's the data as well. And not all code or data can be addressed simply by using relative offsets, it has to be resolved at load-time (when the library/program is loaded into memory) or even during run-time.
Also, using relative addressing means that the CPU have to translate the relative offsets into absolute addresses, instead of it being done by the compiler.
On system with virtual memory there's often no need to spend load- or run-time on these relative address resolutions when the compiler can do it once and for all.
On some architectures, including x86, -fPIC
generates much worse code (i.e. a function call) for loads/stores of data. While this is tolerable for libraries, it is undesirable for executables.
One of the major selling points of the amd64 instruction set (and also the recent gnu-x32 ABI) was the addition of "PC-relative load/store" instructions, which solve the efficiency problem.
Note that hardened systems usually do enable -fPIE
for all executables, because it allows address-space layout randomness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With