- Всего лишь меняем модель эмулятора Android устройства
- Пролог
- Дисклеймер
- Зачем это нужно?
- Достаем build.prop
- Редактируем build.prop
- Запускаем эмулятор с доступом на перезапись системных файлов
- Активируем доступ на перезапись системных файлов
- Редактируем правильный build.prop
- Подводим итоги
- mvaisakh / Bringup.md
Всего лишь меняем модель эмулятора Android устройства
Пролог
Казалось бы, на первый взгляд весьма простая задача. Некоторые читатели могли еще в те бородатые времена лазить по всяким 4пда, рутить свой сенсорный самсунг, менять содержимое файла build.prop и показывать наивным ламерам свой iPhone 15+ Max Pro. Однако, как оказалось, и как оно часто бывает, не все так просто и здесь есть свои подводные камни. Статья призвана помочь простым работягам избежать все кочки да ямы на пути к своей цели!
Дисклеймер
Сразу предупрежу, что люблю писать подобные статьи довольно подробно, не ради объема и многобукав, а ради максимального погружения в проблему и способ ее решения. Обратите внимание, что я работаю на macOS, поэтому все команды в терминале будут ориентированы под данную ОС. Также, следует отметить, что проворачиваю все это для API 30, то есть для самого последнего на момент написания статьи. Как говорят интернеты, сложности по этой теме начались с API 29.
Зачем это нужно?
Предполагаю, что у вас, дорогой читатель, есть на это своя веская причина, иначе не стали бы вы этим заниматься. Наиболее вероятно, что у вас, как и у меня есть программная проверка на модель устройства с которого запущено приложение, примерно как здесь. К слову, таким образом можно будет проверять результат наших трудов. Второй же, и более простой способ проверки модели эмулятора будет через настройки девайса в разделе сведений об устройстве:
Ради контекста вкратце расскажу зачем это понадобилось мне. Я получил .apk с багом где-то внутри приложения. Однако пройти дальше первого экрана в этом приложении я не смог. Дело в том, что при запуске, с сервера приходит список разрешенных для запуска устройств и ни мой народный Ксяоми, ни мой эмулятор в этот список не входит. Вот и додумался поменять имя модели устройства на одно из разрешенных. Рутить свой личный телефон не хотелось, поэтому решил шаманить с эмулятором.
Экран не пустивший меня дальше
Достаем build.prop
Как уже говорилось в начале статьи, за имя производителя и модель устройства отвечает системный файл build.prop, который находится в корне устройства в папке system/. Однако при попытке просмотреть его, не говоря уже о редактировании, мы получим отказ в доступе:
Для решения этой проблемы необходимо в терминале обратиться к adb и запросить root права следующей командой: adb root . И вот и первый подводный камень, а именно вывод следующего сообщения: adbd cannot run as root in production builds . Это из-за того что при создании эмулятора мы выбрали вариант с установленными Google сервисами:
Простое решение — создать эмулятор без установленных Google сервисов, после чего повторить команду adb root . После чего в консоли должно появиться сообщение: restarting adbd as root что говорит об успешном проведении операции. Естественно если с самого начала у вас был эмулятор без Google сервисов, то скорее всего с adb root и выше описанной проблемой вы не столкнулись.
Отлично, теперь мы видим содержимое файла build.prop:
Редактируем build.prop
Сохраним файл build.prop в любое удобное место для дальнейшего редактирования выделенной красным области на скриншоте выше. Я сохранил прямо на рабочий стол:
Вносим необходимые изменения. Просмотрев логи запросов и ответов предоставленного мне .apk я нашел приходящий с сервера список разрешенных устройств. То есть, для моих целей нужно поменять два значения на PIXEL 3A XL (как вы поняли, здесь вы можете указывать необходимую именно вам модель):
Сохраняем изменения и заливаем файл обратно на эмулятор. Делается это при помощи команды adb push (кстати, скачать файл с эмулятора можно при помощи adb pull если у вас вдруг аллергия на GUI).
Вводим команду в терминал: adb push build.prop system/
И получаем ошибку:
adb: error: failed to copy ‘build.prop’ to ‘system/build.prop’: remote couldn’t create file: Read-only file system
Вот здесь и начинается самое интересное! По умолчанию эмулятор запускается в режиме чтения системных файлов, без возможности делать записи. Следовательно, что либо поменять без прав на запись у нас не выйдет. Для этого нам необходимо запустить эмулятор в ручном режиме с доступом на запись системных файлов.
Запускаем эмулятор с доступом на перезапись системных файлов
Для этого нужно выполнить следующую команду в терминале (чтобы скорее всего получить еще одну ошибку):
emulator -avd Pixel3XLAPI30 -writable-system -no-snapshot -nocache
итак здесь Pixel3XLAPI30 — это название нашего эмулятора который мы будем запускать в режиме записи, получить это имя можно выполнив команду emulator -list-avds
-writable-system — собственно тот самый флаг и виновник торжества.
-no-snapshot -nocache — просто советую ввести чтобы избавиться от любого возможного мусора, который может помешать нашему плану-капкану.
После у нас либо запустится эмулятор (несколько секунд запускается, так что если тупит то так и должно быть) либо получаем ошибку следующего типа:
PANIC: Missing emulator engine program for ‘x86’ CPU.
Что бы и нам решить с этим нужно в файле .bash-profile (или если у вас zsh то в файле .zshenv) находящийся в корне вашего профиля macOS, добавить дополнительные пути. Вот как это выглядит у меня:
есть такая переменная ANDROIDHOME и с ее участием редактируем переменную PATH:
Чтобы изменения вступили в силу перезапускаем терминал (или вводим source
/.bash_profile ) (или source
/.zshenv ). Результат можно проверить выполнив команду echo $PATH и убедиться что в переменной PATH появился добавленный нами путь.
Пробуем запустить эмулятор еще раз.
emulator -avd Pixel3XLAPI30 -writable-system -no-snapshot -nocache
Теперь он должен был успешно запустится.
Активируем доступ на перезапись системных файлов
Из описания флага -writable-system:
-writable-system make system & vendor image writable after ‘adb remount’
делаем вывод что теперь нам нужно выполнить adb remount . Для этого открываем новое окно терминала и выполняем сначала команду adb root , что бы adb remount сработало.
После adb remount , будет сообщение что эмулятор нужно перезапустить. Сделать это можно командой adb reboot. Но и здесь не все так просто. Очередной подводный камень об который мы разбили еще один ноготь на пальцах ног. Если сделать adb reboot то все просто напросто зависает НАВСЕГДА. Настолько навсегда, что придется удалять эмулятор и создавать его заново. Интернет и с этим столкнулся и даже баг создали на гуглов. И благо нашлось решение. Чтобы эмулятор не зависал нужно добавить пару команд до adb remount .
Итак по порядку:
Делаем adb root
Теперь делаем adb shell avbctl disable-verification
Если вы вдруг остались в shell то введите exit
Перезагружаем эмулятор adb reboot и ждем
Снова делаем adb root
И вот теперь можно делать adb remount
Ура! Теперь мы можем записывать файлы в системную папку нашего эмулятора. Можем пушнуть наш отредактированный build.prop файл: adb push build.prop system/ . Сделаем adb reboot и убеждаемся что ничего не поменялось… Имя модели не изменилось.
Редактируем правильный build.prop
Вернемся к началу и заметим, что значения ro.product.product.name и ro.product.product.model не соответствует тому, что отображается в настройках устройства. Изучив структуру системных папок я заметил, что существует несколько файлов build.prop, которые располагаются в папках: system, system_ext, vendor и product. Эмпирическим методом я скачивал, редактировал и пушил обратно каждый из этих файлов. В конце концов ключевым оказался файл в папке product. Отредактировав его я наконец-то смог изменить название модели эмулятора устройства!
Подводим итоги
Наконец-то я смогу запустить приложение и воспроизвести баг. Подумал я…
Теперь я уперся в то, что запускаю приложение якобы с рутованого девайса (ну да есть такой грешок). И дело даже не в команде adb root , ведь команда adb unroot не помогла. Что ж, опускать руки уже поздно, придется что-то придумать.
О том, как я обходил проверку на рутованность устройства я расскажу в следующей своей статье. Немного реверс инжиниринга и даже такая популярная библиотека как RootBeer не проблема.
Данной статьей я стремился собрать как можно больше проблем по этому вопросу и изложить все в форме step-by-step. Спасибо за ваше внимание и очень надеюсь, что статья оказалась полезной!
Источник
mvaisakh / Bringup.md
A small Device Tree Bringup Guide
So, you guys might be wondering, how do these «Developers» get your favourite Custom roms, such as LineageOS, Paranoid Android etc., to their own devices. Well I’m here to Guide you on how to do it, specifically on how to bringup or make your own device tree from scratch or adapting.
Gist of this Guide: This is for people with genuine interest in Android OS porting/development. After going through this guide, you should be able to do a total device tree bringup on your own.
Prerequisite: Certain requirements are to be met before you start with this amazing journey.
A brain (The most important part)
A computer/server powerful enough to build android roms (Out of the scope of this guide, though you should check out minimum specifications required to build android from AOSP)
Basic text editing.
A way around Android Build system
Familiarity with Linux/MacOS Command Line Interface
Note: I assume that you already know about Linux directories and Android Build System (How Android.mk works, etc.), which to be explained is out of the scope of this guide.
Note 2: This guide applies to devices that were launched with Project Treble enabled (Android Oreo 8.0+), devices launched without it, are not supported on this thread.
Note 3: I’d be specifically talking about a Qualcomm Device (Snapdragon SDM660 based device, launched with Android Oreo 8.1.0) as a reference on this guide. I’m really not experienced with MediaTek or other SoCs device trees , if anyone knows about them, feel free to add a reply to this thread.
Note 4: This guide uses Paranoid Android as the Android Rom Build System. Each and every rom has a different/unique base. This rom here is based on CodeAuroraForum (CAF) Collaborative Project.
For refreshing, android device trees are certain bits of makefile code (also has certain other parts), that allows the Android Build system to recognise the target device specifications to build for, and what all to be built with it.
According to the Google’s conventions, a device is usually placed in a specific location:
There’s a script located in device/common to populate the basic makefiles according to the format I specified above. But, it’s better to do it manually to have a better understanding and learning on how to do it. Understanding Basic Structure of the device tree
When we look at certain device trees, there are certain files and folders we come across, as you can see here
Let’s break these down:
- Android.mk: This is the most basic makefile definition for any path to be included in the android build system. This makefiles calls for all other makefiles present in the directory and subdirectories of the device tree. The basic use of this specific makefile is to guard the device tree makefile when not building for our target device.
- BoardConfig.mk: This contains the Board (SoC/Chipset) specific definition, such as the architecture (arm, arm64, x86, etc.), required build flags and kernel build flags. The flags in these aid during building.
- device.mk: This makefile contains all the build targets and copy specifications (Such as audio configs, feature configs, etc.). If you want a certain package to be built inline with android rom builds, this where you’d want to define it. The vendor tree makefiles are also called from here.
- README.md: Contains the basic info about the device. It’s always good to have documentation.
- config.fs: Read more about it on AOSP.
- extract-files.sh, setup-makefiles.sh & proprietary-files.txt: These files are linked to each other. These are used to extract proprietary blobs from a device and/or from a stock rom dump. Proprietary-files.txt is a list of proprietary (Non-opensource or blobs with proprietary OEM modifications) binaries, which is to be extracted and pushed to vendor tree. Read more about it from LineageOS Wiki.
- props.mk or any .prop: These contain the specifications needed for build.prop or commonly known as runtime properties.
- framework-manifest.xml: These are HIDL manifest required by the system framework features and HAL features to work. Read more about them at AOSP.
- rootdir directory: This contains the major init scripts that are executed during boot time. These are usually found in etc/ dir of /system and /vendor partition.
- sepolicy directory: This folder contains the specific SELinux policies that are required for the Mandatory Access Control (MAC). Read more about it on AOSP.
- overlay: This is an important directory. This contains all the framework additions and removals (Since the android framework is largely based on Java, Kotlin and XML, framework configs are controlled from xmls in overlays rather than flags in BoardConfig.mk).
- aosp_device-name.mk: This is a common makefile found in most AOSP trees. This specific makefile defines device name and manufacturer and build product details. This makefile for my device can be found in Paranoid Android vendor repo (As I mentioned earlier, every rom has their base, which can also mean they have their own way of including device trees)
- AndroidProducts.mk: This makefile includes the device specific makefiles, i.e., the above mentioned aosp_device codename.mk on lunching (term used to initialise device trees for build). This makefile also defines the lunch target (Android 10+).
Now that we know what the Android Device tree are made up of, let’s move on ahead with actually getting our device tree up!
You’ll need to figure out the codename of the device by looking at the build number or reading the build.prop or checking out the stock rom dump.
Since I have a qualcomm device, I started digging into CAF OSS board trees, they have certain codenames for their boards (sdm660 is called falcon), you should be able to find them by a google search. If you can’t find your Board OSS tree, there’s a high chance that it uses a major board type for your specific board (eg., msm8937 uses thorium trees, and since then, sdm450 etc., have used thorium as their base tree). You should take a look at the Board trees present here.
Now my tree here is falcon_64 (64 suffix is here because it’s an arm64 device, your board may or may not have it). Open the OSS Board Tree git repository, and use the tag/branch that matches your android version that you want to bring up. note: CAF tags starting with LA.UM.7.x are Android 9.0 pie, LA.UM.8.x are Android 10, and so on.
Now what we need to do is, create the above mentioned files in the device tree. (It’s better to initialise a repository beforehand)
Starting with Android.mk, we’d need to add the guard conditions (using ifeq ) that should be like:
This means that only if the TARGET_DEVICE variable is set to your device, it will start including this device tree, else this tree would be ignored.
My device’s codename here is X01BD
You should also add an inclusion command so that all other makefiles in the sub directory are included, such as:
Basic Android.mk structure is done!
Moving on to BoardConfig.mk, we need to add architecture specifications, this is where the OSS Board Tree comes in handy, as you can just take all the flags from there. So, almost all the BoardConfig flags are written in a specific format, i.e.,
Note: The ‘#’ here is a comment.
Copy most of the flags from the Board OSS tree, for reference use my BoardConfig to check what to copy and what not to copy. Most of the flags should be similar. Note: Kernel flags may or may not be same across different boards. Make sure you get the proper ones. And additional flag that you might want to add is
This is to allow the selinux to be permissive and help us boot avoiding selinux shenanigans. You should also look into other .mk files for specific flags in the Board OSS tree.
Источник