Android rom from zip

Разработка и модификация прошивки для Android телефонов на примере HTC Hero GSM. Часть 1

Причины по которым люди ставят модифицированные версии прошивок различны. Кому-то хочется удивить друга смешной анимацией загрузки, кому-то не хватает определенного функционала (например vpn), кто-то хочет выжать максимум производительности из своего телефона за счет разгона процессора, а кто-то пять месяцев ждет новую версию операционной системы Android для своего любимого HTC Hero.
На данный момент уже существует превеликое множество самых невообразимых сборок для самых различных телефонов на базе Android. Иногда они даже появляются в той или иной форме на Хабре.
Я же хочу Вам рассказать о процессе и особенностях создания кастомной прошивки на основе официальной. Данные знания были получены в процессе разработки одной из не многих отечественных прошивок на базе Android 2.1 для HTC Hero GSM. И более или менее успешно опробованы на себе и других подвернувшихся пользователях одного крупного российского форума.
Не смотря на то, что все нижеследующее было сделано для HTC Hero, данные правила и особенности имеют полную силу для всех телефонов, особенно тех, которые разработаны компанией HTC и используют фирменную оболочку Sense.
Для экспериментов нам понадобится:

  • Android SDK желательно последней версии
  • Утилита apktool для реинжениринга системных приложений
  • Утилиты smali/baksmali для де-оптимизации системных приложений
  • Утилита unyaffs для извлечения системных файлов из образа
  • Скрипт split_bootimg.pl для извлечения ядра и ramdisk-а
  • Утилита testsign для подписывания пакета обновления и отдельных приложений
  • установленное и настроенное JRE
  • телефон с операционной системой Android
  • права суперпользователя и модифицированная подпрограмма восстановления (recovery rom)

Все вышеперечисленное доступно в версиях как для системы Linux так и для Windows. Но в своих примерах я буду ориентироваться на использование Linux.
Конечно же ни root-права ни recovery нам не нужен для того, чтобы начать разработку, однако если мы захотим опробовать наше творение, они нам понадобятся. Для HTC Hero можно использовать RA-hero-v1.6.2.
Наверное, самое время напомнить, что использование неофициальных прошивок лишает нас гарантии, но где наша не пропадала. И несмотря на то, что большинство операций безопасно — всегда нужно четко понимать что и зачем делается, дабы не причинить необратимый вред своему андроиду

Основа

Существует несколько различных подходов к разработке прошивки.

  • Сборка из исходников Android Open Source Project
  • Сборка из исходников проекта CyanogenMod
  • Модификация прошивки, предоставляемой производителем телефона

Несмотря на то, что платформа Android вроде как и является открытой, но в реальных телефонах используются закрытые компоненты. Это и драйверы распространяющиеся в бинарном виде (wifi/gps/fm), и ключевые компоненты системы, такие как Маркет и другие сервисы Google. Также сюда нужно добавить разработки компаний в области интерфейса, такие как HTC Sense, Motoblur, TouchWiz от Sumsung. Это создает местами непреодолимые трудности по разработке прошивки из исходных кодов.
Я предлагаю остановиться на модификации готовых прошивок, предоставляемых вендорами телефонов.
Прошивки для телефонов HTC существуют в двух видах:

  • RUU. Rom Update Utility (Утилита обновления прошивки). Утилита для ОС Windows производящая обновление телефона
  • OTA. Over the Air (Обновление по «воздуху»). Пакет, скачиваемый самим телефоном через wifi/gprs сети, который устанавливается на телефон без какого-либо участия компьютера

Последнее время OTA-обновления состоят из бинарных diff-ов, что несколько осложняет использование оных в качестве основы. Так как это требует наличия конкретного телефона с определенной версией прошивки, что может быть просто невыполнимым, если мы хотим адаптировать прошивку от одного телефона для другого. Либо предполагает долгую и мучительную подтасовку идентификатора телефона с последующим скачиванием обновления без его установки. Причем, возможно, эту процедуру придется повторить несколько раз.
Будем использовать RUU обновление.

Извлечение rom.zip

1. Скачиваем подходящую версию RUU для интересующего нас телефона. Найти которую можно либо на сайте HTC, либо в других источниках. Для HTC Hero воспользуемся, вышедшей в начале июня версией Android 2.1 для оператора Chunghwa (Тайвань)
2. RUU утилита при обновлении телефона прошивает сразу несколько областей:

  • загрузчик boot (hboot)
  • ядро linux + ramdisk (boot)
  • прошивка для радио-модуля (radio)
  • подпрограмма восстановления (recovery)
  • системный раздел (/system)
  • пользовательский раздел (/data)

Однако мы не можем позволить RUU-утилите перезаписать наш любовно установленный загрузчик и recovery. Дабы иметь и далее возможность устанавливать не только официальные прошивки. Для этого нам необходимо извлечь радио/boot/system/data.
В сущности RUU является InstallShield-овским инсталлятором, который несет в себе необходимые нам образы в rom.zip.
Запускаем его и попадаем в заглавный приветственный экран. Не заходя дальше, открываем системную папку %TEMP%, в которой мы видим 2 новые папки, в одной из которых мы найдем файл rom.zip. Копируем в уединенное место и закрываем RUU отменой установки.

Распаковка образов

Распаковав полученный архив и удалив не интересные для нас образы, мы увидим:

  1. $ ls -1 rom
  2. boot.img
  3. Radio_Signed_HERO_63.18.55.06O_6.35.15.01.img
  4. system.img
  5. userdata.img

Телефон несет в себе 512Мб NAND Flash, которые разбиты на следующие логические блоки

  1. $ adb shell cat/ proc / mtd
  2. dev: size erasesize name
  3. mtd0: 00040000 00020000 «misc»
  4. mtd1: 00500000 00020000 «recovery»
  5. mtd2: 00280000 00020000 «boot»
  6. mtd3: 0aa00000 00020000 «system»
  7. mtd4: 08200000 00020000 «cache»
  8. mtd5: 0a5c0000 00020000 «userdata»
Читайте также:  Как перенести профиль андроид

Как мы видим, данные области памяти непосредственно связаны с полученными нами образами. RUU производит запись образов as-is, но мы хотим ведь изменить наполнение системы, поэтому нам необходимо распаковать их.
В качестве файловой системы для NAND в android используется yaffs2

  1. $ adb shell mount|grep yaffs
  2. / dev / block / mtdblock3 on / system type yaffs2 ( ro )
  3. / dev / block / mtdblock5 on / data type yaffs2 ( rw,nosuid,nodev )
  4. / dev / block / mtdblock4 on / cache type yaffs2 ( rw,nosuid,nodev )

Распакуем system и data (/cache остается пустым)

  1. $ mkdir system &&cd system && unyaffs .. / .. / .. / rom / system.img
  2. $ mkdir .. / data &&cd .. / data && unyaffs .. / .. / .. / rom / userdata.img

В результате мы получили полноценное корневое дерево, пригодное для прошивки в телефон, которое содержит системные библиотеки, framework, системные приложения, файлы конфигурации и пр.

Стоит учитывать, что в распакованном архиве содержатся символические ссылки, которые будут утеряны на файловых системах не поддерживающих оные (fat/ntfs). Которые мы можем восстановить через скрипт обновления, о чем будет рассказано в другой статье.

Также нам понадобиться boot-раздел, который по сути является linux ядром (для выбранной прошивки это 2.6.29 armv6l) с ramdisk-ом и имеет следующий формат:

Если мы захотим заменить ядро, либо модифицировать скрипты инициализации, нам необходимо их извлечь из boot-образа. Для этого нам понадобиться замечательный perl-скрипт split_bootimg.pl за авторством William Enck.

  1. $ split_bootimg.pl .. / rom / boot.img
  2. $ ls
  3. boot.img-kernel boot.img-ramdisk.gz data system

С самим ядром мы ничего не можем сделать, кроме как заменить его другим, а рамдиск можно распаковать для последующего изменения и настройки:

  1. $ mkdir ramdisk &&cd ramdisk &&gzip -dc .. / boot.img-ramdisk.gz |cpio -i
  2. $ ls
  3. data default.prop dev init init.goldfish.rc init.hero.rc init.rc logo.rle proc sbin sys system

В данной статье мы не хотим ничего делать ни с ядром ни с ramdisk-ом, а потому запакуем все обратно (либо вернемся на шаг назад и вообще не будем трогать boot)

  1. find . |cpio —quiet -o -H newc |gzip> .. / new-ramdisk.gz
  2. $ cd .. && mkbootimg —kernel boot.img-kernel —ramdisk new-ramdisk.gz —cmdline «no_console_suspend=1 console=null» -o newboot —base 0x19200000

Для других телефонов настроки базового смещения могут отличаться. Коммандлайн мы получаем из split_bootimg при распаковке.

Скрипт обновления

Для обновления будем использовать update-скрипт, который пишется на специальном скриптовом языке edify, о синтаксисе которого можно прочитать в исходниках android. Скрипт /META-INF/com/google/android/update-script может быть таким:

  1. show_progress 0.1 0
  2. format CACHE:
  3. format SYSTEM:
  4. copy_dir PACKAGE:system SYSTEM:
  5. set_perm_recursive 0 0 0755 0644 SYSTEM:
  6. set_perm_recursive 0 2000 0755 0755 SYSTEM:bin
  7. set_perm 0 3003 02755 SYSTEM:bin/netcfg
  8. set_perm 0 3004 02755 SYSTEM:bin/ping
  9. set_perm_recursive 1002 1002 0755 0440 SYSTEM:etc/bluez
  10. set_perm 0 0 0755 SYSTEM:etc/bluez
  11. set_perm 1002 1002 0440 SYSTEM:etc/dbus.conf
  12. set_perm 1014 2000 0550 SYSTEM:etc/dhcpcd/dhcpcd-run-hooks
  13. set_perm 0 2000 0550 SYSTEM:etc/init.goldfish.sh
  14. set_perm_recursive 0 0 0755 0555 SYSTEM:etc/ppp
  15. set_perm 0 0 04755 SYSTEM:etc/ppp/ip-up-vpn
  16. show_progress 0.1 10
  17. show_progress 0.2 0
  18. copy_dir PACKAGE:data DATA:
  19. show_progress 0.2 10
  20. show_progress 0.3 0
  21. format BOOT:
  22. write_raw_image PACKAGE:boot.img BOOT:
  23. show_progress 0.3 10

Пока этот скрипт очень примитивен и единственное что он делает — подготавливает соответствующие разделы.

Подпись пакета обновления

Для того, чтобы мы смогли прошить нашу прошивку, нам необходимо подписать пакет обновления. Этот процесс аналогичен процессу подписывания jar-пакетов. К пакету добавляется ваш (либо тестовый) сертификат и сохраняются контрольные суммы для файлов внутри него.

  1. $ zip -r habrarom.zip .
  2. $ java -classpath ../../bin/testsign.jar testsign habrarom.zip habrarom-signed.zip

Прошивка радио модуля

Это самая простая часть в плане создания пакета обновления, но и самая опасная в плане последствий при неудачном обновлении.
Пакет обновления создается абсолютно идентично предыдущему, только содержать он будет бинарный блоб с радио, который мы извлекли из RUU и скрипт для его записи в соответствующий раздел памяти.
Простенький скрипт:

  1. show_progress 0.1 0
  2. write_radio_image PACKAGE:Radio_Signed_HERO_63.18.55.06O_6.35.15.01.img
  3. show_progress 0.1 10

Не многое, что будет включено в данный пакет обновления.

  1. $ ls -1
  2. META-INF
  3. Radio_Signed_HERO_63.18.55.06O_6.35.15.01.img

Всё это упаковывается и подписывается как делалось ранее.

Прошивка

Не смотря на то, что в полученную прошивку мы не добавили пока никакого нового функционала, мы бы хотили попробовать прошить и загрузиться в нее.
Для этого

  1. Копируем в корень карты наш пакет обновления
  2. Загружаемся в recovery
  3. Делаем nanroid backup
  4. Делаем wipe
  5. Прошиваем
  6. Перегружаемся

Радуемся тому, что наш больной пережил сложную операцию.

В данный обзор не вошли следующие важные вопросы, которые затрагивают уже непосредственно модификацию подготовленной базовой прошивки. Вопросы с которыми сталкивается любой создатель кастомов, и столкнулся непосредственно я при создании русской версии прошивки 2.1 для HTC Hero GSM

  • Добавление root, busybox
  • Де-оптимизация (deodexing) пакетов. Использование smali/baksmali. Разрешение odex-зависимостей
  • удаленная odex-оптимизация приложений
  • Модификация системных пакетов. Подпись пакетов: когда нужна, и когда можно пренебречь. Упаковка приложений. Обновление ресурсов приложений без пересборки
  • Локализация системы, как пример масштабной модификации системы.
  • Декомпиляция и сборка ресурсов/байткода системных приложений. Исправление ошибок системных приложений
  • zip-align, png оптимизация
  • Подписывание приложений и проблема круговой поруки при использовании shared uid
  • Использование скриптов инициализации на примере переноса данных из одного раздела в другой (dalvik-cache2cache, app2sd)

А тем временем ждем с нетерпением, когда за обновлением FOTA клиента последует обновление самой системы до версии 2.1-update1.

Читайте также:  Как удалить экран блокировки android

Источник

How to Install a Custom ROM on your Android Phone to give it a fresh new look!

Every smartphone comes with a default ROM or UI pre-installed. It can be AOSP-based with not a lot of added features, more commonly referred to as Stock Android, or it can be a custom skin from a particular brand. Samsung phones, for example, use a custom UX based on Android called OneUI. Xiaomi phones use MIUI, Oppo uses ColorOS, OnePlus uses OxygenOS, etc. Every UI looks different and has a different set of features.

While some may like a certain UI or skin, others may not. Some users prefer a feature-rich interface with the ability to install themes and modify system elements while some may want a clean, simple experience with no frills. This is where installing a custom Android ROM comes into the picture.

A custom ROM essentially replaces the stock ROM or skin on your phone with the one you choose to install. For example, if you have a Xiaomi or Redmi phone running on MIUI but you don’t like the interface, you can install a custom ROM that will change the UI to stock Android or something else you like.

There are multiple benefits to installing a custom Android ROM. If the UI you’re currently using has a lot of ads or bloatware, you can install a custom ROM to get rid of them. If your phone’s OEM has stopped updating your device and you’re stuck on an older Android version, you can use a custom ROM based on a newer version of Android. If you like a different OEM’s UI and want to try it on your phone, you can install a custom ROM.

Now that you know what a custom ROM can do, let’s tell you how you can install it on your Android phone. Note that there’s no universal custom ROM, although Project Treble somewhat materialized it by introducing the concept of the Generic System Image (GSI). While it is possible to install a GSI sprinkled with all the goodies from your favorite custom ROM, keep in mind that it may not offer you the same level of stability and performance that you can get from a fine-tuned dedicated custom ROM for your device. So with all of this being said, you’ll have to install a ROM that’s specifically made for your phone. Failing to do so may result in bricking your phone. You’ll then have to find ways to recover it or take it to the service center.

Note: Installing a custom ROM can void the warranty on some devices since it involves unlocking the bootloader. Proceed with caution as you can cause temporary/permanent damage to your device if you don’t follow all the steps correctly.

Sometimes, installation instructions can have some variations depending on your device. These are generic instructions. Please double-check with your device forums for variations.

Pre-requisites to Install a Custom ROM

There are certain things you need before you can start installing a custom Android ROM on your phone. Let’s go over all of them so your device is ready for the installation process.

  • An Android device.
  • An unlocked bootloader (if you don’t know how to unlock the bootloader of your phone, head over to the XDA Forums and search for your device name followed by “unlock bootloader” and you’ll find a guide. The process is different for every phone so make sure you follow the one specifically meant for your device.)
  • A custom recovery: TWRP is a good option, you can follow our detailed guide to install TWRP on your phone. However, some custom ROMs have specific recommendations on the recovery you need to use, so please follow that if such instructions are present.
  • A custom ROM zip file that you want to install (again, head over to the XDA Forums and search for your device, go through all the available ROMs, and choose the one you want to install.)
    • Please note again that custom ROM installation instructions can and do vary by device and ROM. If your ROM of choice comes with its own instructions, please follow them instead of this guide. This guide is a general list of instructions and does not take into account any special device instructions.
  • GApps or Google Apps.
  • A little bit of patience.

How to Install a Custom ROM

Now you have everything ready to install a custom ROM, we can begin the process.

Step 0: Back up your data

There’s one more thing you need to do before starting the installation though, and that’s to make a backup of all your data. We have a detailed guide to help you back up every aspect of your phone’s data so make sure you do that so it’s easy to restore your data once you install a new ROM.

Step 1: Downloading the correct ROM

As we mentioned earlier, the best way to do this is to head over to the XDA Forums for your device and look for a ROM that best suits your needs. Custom ROMs are device-specific so download a ROM that’s made specifically for your device. Also, there can be multiple variants of the same device based on carrier, region, etc. so keep this in mind too. Locate the appropriate custom ROM for your exact device. If you’re not sure, ask about compatibility in the XDA Forums.

Читайте также:  Список с выбором андроид

Once you’ve found the ROM you want to install, download the zip file either on your computer or on your phone. Note that you will need to data wipe your phone in some of the later steps, so it is advisable to do the file transfer later on, after the data wipe — but ensure that your phone can connect to your computer and can receive files, just to be clear that your device drivers are in place. Later on, you will need to copy the ROM file to the root of your phone’s internal storage. Don’t extract the zip file.

Step 2: Downloading GApps or Google Apps

Custom ROMs do not come with Google’s apps and services pre-installed (with the exception of a few). So if you want to be able to sign in with your Google account and use Google’s services like Sync, Play Store, Gmail, Drive, etc., you’ll need to install a separate GApps package. There are multiple variants of GApps you can install. You can refer to our guide on finding the right Gapps package for you and download one that’s appropriate for you. This will also be in the form of a zip file. Download and transfer it to your phone’s internal storage. You can also install them right from your PC/Mac if you opt for the adb sideload method.

Note: Some custom ROMs like Pixel Experience come with GApps pre-installed. In such cases, you don’t have to flash the GApps file separately.

Step 3: Booting into TWRP

Once you’ve copied the ROM and GApps files to your phone’s internal memory, it’s time to boot into TWRP to flash the files. If you’re not familiar with booting into recovery mode on your phone, we have a guide telling you how to boot into recovery on your phone so you can follow that to boot into TWRP. Once you’re in TWRP, there are a few things you need to do before installing the ROM which we’ll go over in the next step.

Step 4: Installing the Custom ROM

Once you’re in TWRP, it’s a good idea to take a nandroid backup of your entire system before proceeding further. This can be useful in case you end up with a failed installation. You’ll be able to boot into TWRP and restore the backup to go back to the previous state of your device.

  • To do this, select the Backup option in TWRP and select Boot, System Image, Data, Modem, and EFS, and then Swipe to backup. Wait till it’s done.

  • This step will wipe your entire phone: Go back to the main menu of TWRP and select Wipe. Then, Swipe to Factory Reset. Select the Format Data option and type in ‘yes’ and select the tick mark to format your phone. Note that formatting the /data partition will need you to reboot once so that TWRP can properly identify the newly created file system.

  • Moreover, since the internal memory of the device is wiped during formatting, you must copy the ROM and GApps files once again to your phone’s storage.
    • You can do this from within TWRP itself. Head over to the Mount section and select the Enable MTP option.
    • Now, connect your phone to your PC and it should be detected as a storage device. Transfer the ROM and gapps files.

  • Once done, go back to the main menu on TWRP and select Install. Browse to the location where you saved the ROM and GApps files. First, select the ROM and Swipe to Install it.
    • Head back to the previous menu and select the GApps file. Install that as well. Once the installation is complete, select Reboot to System.
    • If your installation does not boot with this sequence of steps, you may need to flash/install the ROM, reboot back into recovery, and then flash the GApps file. This additional reboot is needed in some cases.

You now have a custom Android ROM installed on your phone! Wait for your phone to boot up. It may take a while for the initial boot process so don’t panic, your phone will boot into the setup process.

That’s how you can install a custom Android ROM on your phone. It’s a fairly simple process and with a little bit of time and patience, you can enjoy a fresh new ROM on your phone with added features, customization, theming, and more. If you installed a custom ROM and you don’t like it or it has issues, just download a new ROM and repeat the installation process.

Источник

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