- 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 arm64-v8a, armeabi-v7a, armeabi, x86 подробное объяснение
- перед началом
- Введение в архитектуру
- Для 64-битных телефонов и 64-битных процессоров
- Конфигурация упаковки
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 arm64-v8a, armeabi-v7a, armeabi, x86 подробное объяснение
Недавно при упаковке с флаттером я столкнулся с ситуацией, когда упаковка не могла быть напечатана. Я долго проверял причину и обнаружил, что это было вызвано отсутствием конфигурации руки. После того, как она была экипирована, она разыгралась. Я воспользовался этой возможностью, чтобы изучить abi с нуля.
перед началом
Прежде чем начать, вам нужно знать lib, libs и т. Д.
1. lib и libs
Ссылки на те, что помещены в lib, включены в библиотеки.
Файлы, помещенные в библиотеки, будут автоматически включены редактором. Так что не ставьте API в библиотеках.
Содержимое библиотеки lib не будет упаковано в APK, содержимое библиотеки li будет упаковано в APK
Два . так библиотека
Библиотека динамических ссылок, скомпилированная из NDK.
Некоторые важные алгоритмы шифрования или базовые протоколы обычно пишутся на языке c, а затем вызываются в java. Это позволяет избежать просмотра исходного кода приложения после декомпиляции.
Три . как хранить так библиотеки
Правильная позиция для размещения файла .so — это два предложения:
• Чтобы уменьшить размер apk, оставьте только две папки armeabi и armeabi-v7a и убедитесь, что число .so в этих двух папках одинаково
• Для стороннего .so, который предоставляет только версию armeabi, сделайте копию в папку armeabi-v7a
Правила хранения так:
Вы должны предоставить .so файлы, оптимизированные для каждого ABI, насколько это возможно, но поддерживаются все или все: вы не должны смешивать их. Вы должны предоставить соответствующий файл .so для каждого каталога ABI.
По вопросам хранения вы можете посмотретьЭта
4. Какова роль armeabi и т. Д. Под libs
хранит библиотеку .so, которая в основном совместима с различными устройствами, а также, как можно сказать, особенно совместима с архитектурой ЦП различных телефонов Android.
Давайте потянем процессор Android
Тип процессора устройства Android (часто называемый «ABI»)
Введение в архитектуру
Ранние системы Android почти только поддерживали архитектуру процессора ARMv5, а затем были разработаны для поддержки семи различных архитектур процессоров: ARMv5, ARMv7 (с 2010 года), x86 (с 2011 года), MIPS (с 2012 года), ARMv8 , MIPS64 и x86_64 (с 2014 года), каждый связан с соответствующим ABI.
Двоичный интерфейс приложения (двоичный интерфейс приложения) определяет, как двоичные файлы (особенно файлы .so) работают на соответствующей системной платформе, от используемого набора инструкций, выравнивания памяти до доступного Библиотека системных функций. В системе Android каждая архитектура процессора соответствует ABI: armeabi, armeabi-v7a, x86, mips, arm64-v8a, mips64, x86_64.
Но последние официальные документы Google удалили mips и armv5, как показано на рисунке:
Анализ каждой версии выглядит следующим образом:
• mips / mips64: редко используется на мобильных телефонах и может игнорироваться (последняя документация Google больше не поддерживается)
• x86 / x86_64: мобильные телефоны с архитектурой x86 будут включать в себя инструмент динамического транскодирования набора инструкций под названием Houdini, предоставляемый Intel для обеспечения совместимости с arm .so, затем рассмотрите x86 1% или менее Доля рынка, две .so, связанные с x86, также незначительны
• armeabi: ARM v5. Это довольно старая версия, в которой отсутствует аппаратная поддержка для вычислений с плавающей запятой, и имеются узкие места в производительности, когда требуются большие объемы вычислений.
• armeabi-v7a: ARM v7
• arm64-v8a: поддержка 64-бит,Текущая основная версияХотя многие блоги в Интернете говорят, что версия v7 является основной версией, я лично протестировал многие мобильные телефоны, все из которых основаны на архитектуре arm64-v8a. Тестовые модели включают Xiaomi 5-Xiaomi 9, Huawei P30, Huawei mate10 и Charm Blue 2. архитектура v8
Запрос командной строки ЦП мобильного телефона:
Нет картины без правды:
Существует только один неизвестный телефон с операционной системой Android 4.3, который использует архитектуру v7.
Для 64-битных телефонов и 64-битных процессоров
ARM64-битный процессор и компьютерный 64-битный процессор — это две совершенно несовместимые концепции: он не является 64-битной нативно совместимой с 32-битными программами, но работает 32 через 32-битную архитектуру, интегрированную в 64-битный процессор. Битовая программа. Проще говоря, он не запускает 32-разрядные программы в 64-разрядной форме, но запускает 32-разрядные программы в 32-разрядной форме.
Поскольку новый 64-разрядный процессор в настоящее время включает в себя две архитектуры, а технология процесса не была улучшена (28 нм), в то же время на мобильных телефонах и планшетах площадь чипа строго ограничена и не может быть чрезмерно увеличена, что приводит к среднему распределению 64-разрядных процессоров ARM. Количество транзисторов в каждой архитектуре резко сократилось, то есть из 32-разрядной архитектуры 64-разрядных процессоров для 32-разрядных процессоров с одинаковыми характеристиками они не только не улучшились, но и производительность снизилась в определенном масштабе. Однако производители процессоров должны объяснить потребителям, как лучше продвигать 64-разрядные системы, поэтому производители должны повысить производительность в других аспектах, чтобы компенсировать потери, вызванные сокращением числа транзисторов ЦП. Например: замените более мощный графический процессор, увеличьте пропускную способность памяти, многоядерный виртуальный одноядерный для повышения производительности одноядерного, совместные поставщики программного обеспечения для работы, чтобы изменить веса работы (повысить оценку GPU, снизить вес процессора) и т. Д. Таким образом, приобретая сильные стороны и избегая недостатков и, наконец, попадающих в руки потребителей, они работают с запущенным программным обеспечением, оно действительно улучшилось, пользователи довольны, карманы производителя также выпирают.
Таким образом, битовый процессор ARM64 более точно называется ARM32 + 64 в строгом смысле слова. По сравнению с битовым процессором ARM32, он имеет место для регресса и возможности для улучшения, но именно из-за регрессии, который стимулировал прогресс ARM Определено, что он внесет смелые и смелые изменения, и это должно быть улучшением. Но действительно ли ARM64 полезен для мобильных телефонов? Я могу только сказать, что это действительно бесполезно в данный момент, но это может произойти в будущем. (Собранный в другом месте) Таким образом, в строгом смысле ARM64-битный процессор более точно называется ARM32 + 64. По сравнению с ARM32-битным процессором он имеет некоторые недостатки и возможности для улучшения, но это из-за Эта регрессия подтолкнула ARM к решимости добиться прогресса, что позволило ему внести радикальные изменения, что, по-видимому, является улучшением. Но действительно ли ARM64 полезен для мобильных телефонов? Я могу только сказать, что это действительно бесполезно в данный момент, но это может произойти в будущем. (Искал в другом месте)
Настоящий 64-разрядный мобильный телефон не просто остается на процессоре. Если его называют 64-разрядным мобильным телефоном только потому, что его процессор 64-разрядный, мы можем без колебаний сказать, что это может быть ложной пропагандой. К счастью, Lenovo Очень умно, когда были выпущены A678t и A805e, они говорили только о телефонах с 64-битным процессором.
«64-разрядный телефон» и «64-разрядный телефон» — это две разные концепции: если процессор содержит 64 архитектурных бита, его можно назвать «64-разрядным процессором» «Мобильный телефон», этот вид мобильного телефона, возможно, не сможет запускать 64-разрядные программы, но используется только для захвата рынка, по сравнению с 32-разрядными мобильными телефонами, преимущество не очевидно.
«64-разрядный мобильный телефон» отличается: он содержит 64-разрядный процессор, 64-разрядную стандартную систему, 64-разрядную виртуальную машину Android и 64-разрядную программу. Это настоящий 64-разрядный мобильный телефон!
Представители Google заявили, что Android уже давно поддерживает 64-разрядные версии, это правда, от Android4.0 до Android4.4, системы Android поддерживают 64-разрядное оборудование, но это Это означает только то, что базовый драйвер поддерживает 64-битные и может работать на 64-битном оборудовании, и ничего более. Однако программное обеспечение, работающее на верхнем уровне, будь то виртуальная машина Dalvik или виртуальная машина ART, является 32-разрядным. Другими словами, до тех пор, пока ваша система мобильной связи работает под управлением Android 4.0-4.4, даже если ваш процессор 64-разрядный, вы можете запускать 32-разрядные программы только на 32-разрядной виртуальной машине, даже если перед вами стоят настоящие 64-разрядные программы, Это не может быть установлено. ,
Однако Google официально объявил об обязательной 64-битной архитектуре в начале этого года.:
Еще в январе этого года (2019 г.) Google выпустил уведомление о том, что с 1 августа этого года перечисленные приложения, помимо предоставления 32-разрядных версий, также должны предоставлять 64-разрядные версия.
Следовательно, больше невозможно принудительно использовать только архитектуру armeabi перед проектом.
Что конкретно означает поддержка 64-битной версии?
Если ваше приложение написано полностью на Java или Kotlin и не содержит никакой встроенной поддержки, то это означает, что приложение уже поддерживает 64-битную версию.
Однако в приложении используется любая встроенная поддержка (например, библиотека), поэтому вам необходимо обеспечить разные версии поддержки этих файлов и разных архитектур ЦП.
Следует отметить, что иногда в нашем собственном коде встроенная поддержка действительно не используется, но в нее включены некоторые сторонние библиотеки, используемые в приложении.
В настоящее время наиболее надежным способом является анализ файла APK, созданного окончательной упаковкой, для определения необходимости обеспечения поддержки 64-разрядной архитектуры.
Конфигурация упаковки
Трещина
Эта команда может быть заключена в соответствии с различными правилами, такими как abi, плотность экрана (например, ldpi, hdpi и т. д.)
Включить включено, а исключить не включено. Каждый элемент, включенный в конфигурацию, будет генерировать пакет apk.
Однако эта конфигурация создаст два пакета, один из которых содержит только библиотеку x86 so, а другой — только библиотеку armabi so. Очевидно, не соответствует потребностям
Фильтр ndk
Эта инструкция может быть настроена для упаковки только той библиотеки, которую вы настраиваете, и она не будет упакована, если она не настроена, что очень гибко.
Эта конфигурация упакует библиотеку so из трех пакетов armeabi, armeabi-v71, arm64-v8a в apk, в отличие от split, которая будет воспроизводить apk для каждого пакета.
Источник