Build android on mac

Build android on mac

Disclaimer: it’s translation of my article that was written in Russian some time ago. All mentioned versions of software are outdated now. But anyway, it can be helpful :).

For one of my projects I needed to improve original Android sources to create firmware for specific hardware. The version of Android was chosen quite old — AOSP 4.0.4 but it was necessary because stable version of sources for our hardware was based on this version. The next issues was my work environment. Besides Android development I’m working with iOS so I have to use Mac OS X and Xcode as development environment.

The main issue in my case was broken AOSP build system for outdated versions of OS. While building of master branch is simple task, building of older versions of Android under new Mac OS X demands some patience and fixing a few bugs in build system.

My work environment looks like this:

  • AOSP 4.0.4 r1.1 (alongside with 4.0.3 and 4.1.1)
  • Mac OS X 10.7.5
  • Xcode 4.6.3 and command line tools
  • GNU Make 3.81

All essential moments and complications of AOSP build process is described in official documentation. The documentation gives us information that Mac OS 10.5 or 10.6 are necessary to build 4.0.x branch, also Xcode 3.14 is recommended version of Xcode. Additionally, in the «Known issues» section, mentioned that Mac OS 10.7 isn’t supported for 4.0.x branch.

I was using Mac OS and Xcode for iOS development and I had no intention to move back on previous versions of software. As well as I wanted to solve this quest but not to avoid it.

Solution

The initial configuration is well described in official documentation and was set up on my computer: created case-sensitive disk image, installed necessary tools, downloaded sources of Android. And then I ran build with full-eng profile.

Bellow I give descriptions of the issues and solutions for them. They can appear fully or partially, it’s related to used version of AOSP and current build environment. In addition to AOSP 4.0.4, 4.0.3 and 4.1.1 were checked too. There is the following trend: the more newer version of AOSP than less issues appear but first 2 issues have place everywhere. Separately necessary to note that emulator will be build correctly and can ne used without problems after all fixes described bellow.

To solve issue with compilator, you need to use the command listed bellow. The vital part is CC=»gcc» CXX=»g++», alongside with these parameters you can use other in any order or combination.

So, will look on the issues what you can see while the building process (besides described in the documentation).

Issue 1
Solution 1

You need to apply the patch https://bugs.webkit.org/show_bug.cgi?id=92264. But this patch will be applied with minor error because of difference in context. It’s necessary to check rej file and remove a few of old lines which cause the error. The target directory for patch is /external/webkit/.

Читайте также:  Тестовое меню у андроида
Important

While project linking, on final stage of building, you can see the following issues:

It happens in relation to changes into CSSParser. Here appears a strange mystery of linker (you won’t see such issues for 4.1.1 version). To fix the issue you need to include any changes to CSSParser (but not a comments, something what compiler will count). I changed definition of this method from cssyyparse(void*) to cssyyparse(WebCore::CSSParser*) or in reverse order. Then you can start rebuild and all will be fine.

Issue 2
Solution 2

Move definitions to file /external/srec/portable/include/PortExport.h from master branch to current branch.

Issue 3
Solution 3

Add library LOCAL_SDL_LDLIBS += /usr/lib/dylib1.o to /development/tools/emulator/opengl/tests/translator_tests/ for /GLES_V2/Android.mk and /GLES_CM/Android.mk.

Issue 4

Different definitions of the method strnlen in system and local files. Unfortunately, I didn’t save log for this issue but you can understand that when see mentioning of strnlen.

Solution 4

Add condition for method strnlen to /external/elfutils/config-compat-darwin.h:

Issue 5

Choosing version of SDK by version of Mac OS to build emulator. It’s without log, similar to previous issue. But you will understand when see mentioning of qemu.

Solution 5

Replace condition for Mac OS version in /external/qemu/Makefile.android:

And add inclusion of libraries for Mac OS:

Issue 6

You can see the following issue if you’ve OS on drive with case-sensitive file system:

Solution 6

The cause of the issue is simple — misprint in the name of .h file. Instead of the capital ‘K’ is used small ‘k’. Usually, this type of the issues won’t appeared because Mac OS installs on drive with case-insensitive file system. To fix the issue you just need to replace letter to the correct one.

Conclusion

It’s better to build Android under Linux systems but not under Mac OS :). You can use virtual box or just use separate installation of Linux on your computer. As I see, Mac OS can only be a partial alternative for AOSP build environment. Especially considering that all variations of build environment are not checked when Android moves further.

Источник

Building Android O with a Mac

Mar 26, 2018 · 6 min read

After spending several hours to analyse dozens of posts and articles to compile Android O MR1 AOSP, I decided to write a short manual to help you to build your AOSP effortlessly 😉

This article is based on Official Android documentation: https://source.android.com/setup/requirements

My Environment

  • OS: macOS Sierra 10.12.5
  • CPU: 2,9 GHz Intel Core i5 (influence the speed compilation)
  • RAM: 8 GB 1867 MHz DDR3 (8GB minimum, recommended 16GB)
  • Disk: 200GB free space (after AOSP sources downloaded — minimum 200GB)
  • Device: Nexus 5X (bullhead)

Setup your Build Environment

  • Install Xcode: https://developer.apple.com/xcode/
  • Install Xcode command line tools with:
  • Install Homebrew with:
  • Install JDK with: https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html
  • Check your Java version:
  • Install GIT with:
  • Install Python with:
  • Install Make with:

Creating a case-sensitive disk image

Case sensitive volume of 200GB with the following command line:

Install tools and libraries via MacPort

Install MacPorts: https://www.macports.org/install.php then type the following command line:

Then create and edit the .bash_profile file with the following code:

Download AOSP source code

To identify the right b ranch to download , check the Build number of the target device. In our case OPM5.171019.017 which isncorresponding to the branch android-8.1.0_r18.

Читайте также:  Htc desire версия android

Warning: when you choose a branch be sure that the branch support the targeted device!

Select the targeted AOSP version with the branch with -b parameter: android-8.1.0_r18

Building ASOP source code

Select the device target with lunch command, then build the sources with make command:

When the build process if finished you get the following message:

Install new Android Build on Device

Connect the Device in USB, enable the Developer Mode, then input the following command lines in you Terminal:

Restore Android Image

To restore an official Android Image please download the target Image and follow the instructions:

  • Download Android Image: https://developers.google.com/android/images
  • Unzip the archive
  • Execute the following command lines:

Rebuild a single package

To rebuild a single package (example: Dialer App) instead of rebuild the entire baseline, use the following command lines:

The output APK path will be prompt by the console, or located at the following path:

How to install it

System UI

Build System UI only:

How to install it

Android Framework

  • Build Framework JAR only: mmm framework/base/
  • Build Framework Resources only: mmm framework/base/core/res/

How to install it

Signing Build

The standard Android build uses four keys, all of which reside in build/target/product/security :

  • testkey: Generic default key for packages that do not otherwise specify a key.
  • platform: Test key for packages that are part of the core platform.
  • shared: Test key for things that are shared in the home/contacts process.
  • media: Test key for packages that are part of the media/download system.

To sign an app with one of the existing key, use the following instruction ( LOCAL_CERTIFICATE) into the associated makefile Android.mk:

Troubleshooting

Can not find Mac SDK or Required minimum for the macosx platform

Download and uncompress the exact missing Mac SDK version into the following directory:

Error: could not find jdk tools.jar

Need to defined $ANDROID_JAVA_HOME used in

Make error — already defined

If you got the following error during the AOSP compilation:

Go to the already defined directory and rename simply the Android.mk file to Android_old.mk

GC overhead limit exceeded

To increase the the heap size use the following command lines:

Case-insensitive filesystem

You are building on a case-insensitive filesystem.

Fatal error file not found

If the following error is raised during the Android building process:

Please check the filename user or lower case. Remember that the Android building process is case-sensitive.

In this case create a symbolic name xt_dscp.h for the original file xt_DSCP.h with the following command lines:

No space left on device

If the case-sensitive partition become full (no free space available):

Open Terminal and increase the partition size:

Missing and no known rule to make it

If the flowing error is raised during a single package compilation thought mm or mmm command:

Compile the bidding library metrics-helper:

Источник

Сборка Android под Mac OS X

Вводная

Для одного из проектов потребовалось заняться доработками оригинального кода Android для создания прошивки под специфичную железку. Версия для сборки была выбрана уже относительно старая — AOSP 4.0.4, но на ней базируется стабильная ветка кода от производителя железки, поэтому условие необходимое. Кроме разработки под Android я занимаюсь разработкой iOS приложений, соответственно работаю под Mac OS X и использую Xcode как одну из сред для разработки.

Читайте также:  Монопод только для андроид

Основной проблемой в моем случае явилось то, что старые версии AOSP ни кем не отслеживаются и новые правки в сборочную систему не вносятся. Поэтому если сборка master’а особой сложности не представляет, то сборка предыдущих версий Android под более свежие версии MacOS требует исправления ряда проблем.

В моем случае рабочее окружение выглядит так:

  • AOSP 4.0.4 r1.1 (а так же 4.0.3 и 4.1.1)
  • Mac OS X 10.7.5
  • Xcode 4.6.3 и command line tools
  • GNU Make 3.81

Все основные моменты и сложности сборки AOSP хорошо описаны в официальной документации. Там же указано что для сборки ветки 4.0.x необходимы MacOS 10.5 или 10.6 и рекомендован Xcode 3.14, а в разделе «Known issues» указано что ветка 4.0.x не совместима с MacOS 10.7.

MacOS и Xcode я использую для разработки и откатываться на предыдущие версии крайне не хотелось. К тому же был чисто спортивный интерес разобраться со сборкой без какого-то кардинального изменения окружения.

Решение

Непосредственно все первоначальные шаги для сборки описаны в документации и были выполнены в соответствии с ней: создан case-sensitive disk image, установлены необходимые утилиты, скачан код Android. Далее была запущена сборка с профилем full-eng.

Ниже я привожу тексты ошибок из консоли и методы исправления. В зависимости от версии AOSP и вашего окружения они могут проявляться все или частично. Большинство решений можно найти в интернете, я привожу лишь краткое описание необходимых действий. Кроме AOSP 4.0.4 также были проверены версии 4.0.3 и 4.1.1. Чем новее версия, тем меньше встречалось ошибок, но первые 2 имели место везде. Отдельно стоит заметить что при внесении описанных изменений, эмулятор собирается корректно и я не встретил проблем с запуском эмулятора указанных в том же официальном «Known issues».

Запуск сборки для решения проблем с компилятором осуществляется командой приведенной ниже. Здесь важная часть CC=«gcc» CXX=«g++», остальными могут быть стандартные параметры в любом порядке и сочетании.

По ходу сборки, не считая описанного в документации, возникали следующие проблемы:

Ошибка 1
Исправление

Применить патч https://bugs.webkit.org/show_bug.cgi?id=92264. Патч ложится с небольшой ошибкой, из-за расхождения контекста, нужно посмотреть rej и удалить пару старых строк, которые не смог убрат патч. Применять патч в директории external/webkit/.

Важно

Во время линковки, на финальной стадии сборки, могут появиться ошибки типа:

В зависимости от того добавляли ли вы изменения в CSSParser. Здесь проявляется некая мистика линковщика (для 4.1.1 версии со сборкой с этими исправлениями таких проблем нет). Для устранения проблемы нужно в CSSParser внести какие-нибудь изменения (считываемые компилятором, т.е. не комментарии). Я менял определение этой функции с cssyyparse(void*) на cssyyparse(WebCore::CSSParser*) или наоборот. Далее запустить пересборку — все пройдет гладко с этого места.

Ошибка 2
Исправление

Перенести определение в файл external/srec/portable/include/PortExport.h из ветки master в нашу.

Ошибка 3
Исправление

Добавить библиотеку LOCAL_SDL_LDLIBS += /usr/lib/dylib1.o в /development/tools/emulator/opengl/tests/translator_tests/ для GLES_V2/Android.mk и GLES_CM/Android.mk.

Ошибка 4

Разное определение функции strnlen в системе и в локальных файлах. К сожалению для этой ошибки лог не записал, но суть будет понятна при упоминании функции strnlen.

Исправление

Добавить условие для функции strnlen в external/elfutils/config-compat-darwin.h:

Ошибка 5

Выбор версии SDK по версии Mac OS для сборки эмулятора. Аналогично предыдущей ошибке без лога, но упоминание эмулятора qemu в логе укажет сюда.

Исправление

Заменить условие для версии Mac OS external/qemu/Makefile.android:

И добавить подключение библиотек для MacOS:

Ошибка 6

Если у вас операционная система стоит на диске с case-sensitive file system, то может проявиться такая ошибка:

Источник

Оцените статью