Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not always use fpic (Position Independent Code)? [duplicate]

Tags:

c++

gcc

fpic

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?

like image 464
Azil Avatar asked Jul 10 '15 04:07

Azil


People also ask

Should I use position independent code?

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.

Is position independent code slower?

Consequently, PIC objects are usually slightly larger and slower at runtime than the equivalent non-PIC object.

What does the fPIC option do?

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".

What is position independent Shellcode?

Position-independent code (PIC) is code that uses no hard-coded addresses for either code or data. Shellcode is PIC.


2 Answers

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.

like image 97
Some programmer dude Avatar answered Oct 13 '22 23:10

Some programmer dude


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.

like image 37
o11c Avatar answered Oct 14 '22 00:10

o11c