Сборка 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, то может проявиться такая ошибка:
Источник
Running Android on a Mac
Android is a popular mobile operating system that has a wide library of apps, some of which are useful on the desktop. Luckily, because Android is open source, it can be run on just about any device, including a Mac.
In order to run a full install of Android on a Mac, you’ll need to set up and install an Android virtual machine.
And though there’s a ton of virtualization software available for the Mac, I’ll you how to create an Android virtual machine using Virtualbox, a free open-source piece of virtualization software by Oracle.
Installing Android on a Mac
To start, download Virtualbox for OS X, free of charge, and open the downloaded image. Run the Virtualbox.pkg package and follow the on-screen prompts to install the app on the Mac.
Download Android for x86, a modified version of Android that’s developed to run on Intel-based computers. Do this by navigating to the Android for x86 website and finding the version of Android you’d like to install from the list of ISOs.
I’ll be installing the Android 4.4 for x86 RC2 in this tutorial because it is, at the time of writing this tutorial, the most recent version of Android for x86.
Setting Up an Android Virtual Machine
Navigate to the Applications folder and launch Virtualbox. Look towards the upper left-hand corner of the application and click on the blue New button.
Giving the new virtual machine a name and selecting its type.
You will be prompted to give the new virtual machine a name, and to select the type of virtual machine, and its version of software.
Name the machine whatever you’d like, select Linux from the Type drop-down menu, and select Other (32-bit) from the Version drop-down menu.
Click the Continue button from the lower right-hand side of the menu to continue the installation process.
Choose how much memory you’d like to allocate by using the slider that is located towards the center of the window or by typing it into the text-box located on the right-hand side of the window. Keep in mind that the virtual machine will run like a stand-alone Android device, so it’s best to allocate 1GB or more of memory to the virtual machine.
Look towards the center of the Hard Drive menu and select the radio button that’s located to the left of the Create a virtual hard drive now button and click the Create button from the lower right-hand-corner of the menu.
Make sure the VDI radio button is selected from the Hard drive file type menu and click the Continue button.
Select the the Fixed Sized button from the bottom of the Storage on a physical hard drive window and click Continue to continue to the virtual hard drive section of installation.
Sizing and naming the Android virtual machine’s drive.
The virtual hard drive will be used to store the Android operating system and all content downloaded to the VM, so size the virtual drive accordingly. I recommend sticking somewhere between 8-10GB for light use, though you can make it bigger if you’d like.
Size the drive using the slider towards the center of the center of the window and click the Create button. When creating the virtual hard drive, it is normal for the Mac to beach ball for a few seconds.
Installing Android to the Virtual Machine
Look towards the left-hand side of the Virtualbox window, click on the new Android virtual machine, and click the green Start button from the top of the window.
Selecting the Android ISO you’d like to install to the newly created virtual machine.
At the bottom right-hand corner of the window and click on the yellow folder button. Select the Android ISO from the pop-up menu and click the Open button from the lower right-hand corner of the screen. The virtual machine will now boot into Android’s installer.
Note: When you first click the mouse pointer into the new virtual machine, you’ll be notified that your mouse is about to be used to control the virtual machine, and that to use your mouse and keyboard to control the Mac, you must tap the Host key on the keyboard. By default, the host key is the left Command key.
Creating a new partition on the virtual hard drive.
Select the Install Android-x86 To Harddisk option that’s located towards the bottom of the window using the arrow keys on the keyboard.
From the next window, click on the Create/Modify partitions button and look towards the bottom of the screen at the list of partition options.
Select the New button to create a partition and press the Return key twice to make it the primary partition as well as allow it to use the entirety of the virtual drive’s space.
Select the Write button from the list of partition options and the installation will fail (this is a good thing).
Selecting the partition you’d like to format.
Use the arrow keys to select the Quit button from the list of options, and you’ll be redirected back to the Choose Partition window.
Select the sda1 Linux Swap drive and press the Return key on the keyboard where you will be brought to a list of format types. Key down to the ext3 option and press the Return key on the keyboard.
The installer will then prompt you to install boot loader GRUB and ask you if you’d like to install /system directory as read-write. Respond Yes to both of these prompts.
From the final screen of the Android installer, select the Reboot button. Once the Android installation restarts, look towards the upper left-hand-corner of the virtual machine’s window and click the red X menu button and, from the drop-down menu, select the Power-off button.
Removing the Android ISO from the storage tree.
Now, open the Virtualbox window and click into the Android virtual machine from the menu bar on the left-hand side of the screen.
Towards the center of the Virtualbox window, click the Storage header. From the storage tree located towards the center of the window, select the option that’s labeled the same as the Android ISO you downloaded earlier.
Towards the right-hand side of the window, click on the small CD icon and select the Remove disk from virtual drive option from the drop-down menu.
Using Android on the Mac
Boot the virtual machine by clicking the green Start button from the top of the Virtualbox window. Your new virtual machine will then boot into Android.
Using Android on the Mac is simple. Clicking into the Android window will let you control the Virtual Machine using the keyboard and mouse and the back, menu, and home buttons are available for use from the bottom of the screen. To exit the VM and use your keyboard and mouse to control the Mac, tap the left Command key on the Mac’s keyboard.
When controlling the Android virtual machine, you can use your trackpad or mouse to control Android as you would on a touch screen. For example, to scroll through menus, just click and drag, and to tap a button, click on it.
Disabling mouse integration in Virtualbox.
Note: If you have issues getting the mouse clicks to register in Android, click on the Machine button from the toolbar and select Disable Mouse Integration from the drop-down menu. Click back into the Android window and press the Capture button from the pop-up window.
Upon first boot, Android will greet you with a few setup screens. Follow the prompts on these screens, setting up your language settings, Google account, and other information.
Note: Skip the Wi-Fi setup process as the Android virtual machine will use the Mac’s existing network settings to access the internet.
Accessing the app drawer in the Android VM.
To access all pre-installed apps on the Android virtual machine, click on the App Drawer button that’s located towards the bottom of the menu to pull up the Android app launcher.
If you installed the Android 4.4 ISO I noted earlier in the tutorial, you can download new apps and content to the Android VM using the included Google Play app. To do this, launch Google Play from the app drawer and search the store for new apps.
Unfortunately, because the Android Virtual Machine is running on an Intel chipset, it will have compatibility issues with certain applications on Google Play. Finding apps that support x86 is hit or miss, so make sure you put your favorite x86-compatible app in the comments.
Enjoy Using Android on a Mac
In this tutorial I’ve shown you how to install and use Android on a Mac.
Aside from some app incompatibility issues, the new virtual machine can be used to do just about anything you’d do on a standard Android device: from browsing the web to editing documents in Google Drive.
Источник