- ABI Management
- On this page
- Supported ABIs
- armeabi
- armeabi-v7a (armeabi-v7a-hard)
- armeabi-v7a-hard
- arm64-v8a
- x86_64
- mips64
- Generating Code for a Specific ABI
- ABI Management on the Android Platform
- Native code in app packages
- Android Platform ABI support
- Automatic extraction of native code at install time
- Русские Блоги
- Анализ Android ABI
- Концепция Android ABI
- Связь между ABI и CPU
- Проблемы при использовании
- .so файл, поместите в каталог ABI с низким приоритетом
- Файлы .so помещаются в каталог ABI с высоким приоритетом.
- Приоритет файлов ABI в нескольких сторонних SDK различается.
- Важные правила so файлов
- Совместимость с NDK
- Меры предосторожности
ABI Management
On this page
Different Android handsets use different CPUs, which in turn support different instruction sets. Each combination of CPU and instruction sets has its own Application Binary Interface, or ABI. The ABI defines, with great precision, how an application’s machine code is supposed to interact with the system at runtime. You must specify an ABI for each CPU architecture you want your app to work with.
A typical ABI includes the following information:
- The CPU instruction set(s) that the machine code should use.
- The endianness of memory stores and loads at runtime.
- The format of executable binaries, such as programs and shared libraries, and the types of content they support.
- Various conventions for passing data between your code and the system. These conventions include alignment constraints, as well as how the system uses the stack and registers when it calls functions.
- The list of function symbols available to your machine code at runtime, generally from very specific sets of libraries.
This page enumerates the ABIs that the NDK supports, and provides information about how each ABI works.
Supported ABIs
Each ABI supports one or more instruction sets. Table 1 provides an at-a-glance overview of the instruction sets each ABI supports.
Table 1. ABIs and supported instruction sets.
ABI | Supported Instruction Set(s) | Notes |
---|---|---|
armeabi | | No hard float. |
armeabi-v7a ( armeabi-v7a-hard) | | Hard float when specified as armeabi-v7a-hard . Incompatible with ARMv5, v6 devices. |
arm64-v8a | | |
x86 | | No support for MOVBE or SSE4. |
x86_64 | | |
mips | | Uses hard-float, and assumes a CPU:FPU clock ratio of 2:1 for maximum compatibility. Provides neither micromips nor MIPS16. |
mips64 | |
More detailed information about each ABI appears below.
armeabi
This ABI is for ARM-based CPUs that support at least the ARMv5TE instruction set. Please refer to the following documentation for more details:
The AAPCS standard defines EABI as a family of similar but distinct ABIs. Also, Android follows the little-endian ARM GNU/Linux ABI.
This ABI does not support hardware-assisted floating point computations. Instead, all floating-point operations use software helper functions from the compiler’s libgcc.a static library.
The armeabi ABI supports ARM’s Thumb (a.k.a. Thumb-1) instruction set. The NDK generates Thumb code by default unless you specify different behavior using the LOCAL_ARM_MODE variable in your Android.mk file.
armeabi-v7a (armeabi-v7a-hard)
This ABI extends armeabi to include several CPU instruction set extensions. The instruction extensions that this Android-specific ABI supports are:
- The Thumb-2 instruction set extension, which provides performance comparable to 32-bit ARM instructions with similar compactness to Thumb-1.
- The VFP hardware-FPU instructions. More specifically, VFPv3-D16, which includes 16 dedicated 64-bit floating point registers, in addition to another 16 32-bit registers from the ARM core.
Other extensions that the v7-a ARM spec describes, including Advanced SIMD (a.k.a. NEON), VFPv3-D32, and ThumbEE, are optional to this ABI. Since their presence is not guaranteed, the system should check at runtime whether the extensions are available. If they are not, you must use alternative code paths. This check is similar to the one that the system typically performs to check or use MMX, SSE2, and other specialized instruction sets on x86 CPUs.
For information about how to perform these runtime checks, refer to The cpufeatures Library. Also, for information about the NDK’s support for building machine code for NEON, see NEON Support.
The armeabi-v7a ABI uses the -mfloat-abi=softfp switch to enforce the rule that the compiler must pass all double values in core register pairs during function calls, instead of dedicated floating-point ones. The system can perform all internal computations using the FP registers. Doing so speeds up the computations greatly.
Although the requirement to use core register pairs produces a modest performance hit, it ensures compatibility with all existing armeabi binaries. If you need the additional performance, you can specify your ABI as armeabi-v7a-hard instead. Doing so allows you to use hard floats, while still linking with Android native APIs that use softfp . For more information, refer to the comments in $NDK/tests/device/hard-float/jni/android.mk .
Note: You cannot specify APP_ABI as both armeabi-v7a and armeabi-v7a-hard . In either case, the build system places the shared libraries in the armeabi-v7a/ directory.
armeabi-v7a-hard
This variant of the armeabi-v7a ABI is unique to the NDK. The NDK build system adds the following flags in addition to those that it uses for the armeabi-v7a ABI:
The compiler compiles all code with hard-float, and links it with libm_hard.a . This math library is the same one as libm.a , except that it follows hard-float ABI conventions. In the APK, the generated shared libraries reside in /lib/armeabi-v7a/ .
arm64-v8a
This ABI is for ARMv8-based CPUs that support AArch64. It also includes the NEON and VFPv4 instruction sets.
For more information, see the ARMv8 Technology Preview, and contact ARM for further details.
This ABI is for CPUs supporting the instruction set commonly referred to as «x86» or «IA-32». Characteristics of this ABI include:
- Instructions normally generated by GCC with compiler flags such as the following:
These flags target the the Pentium Pro instruction set, along with the the MMX, SSE, SSE2, SSE3, and SSSE3 instruction set extensions. The generated code is an optimization balanced across the top Intel 32-bit CPUs.
For more information on compiler flags, particularly related to performance optimization, refer to GCC x86 performance hints.
The ABI does not include any other optional IA-32 instruction set extensions, such as:
You can still use these extensions, as long as you use runtime feature-probing to enable them, and provide fallbacks for devices that do not support them.
The NDK toolchain assumes 16-byte stack alignment before a function call. The default tools and options enforce this rule. If you are writing assembly code, you must make sure to maintain stack alignment, and ensure that other compilers also obey this rule.
Refer to the following documents for more details:
x86_64
This ABI is for CPUs supporting the instruction set commonly referred to as «x86-64.» It supports instructions that GCC typically generates with the following compiler flags:
These flags target the x86-64 instruction set, according to the GCC documentation. along with the MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, and POPCNT instruction-set extensions. The generated code is an optimization balanced across the top Intel 64-bit CPUs.
For more information on compiler flags, particularly related to performance optimization, refer to GCC x86 Performance.
This ABI does not include any other optional x86-64 instruction set extensions, such as:
You can still use these extensions, as long as you use runtime feature probing to enable them, and provide fallbacks for devices that do not support them.
Refer to the following documents for more details:
This ABI is for MIPS-based CPUs that support at least the MIPS32r1 instruction set. It includes the following features:
- MIPS32 revision 1 ISA
- Little-endian
- O32
- Hard-float
- No DSP application-specific extensions
For more information, please refer to the following documentation:
The MIPS-specific documentation is available here, with further information here.
mips64
This ABI is for MIPS64 R6. For more information, see MIPS64 Architecture.
Generating Code for a Specific ABI
By default, the NDK generates machine code for the armeabi ABI. You can generate ARMv7-a-compatible machine code, instead, by adding the following line to your Application.mk file.
To build machine code for two or more distinct ABIs, using spaces as delimiters. For example:
This setting tells the NDK to build two versions of your machine code: one for each ABI listed on this line. For more information on the values you can specify for the APP_ABI variable, see Android.mk.
When you build multiple machine-code versions, the build system copies the libraries to your application project path, and ultimately packages them into your APK, so creating a fat binary. A fat binary is larger than one containing only the machine code for a single system; the tradeoff is gaining wider compatibility, but at the expense of a larger APK.
At installation time, the package manager unpacks only the most appropriate machine code for the target device. For details, see Automatic extraction of native code at install time.
ABI Management on the Android Platform
This section provides details about how the Android platform manages native code in APKs.
Native code in app packages
Both the Play Store and Package Manager expect to find NDK-generated libraries on filepaths inside the APK matching the following pattern:
Here, is one of the ABI names listed under Supported ABIs, and is the name of the library as you defined it for the LOCAL_MODULE variable in the Android.mk file. Since APK files are just zip files, it is trivial to open them and confirm that the shared native libraries are where they belong.
If the system does not find the native shared libraries where it expects them, it cannot use them. In such a case, the app itself has to copy the libraries over, and then perform dlopen() .
In a fat binary, each library resides under a directory whose name matches a corresponding ABI. For example, a fat binary may contain:
Note: ARMv7-based Android devices running 4.0.3 or earlier install native libraries from the armeabi directory instead of the armeabi-v7a directory if both directories exist. This is because /lib/armeabi/ comes after /lib/armeabi-v7a/ in the APK. This issue is fixed from 4.0.4.
Android Platform ABI support
The Android system knows at runtime which ABI(s) it supports, because build-specific system properties indicate:
- The primary ABI for the device, corresponding to the machine code used in the system image itself.
- An optional, secondary ABI, corresponding to another ABI that the system image also supports.
This mechanism ensures that the system extracts the best machine code from the package at installation time.
For best performance, you should compile directly for the primary ABI. For example, a typical ARMv5TE-based device would only define the primary ABI: armeabi . By contrast, a typical, ARMv7-based device would define the primary ABI as armeabi-v7a and the secondary one as armeabi , since it can run application native binaries generated for each of them.
Many x86-based devices can also run armeabi-v7a and armeabi NDK binaries. For such devices, the primary ABI would be x86 , and the second one, armeabi-v7a .
A typical MIPS-based device only defines a primary abi: mips .
Automatic extraction of native code at install time
When installing an application, the package manager service scans the APK, and looks for any shared libraries of the form:
If none is found, and you have defined a secondary ABI, the service scans for shared libraries of the form:
When it finds the libraries that it’s looking for, the package manager copies them to /lib/lib .so , under the application’s data directory ( data/data/
If there is no shared-object file at all, the application builds and installs, but crashes at runtime.
Источник
Русские Блоги
Анализ Android ABI
Концепция Android ABI
Полное название ABI: Application binary interface (двоичный интерфейс приложения), определяет набор правил, которые позволяют скомпилированным двоичным кодам объектов работать во всех операционных системах, совместимых с ABI, без изменений.
В разных телефонах Android используются разные процессоры, поэтому для взаимодействия необходимо предоставить соответствующие правила взаимодействия с двоичным интерфейсом (то есть соответствующие файлы ABI).
Некоторые процессоры могут поддерживать несколько правил взаимодействия, но это совместимо за счет производительности.
Основная архитектура ABI
- armeabiv-v7a: процессоры ARM 7-го поколения и выше. Его используют большинство устройств Android, выпущенных после 2011 года.
- arm64-v8a: 8-е поколение, 64-битный процессор ARM, несколько устройств, Samsung Galaxy S6 — одно из них.
- armeabi: 5-е и 6-е поколения процессоров ARM в основном используются в первых мобильных телефонах.
- x86: Больше используются планшеты и симуляторы.
- x86_64: 64-битный планшет.
Связь между ABI и CPU
Когда приложение установлено на устройстве, будет установлен только файл .so, соответствующий архитектуре ЦП, поддерживаемой устройством. Если поддерживается несколько архитектур ABI, он будет следовать приоритету
Конкретные типы поддержки следующие:
ARMv5(CPU):armeabi(ABI)
ARMv7:armeabi,armeabi-v7a
ARMv8:armeabi,armeabi-v7a,arm64-v8a
MIPS:mips
MIPS64:mips,mips64
x86:x86(1),armeabi(2),armeabi-v7a(3)
x86_64:armeabi,x86,x86_64
Видно, что большинство процессоров имеют прямую совместимость, но при выборе ABI будет приоритет.
Например, для процессоров X86 предпочтительнее использовать пакет .so в каталоге x86. Если он существует, другие поддерживаемые архитектуры ABI не будут установлены; если нет каталога x86, будет выбран .so в каталоге armeabi-v7a, и будет выбран последний. Выберите файл .so в каталоге armeabi.
ps: Хотя устройства X86 могут запускать библиотеку so под armeabi, производительность может быть потеряна, и нет гарантии, что сбоев не произойдет, особенно если есть библиотеки, созданные небольшими компаниями.
Проблемы при использовании
.so файл, поместите в каталог ABI с низким приоритетом
Архитектура процессора устройства — ARMv7, а файл ABI — armeabi-v7a, но он помещается в каталог armeabi.
1. Если в проекте есть каталог armeabi-v7a и в нем нет библиотеки so, ARMv7 сначала загружает каталог armeabi-v7a, а если нет соответствующей библиотеки so, будет сообщено об ошибке.
2. В проекте есть только каталог armeabi. ARMv7 одновременно загрузит каталог armeabi и библиотеку so в каталог, что эквивалентно загрузке библиотеки armeabi rule so. Из-за функции прямой совместимости он не будет сообщать об ошибке и может работать, но Производительность будет потеряна.
Файлы .so помещаются в каталог ABI с высоким приоритетом.
Архитектура ЦП устройства — ARMv7, а файл ABI — armeabi, но он помещается в каталог armeabi-v7a.
Может загружаться, но можно ли пользоваться? Я тоже не уверен. Поскольку библиотека so armeabi может не обязательно поддерживать правила взаимодействия с интерфейсом, установленные armeabi-v7a.
Приоритет файлов ABI в нескольких сторонних SDK различается.
Приоритет файлов ABI в двух сторонних SDK различается. Когда мобильный телефон загружен и работает, библиотека с низким приоритетом не загружается.
Архитектура процессора моего мобильного телефона — ARMv7, и в проекте используются два сторонних SDK: Enterprise A и Enterprise B.
Предприятие A: ABI-файл — это armeabi-v7a, поместите его в каталог armeabi-v7a.
Предприятие B: файл ABI — это armeabi-v5te, поместите его в каталог armeabi.
При запуске вы обнаружите, что после запуска происходит сбой, и появляется следующая информация журнала.
Это связано с тем, что низкий приоритет, то есть пакет so предприятия B, не загружен, и его нельзя использовать в обычном режиме, что приводит к ошибке.
Решение:
1. Используйте файлы ABI с одинаковым приоритетом и поместите файлы ABI в каталог ABI с тем же приоритетом.
Предприятие A: ABI-файл — это armeabi-v5te, он находится в каталоге armeabi.
Предприятие B: файл ABI — это armeabi-v5te, поместите его в каталог armeabi.
или
Предприятие A: ABI-файл — это armeabi-v7a, поместите его в каталог armeabi-v7a.
Предприятие B: файл ABI — armeabi-v7a, поместите его в каталог armeabi-v7a.
2. Используйте файлы ABI с разными приоритетами и помещайте файлы ABI в каталоги ABI с одинаковым приоритетом. Обычно это не рекомендуется.
Предприятие A: ABI-файл — это armeabi-v7a, но он находится в каталоге armeabi.
Предприятие B: файл ABI — это armeabi-v5te, поместите его в каталог armeabi.
или
Предприятие A: ABI-файл — это armeabi-v7a, поместите его в каталог armeabi-v7a.
Предприятие B: файл ABI — это armeabi-v5te, но он помещается в каталог armeabi-v7a.
Важные правила so файлов
При работе с файлами .so существует простое, но неизвестное важное правило.
Вы должны предоставить как можно больше файлов .so, оптимизированных для каждого ABI.
Совместимость с NDK
При использовании NDK выберите платформу компиляции, соответствующую minsdkVersion приложения, поскольку NDK имеет обратную совместимость.
Меры предосторожности
Таким образом, все папки ABI должны быть согласованы
Если наше приложение решает поддерживать несколько ABI, мы должны обратить особое внимание: для этого в каждом ABI поддерживается либо все, либо ни один. Он не должен смешиваться, но должен предоставлять соответствующий файл .so для каждого каталога ABI.
Источник