Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we enable pie (i.e. Position Independent Executables) for shared libraries in android-ndk r10c?

Can we enable pie (i.e. Position Independent Executables) for shared libraries in android-ndk r10c? And if yes then how to do it?

I read that we should use PIC for dynamic libraries and PIE for executable but looks like android NDK doesn't support PIC.

I tried enabling -pie flag in LDFLAGS, but i'm getting following error:

/android-ndk-r10c/platforms/android-19/arch-arm/usr/lib/crtbegin_dynamic.o:
  in function _start:crtbrand.c(.text+0x8c): error: undefined reference to 'main'

Please help me to solve this as i have read that google will mandate PIE in upcoming android versions so i want my app to be compatible with ANDROID-L+.

like image 615
ssk Avatar asked Nov 20 '14 06:11

ssk


1 Answers

The really short story is, if you're building shared libraries (as opposed to executables), you don't need to do anything. Libraries that run on older versions of android will keep on working just fine - nothing has changed in Android 5.0 with respect to this.

The almost as short story is, if you're building executables using Android.mk and targeting Android 4.1+, the necessary flags should be added automatically already.

The full story: The reason why you fail when you try to add the -pie flag to LDFLAGS for libraries, is that this flag is only for executables, not for libraries. When building shared libraries, the compiler flag -fPIC (while building individual object files, if running the compiler manually - Android.mk and ndk-build takes care of this automatically) may be needed on some architectures, but you will notice that it is needed because the linker will refuse to produce a shared library if it's needed and you haven't set it. Thus, if you have an issue you will know already because it will fail to build - if you've built it successfully you don't have any issue.

Similarly when building executables, you need to add -fPIE when building the object files, and -fPIE -pie when linking the executables. Android.mk and ndk-build will take care of this automatically, if your APP_PLATFORM is android-16 (Android 4.1) or higher. Here's the big gotcha - executables built with -pie will only work on android-16 or higher, while executables built without -pie won't work on android-21 (Android 5.0). So there's a grace period here, Android 4.1 to 4.4 will run any executable just fine, while you explicitly need a version without -pie for the older ones and another version with -pie for the newer ones.

If you need to target Android versions prior to 4.1 as well, see https://stackoverflow.com/a/26422855/3115956 for an explanation on how to easily build two versions of your executable.

like image 174
mstorsjo Avatar answered Sep 30 '22 04:09

mstorsjo