Position Independent Executables and Android

I don't know anything about PIE, Please tell me how to create a position independent executable.

Position Independent Executable or PIE allows a program to be relocated, just like a shared object. At each run of the program, the program can be loaded at different addresses to make it harder for an attacker to guess certain program state.

You can compile and link a PIE executable in one of two ways. First, compile everything with -fPIE and link with -pie. The second is to compile everything with -fPIC and link with -pie.

If you are building both a shared object and a program, then compile everything with -fPIC. Link the shared object with -shared, and link the program with -pie.

You cannot do it the other way. That is, you cannot compile everything with -fPIE and build both a shared object and a program. For the details, see Code Generation Options in the GCC manual.


One thing to watch out for on Android: building with PIE prior to 4.1 will cause a segmentation fault in /system/bin/linker. PIE was added at Android 4.1, and it crashes lesser versions.

Someone told me to supply a custom link/loader to avoid the problem, but I can't find the reference at the moment.

Also see Security Enhancements in Android 1.5 through 4.1.


Error: only position independent executables (PIE) are supported

Yes, that's a Lollipop feature. See Security Enhancements in Android 5.0.


You can check if a program is built with PIE using readelf:

$ readelf -l my-prog | grep -i "file type"
Elf filetype is DYN (shared object file)

The important part is readelf is reporting DYN, and not reporting EXE. EXE means it lacks PIE, and that should trigger a security related defect.


Related, see Is PIE (Position-independent executable) for main executables supported in Android 4.0 (ICS)?


i know this is an old topic but this hacky way may save some people's time
with a Hex-Editor , find the 17th byte, change the value 02 to 03, and that’s it!