Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lopestom/c4a2648958db5c3db03d32033a3583cd to your computer and use it in GitHub Desktop.
Save lopestom/c4a2648958db5c3db03d32033a3583cd to your computer and use it in GitHub Desktop.
Copying firmware files to the Device Tree - Mediatek

Preface

:atom: Last updated on 03/05/2024.

🌎 initial file on 01/23/2024.

Many users, generally users with little knowledge and no experience, asked me which correct files should be placed in the device tree1 for Custom Recovery to generally work.

But of course most of these users want to know the files that control the encryption, that is, they want to know the correct files so that the encryption/decryption can work. In this sense, as there is not much information about this on the internet, I decided to put some words and some experience that I have had over a few years with Mediatek devices.

Although most of the information has programming, even though I am an Engineer and Teacher, I always wanted the language to understand to be as simple and easy as possible. Even so, you really need to understand some parts of Linux, Android and programming code. Don't read all of this without prior knowledge2 of the subject.

The idea about this Info Guide

This "guide" interacts/complements with some important information from other guides:

Custom Recovery for MediaTek devices

Fixing Touchscreen - custom recovery

Important

There is no Android version limit to start follow this guide. Understanding how you will have files from Android 4.4 to Android 13 (new information on how to decrypt userdata must be understood and make correct changes depending on each encryption mode), is something individual and each user must know which tool/software to use.

Table of contents

  1. What you need?

    1.1 Tools/Software

    1.2 Unpacking img files

    1.3 Which img file is best to start with?

  2. The recovery ramdisk

    2.1 Parts of recovery ramdisk

    2.2 What informations does Device Tree need? * Mediatek devices vs knowledge

    2.2.2.1 The *.mk files - BoardConfig.mk - part I of III

    2.2.2.1 The *.mk files - BoardConfig.mk - part II of III

    2.2.2.1 The *.mk files - BoardConfig.mk - part III of III

    2.2.2.1 The *.mk files - BoardConfig.mk for Recovery_ramdisk in the boot.img

    2.2.2.1 The *.mk files - BoardConfig.mk for Recovery_ramdisk in the vendor_boot.img

    2.2.2.2 The *.mk files - device.mk

    2.2.2.3 The *.mk files - twrp_devicename.mk

    2.2.2.4 The *.mk files - Android.mk & AndroidProducts.mk

    2.3 The folders /recovery/root/

    2.3.1 \recovery\root\

    2.3.2 \recovery\root\lib\modules\

    2.3.3 \recovery\root\first_stage_ramdisk\

    2.3.4 \recovery\root\system\

    2.3.5 \recovery\root\vendor\

  3. Crypt-Decrypt

    3.1 Process & Files

    3.2 Trustkernel

    3.3 Beanpod (microtrust)

    3.4 Trustonic

Finishing & Thanks and Notes

Footnotes

  1. Device Tree using a Minimal Manifest repository is an informative data structure used to describe the hardware parts of the devices in a platform-independent manner. It provides a way to describe hardware info and or firmware version (if want) of the device without the need for board-specific source code. The objective is compile a Custom Recovery with special options like backup, instalation and modify files.

  2. Many times in the past I have encountered people who are truly knowledgeable in creating Custom Recovery. But most of them kept the information to themselves. I cannot judge such a choice. It's quite possible that I didn't intend to save my knowledge until I became a worthless carcass, but I also didn't pass on all the knowledge I have when I helped some people. Well, learn that I don't have ALL the knowledge about Custom Recovery and I'm not going to write everything I know either. Most of what you learn from this is definitely reading and doing, making mistakes and learning to correct until you find the perfect skill for you.

1. What you need?

1.1 Tools/Software

Depending on what you know and what you want, tools/software and knowledge are important. Knowing whether the files are in the EROFS, sparse or ext4 extension is relatively easy. So understand that the tool must have the ability to work with the file extensions you will need.

1.1.1 Firmware img files

There are many tools/software in different ways for Linux, Win8.1~11 and even for Android (need ROOT). The particularity at this point is not to highlight how these tools/software are used. But you can have a direction for them:

Linux WinNN Android
SuperRs-Kitchen CRB Android Kitchen UKA

These tools are for unpacking files like super.img and/or vendor_dlkm.img. Some can unpack files like recovery.img, boot.img and vendor_boot.img.

1.1.2 Recovery ramdisk img files

To unpack files like recovery.img, boot.img and vendor_boot.img in particular and save time to have files and information, we can use the most updated tool that exists for WinNN and Linux. Generally the tools/software highlighted above also use the same tool/software as this one: AIK Linux -- AIK WinNN -- AIK-mobile

1.1.3 Editing text files

There are many of them. But I can point out some that do something better and really highlight usability.

  • WinNN

    To edit text files like *.rc, *.prop, *.default, *.fstab, fstab.* and other files that have no extension but can be opened through the text editor, you can use the tool /software Notepad++. To compare text files, you can use the tool /software Beyond Compare.

Tip

Depending on what you want to use, these tools/software can start on Linux with Wine.

  • Linux

    To edit text files like *.rc, *.prop, *.default, *.fstab, fstab.* and other files that have no extension but can be opened through the text editor, you can use the tool /software Vi/Vim or kate. To compare text files, you can use the tool /software Meld or Diffchecker.

Tip

Depending on what you want to use, these tools/software can start in the WinNN too.

Note

These are just as references. Use the tool/software that you know is best and works.

1.2 Unpacking img files

We start by understanding that you already know how to unpack the img files from the device's firmware. So you must have enough space and time to wait for the process. In this sense, you will have the files as a basis for this piece of information: Android - Some information about firmware files

The main files to unpack are:

  • super.img 🔛 this generates the system.img files; vendor.img; product.img which must be unpacked as well, Depending on the OEM, some extra files may be contained in super.img as partitions of system_ext.img; my_preload.img; mi_ext.img; among other img files;
  • recovery.img or boot.img or vendor_boot.img 🔛 thi's a base the files for recovery_ramdisk;
  • vendor_dlkm.img 🔛 starting from A13+, here we have *.ko files which are the hardware driver modules.

1.3 Which img file is best to start with?

By objective and experience, the best file will be the one with the ramdisk part. Therefore, depending on the kernel version, the recovery ramdisk may be inside the recovery.img or boot.img or vendor_boot.img file. For Android with kernel version 4.nn and earlier, you must use recovery.img and boot.img files as recovery ramdisk. This also depends on the Android version and to know what to use, just look at the firmware files which img file exists in it. For Android with kernel version 5.nn and later, you must use the vendor_boot.img file as recovery ramdisk.

2. The recovery ramdisk

We start with the recovery.img or boot.img or vendor_boot.img files to understand the information that is written in **.so files and text files.

2.1 Parts of recovery ramdisk

When you unpack the img file, there are generally two parts/folders:

  • Split or files_info => Structure and informations by kernel files;

    Click to open

    ksnip_20240124-174502

  • Ramdisk or cpio => Folder structure and informations with very different files;

    Click to open

    ksnip_20240124-174704

2.2 What informations does Device Tree need?

I highlighted in the image above some information that will be necessary to place in the Device Tree. Then consider the Split or files_info information for the Device Tree 1️⃣BoardConfig.mk; 2️⃣device.mk

2.2.1 Split or files_info

Click to open

ksnip_20240124-173530

You can have this information on the unpacking screen or just click on each file to open and see the information given. For better visualization and understanding:

  • Supplied image: recovery-MT6761.img

    It is important to understand and know the correct recovery ramdisk partition. This gives us information about what exists in a given img file with its structure and files. Furthermore, install the Custom recovery img file on the correct partition. Understand that I already wrote about this and there are three partitions where the recovery ramdisk part can remain.

    • 1️⃣

      Click to open

      Information Value BoardConfig.mk
      BOARD_KERNEL_CMDLINE bootopt=64S3,32N2,64N2 buildvariant=user BOARD_KERNEL_CMDLINE :=
      BOARD_KERNEL_BASE 0x40078000 BOARD_KERNEL_BASE :=
      BOARD_NAME BOARD_KERNEL_NAME :=
      BOARD_PAGE_SIZE 2048 BOARD_KERNEL_PAGESIZE :=
      BOARD_HASH_TYPE sha1 BOARD_HASH_TYPE :=
      BOARD_KERNEL_OFFSET 0x00008000 BOARD_KERNEL_OFFSET :=
      BOARD_RAMDISK_OFFSET 0x11a88000 BOARD_RAMDISK_OFFSET :=
      BOARD_SECOND_OFFSET 0xbff88000 BOARD_KERNEL_SECOND_OFFSET :=
      BOARD_TAGS_OFFSET 0x07808000 BOARD_KERNEL_TAGS_OFFSET :=
      BOARD_OS_VERSION 11.0.0 PLATFORM_VERSION :=
      BOARD_OS_PATCH_LEVEL 2022-02 PLATFORM_SECURITY_PATCH :=
      BOARD_HEADER_VERSION 2 BOARD_BOOT_HEADER_VERSION :=
      BOARD_RECOVERY_DTBO_SIZE 35345 BOARD_DTBOIMG_PARTITION_SIZE :=
      BOARD_RECOVERY_DTBO_OFFSET 19097600
      BOARD_HEADER_SIZE 1660
      BOARD_DTB_SIZE 102314 BOARD_DTB_SIZE :=
      BOARD_DTB_OFFSET 0x07808000 BOARD_DTB_OFFSET :=

In summary, the information will look like this in BoardConfig.mk

# Kernel
BOARD_KERNEL_CMDLINE := bootopt=64S3,32N2,64N2
BOARD_KERNEL_BASE := 0x40078000
BOARD_KERNEL_PAGESIZE := 2048
BOARD_HASH_TYPE := sha1
BOARD_KERNEL_OFFSET := 0x00008000
BOARD_RAMDISK_OFFSET := 0x11a88000
BOARD_KERNEL_SECOND_OFFSET := 0xbff88000
BOARD_KERNEL_TAGS_OFFSET := 0x07808000
BOARD_BOOTIMG_HEADER_VERSION := 2
BOARD_DTB_OFFSET := 0x07808000
BOARD_MKBOOTIMG_ARGS += --base $(BOARD_KERNEL_BASE)
BOARD_MKBOOTIMG_ARGS += --pagesize $(BOARD_KERNEL_PAGESIZE)
BOARD_MKBOOTIMG_ARGS += --ramdisk_offset $(BOARD_RAMDISK_OFFSET)
BOARD_MKBOOTIMG_ARGS += --tags_offset $(BOARD_KERNEL_TAGS_OFFSET)
BOARD_MKBOOTIMG_ARGS += --kernel_offset $(BOARD_KERNEL_OFFSET)
BOARD_MKBOOTIMG_ARGS += --second_offset $(BOARD_KERNEL_SECOND_OFFSET)
BOARD_MKBOOTIMG_ARGS += --dtb_offset $(BOARD_DTB_OFFSET)
BOARD_MKBOOTIMG_ARGS += --header_version $(BOARD_BOOTIMG_HEADER_VERSION)
BOARD_MKBOOTIMG_ARGS += --dtb $(TARGET_PREBUILT_DTB)

# Hack: prevent anti rollback
PLATFORM_SECURITY_PATCH := 2022-02-05
VENDOR_SECURITY_PATCH := 2022-02-05
PLATFORM_VERSION := 11

Note

Each part of BOARD_KERNEL_* needs BOARD_MKBOOTIMG_ARGS for the source code to create a file with the size value property defined. For 32-bits devices the BOARD_KERNEL_CMDLINE has bootopt=64S3,32S1,32S1.

  • 2️⃣
Information Value device.mk
BOARD_OS_VERSION 11.0.0 PRODUCT_SHIPPING_API_LEVEL :=
# API
PRODUCT_SHIPPING_API_LEVEL := 30

# VNDK
PRODUCT_TARGET_VNDK_VERSION := 30

Some SDK/API informations: Android API Levels

Caution

Some information may be empty like BOARD_NAME. It usually appears on devices from the following brands: Realme; Infinix; Tecno; Cubot; Sansumg. Other information such as BOARD_RECOVERY_DTBO_OFFSET; BOARD_RECOVERY_DTBO_SIZE is not priority/necessary. Only include information that is relevant and can be considered absolutely safe/correct. Therefore, do not take risks due to excessive doubts. This may cause errors in compiling the Custom Recovery img file.

Tip

If your device tree need BOARD_NAME so you need BOARD_MKBOOTIMG_ARGS += --board $(BOARD_NAME)

Important

Before approaching the following continuation, it is important to highlight that some basic knowledge is necessary. Understanding that we must know what the device has in terms of hardware and software information will be important to avoid having doubts or confusing information. In this context, follow this step to obtain all possible information: II. Get some informations from device using adb-fastboot platform-tool

As the main approach is for Mediatek devices, even these have some different peculiarities. Some information should initially be understood as:

Platform Display Memory
Chipset Resolution Internal
CPU Type
GPU Camera cutout Type

In this matter, many Mediatek chipsets exist and are also built with 32bits or 64bits; with Quadcore or Octacore and finally the Kernel Version and the Android OS Version. Some Mediatek chipsets/Processor Name to know: Model number - PLATFORM - Chipsets MediaTek

As there are three types of partitions that can contain the recovery ramdisk - recovery.img or boot.img or vendor_boot.img file - there are also particularities when entering configuration information about these partitions. This part must be understood so that we do not include extra and wrong information.

Partition dependency kernel dtb dtbo
recovery boot.img yes yes yes
boot first_stage_ramdisk folder yes yes no
vendor_boot first_stage_ramdisk folder no yes no

How do we know if such files are on the partition? See the unpacked parts of Split or files_info.

Caution

As a general rule, I will just interact between some basic settings and flags, indicating which file the information should come from. So keep in mind that Device Tree files only serve as a way of learning where information is and where to put it. The Device Tree files below are not intended to serve as an example or copy for a given Chipset. There are many repositories on github that may be good for your device/Chipset and therefore you can use them.

2.2.2 Ramdisk or cpio

Click to open

ksnip_20240124-174704

I highlighted in the image above some information that will be necessary to place in the Device Tree. Then consider the Recovery Ramdisk information for the Device Tree 1️⃣BoardConfig.mk; 2️⃣device.mk; 3️⃣twrp_devicename.mk; 4️⃣Android.mk; 5️⃣AndroidProducts.mk

The important information and files from the Stock img file will be in ramdisk\ prop.default & init.recovery.mtNNNN.rc; ramdisk\first_stage_ramdisk\fstab.mtNNNN & fstab.emmc ; ramdisk\lib\modules/*.ko; ramdisk\system\bin\mtk_plpath_utils; ramdisk\system\lib64\hw\android.hardware.boot@'N.n-impl-N.n-mtkimpl.so and ramdisk\system\etc\recovery.fstab

Warning

Settings are understood as information given from Android source code and flags coming from the TWRP source code that are highlighted with TW_ and that can help with Custom Recovery processes and features. There are many settings and flags that depend on what the device can have. You can read more in the InfoGuide understand about some flags - setup & configurations. You can compare TW_ flags for each Custom Recovery version if you want need know more so look TWRP-10; TWRP-11; TWRP-12.1.

Be careful when using any flag from a certain TWRP version to another TWRP version. As well as the Android version Variable /Settings for another Android version from the AOSP base. Each version of TWRP may have new flags introduced and may also have Deprecated flags.

Therefore, the approach below only serves as an information base for a given device, but obviously it can have many characteristics that are the same or different from other devices.

2.2.2.1 The *.mk files
part I of III
1️⃣ BoardConfig.mk
Click to open

DEVICE_PATH := device/brand/devicename
  • brand ➡️ from prop.default file by any *.brand= line

  • devicename ➡️ from prop.default file by any *.device= line


# For building with minimal manifest
ALLOW_MISSING_DEPENDENCIES := true

Indicates that the source code of Custom Recovery based on minimal manifest programming and will use the kernel file copied in the prebuilt folder.


\# Architecture
TARGET_ARCH := arm64
TARGET_ARCH_VARIANT := armv8-a
TARGET_CPU_ABI := arm64-v8a
TARGET_CPU_ABI2 :=
TARGET_CPU_VARIANT := cortex-a53

TARGET_2ND_ARCH := arm
TARGET_2ND_ARCH_VARIANT := armv8-a
TARGET_2ND_CPU_ABI := armeabi-v7a
TARGET_2ND_CPU_ABI2 := armeabi
TARGET_2ND_CPU_VARIANT := cortex-a53

Since I wrote another InfoGuide Custom Recovery for MediaTek devices, I don't want to repeat too much about this or go into detail. Writing about the Android structure is not the focus at the moment and without a minimum knowledge of Linux-Android, it becomes more difficult to understand it all. ARM architecture family - List of ARM processors - Armv8-A architecture evolution

Architecture 🔀 But for the sake of knowledge, just understand that there are devices with 32-bits (arm) and 64-bits (arm64).

  • TARGET_ARCH ➡️ Comes from prop.default file by any ro.bionic.arch= or/and ro.bionic.2nd_arch= line.

  • TARGET_ARCH_VARIANT ➡️ The Variant comes from the Architecture and depends on each device. Usually armv8-a or armv8-2a for 64-bits devices & armeabi-v7a for 32-bits devices. More details, check the links I left above.

  • TARGET_CPU_ABI ➡️ Comes from prop.default file by any ro.product.cpu.abi= or/and ro.product.cpu.abilist64= or/and ro.product.cpu.abilist= or/and ro.product.cpu.abilist32= line.

  • TARGET_CPU_ABI2 ➡️ Usually with nothing.

Target information variables 🔀 This will indicate which processor will be in the device with generic efficiency. The CPU will determine this part.

  • TARGET_CPU_VARIANT ➡️ Comes from prop.default file by any ro.bionic.cpu_variant= or/and ro.bionic.2nd_cpu_variant= or/and dalvik.vm.isa.arm64.variant= or/and ro.bionic.2nd_arch= or/and dalvik.vm.isa.arm.variant= line.

  • TARGET_2ND ➡️ For devices with 64-bits & 32-bits.

If you have only 32-bits device:

# Architecture
TARGET_ARCH := arm
TARGET_ARCH_VARIANT := armv7-a-neon
TARGET_CPU_ABI := armeabi-v7a
TARGET_CPU_ABI2 := armeabi
TARGET_CPU_VARIANT := generic

# Architecture Extensions
ARCH_ARM_HAVE_NEON := true
TARGET_CPU_SMP := false
ARCH_ARM_HAVE_TLS_REGISTER := true

TARGET_BOARD_SUFFIX := _64
TARGET_USES_64_BIT_BINDER := true
TARGET_SUPPORTS_64_BIT_APPS := true
TARGET_IS_64_BIT := true
  • TARGET_BOARD_SUFFIX ➡️ Set for 64-bit devices.
  • TARGET_USES_64_BIT_BINDER ➡️ Should be set even while doing a 32-bit only build for a 64-bit arch. Maybe it's deprecated.
  • TARGET_SUPPORTS_64_BIT_APPS ➡️ Set for 64-bit devices.
  • TARGET_IS_64_BIT ➡️ Set for 64-bit devices.

If you have only 32-bits device:

ARCH_ARM_HAVE_NEON := true
TARGET_CPU_SMP := false
ARCH_ARM_HAVE_TLS_REGISTER := true

TARGET_BOARD_SUFFIX := _32
TARGET_SUPPORTS_32_BIT_APPS := true
TARGET_SUPPORTS_64_BIT_APPS := false
TARGET_IS_32_BIT := true

# Platform
TARGET_BOARD_PLATFORM := mt6765
TARGET_BOARD_PLATFORM_GPU := mtk
  • TARGET_BOARD_PLATFORM ➡️ Comes from prop.default file by any ro.board.platform=.
  • TARGET_BOARD_PLATFORM_GPU ➡️ It comes from the GPU specification. Generally you should look for this part. Example:
      # Platform
      TARGET_BOARD_PLATFORM_GPU := mali-g76mc4

# Bootloader
TARGET_BOOTLOADER_BOARD_NAME := k62v1_64_h5
TARGET_NO_BOOTLOADER := true
TARGET_USES_UEFI := true
  • TARGET_BOOTLOADER_BOARD_NAME ➡️ Comes from prop.default file by any ro.product.board=.
  • TARGET_NO_BOOTLOADER ➡️ true means that we're not building the bootloader...
  • TARGET_USES_UEFI ➡️ If it's set to "true" or any non-empty value, it means that the target platform supports UEFI and the software should be designed and built with UEFI support. If it is set to "false" or an empty value, it means that the target platform does not use UEFI and the software can be built without UEFI support. You can find out if this exists if you get information with logcat, getprop, dmesg on the device. If in doubt, delete TARGET_USES_UEFI of this part.

# MTK Hardware
BOARD_HAS_MTK_HARDWARE := true
BOARD_USES_MTK_HARDWARE := true
MTK_HARDWARE := true
  • Do I need to explain this part?

# Assert
TARGET_OTA_ASSERT_DEVICE := H166
  • Comes from prop.default file by any *.device= and/or *.model=.
    • Example:
          # Assert
          TARGET_OTA_ASSERT_DEVICE := HCE600,SOYES MAXo

# File systems and partitions
BOARD_HAS_LARGE_FILESYSTEM := true
BOARD_BOOTIMAGE_PARTITION_SIZE := 0x2000000 # 33554432 - 32MB
BOARD_RECOVERYIMAGE_PARTITION_SIZE := 0x2000000 # 33554432 - 32MB
BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
#BOARD_CACHEIMAGE_PARTITION_SIZE := 0x1B000000
BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE := ext4
#BOARD_SYSTEMIMAGE_PARTITION_SIZE := 0x4A939000
BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE := ext4
#BOARD_USERDATAIMAGE_PARTITION_SIZE := 0xD48CF8000
BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE := ext4
#BOARD_VENDORIMAGE_PARTITION_SIZE := 0x1FCD3000

The information in this part comes from Split or files_info.

  • BOARD_HAS_LARGE_FILESYSTEM ➡️ Use this flag if the board has a partition larger than 2GB.
  • BOARD_BOOTIMAGE_PARTITION_SIZE ➡️ The real size of boot.img file. You can put Hexadecimal or Decimal value.
  • BOARD_RECOVERYIMAGE_PARTITION_SIZE ➡️ The real size of recovery.img file. You can put Hexadecimal or Decimal value.

*** See the figure below [fastboot getvar all example] which allows you to have the correct sizes.

  • BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE & BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE & BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE & BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE ➡️ Comes from stock /ramdisk/system/etc/recovery.fstab file by fstype.

    Click to open recovery.fstab example

    ksnip_20240126-201557

  • BOARD_CACHEIMAGE_PARTITION_SIZE & BOARD_SYSTEMIMAGE_PARTITION_SIZE & BOARD_USERDATAIMAGE_PARTITION_SIZE & BOARD_VENDORIMAGE_PARTITION_SIZE ➡️ Comes from fastboot and fastbootd comand with fastboot getvar all.

# Dynamic Partition
BOARD_SUPER_PARTITION_SIZE := 6442450944
BOARD_SUPER_PARTITION_GROUPS := main
BOARD_MAIN_SIZE := 6438256640 # (BOARD_SUPER_PARTITION_SIZE - 4MB)
BOARD_MAIN_PARTITION_LIST := product vendor system odm
  • BOARD_SUPER_PARTITION_SIZE ➡️ Comes from fastboot and fastbootd comand with fastboot getvar all.

    Click to open `fastboot getvar all` example

    ksnip_20240126-214105

In general, it is not necessary to write the size values for the System; Product; Vendor; Userdata; System_Ext; others; partitions because the code-tools of Custom Recovery find this part. So this becomes optional.

  Use any online site that converts Hexadecimal to Decimal if you want to use Bytes.
Example: `boot:0x2000000` has 0x2000000 Hexadecimal and converted to Decimal has 33554432.

2.2.2.1 The *.mk files
part II of III
1️⃣ BoardConfig.mk
Click to open

# Kernel
BOARD_KERNEL_IMAGE_NAME := Image.gz
TARGET_PREBUILT_KERNEL := $(DEVICE_PATH)/prebuilt/Image.gz
TARGET_PREBUILT_DTB := $(DEVICE_PATH)/prebuilt/dtb.img
BOARD_PREBUILT_DTBOIMAGE := $(DEVICE_PATH)/prebuilt/dtbo.img
BOARD_INCLUDE_DTB_IN_BOOTIMG := true
BOARD_INCLUDE_RECOVERY_DTBO := true
BOARD_FLASH_BLOCK_SIZE := 131072 # (BOARD_KERNEL_PAGESIZE * 64)

This is a continuation part of # Kernel setting fom here 2.2.1 Split or files_info.

  • BOARD_KERNEL_IMAGE_NAME ➡️ This is name of kernel to source code put in the correct path. You can use zImage or Image.gz for 32-bits devices. If you have doubts so put kernel.
    • In some case the kernel and dtb is unique one file. So for that you can read the part of prebuilt. Therefore when you use that so the TARGET_PREBUILT_KERNEL have name and Image.gz-dtb file.
  • TARGET_PREBUILT_KERNEL ➡️ The source code include the kernel file within \Split folder of recovery_ramdisk.
  • TARGET_PREBUILT_DTB ➡️ The source code include the dtb file within \Split folder of recovery_ramdisk.
    • In some case the dtb file is unpacked detailed - you can read the part of prebuilt - In addition, - and that need a special folder/directory BOARD_PREBUILT_DTBIMAGE_DIR := prebuilt/dtb/mt6xxx.dtb and the file will be build and copied by the source code to the correct path. Therefore when you use that so not write the BOARD_INCLUDE_DTB_IN_BOOTIMG variable.
  • BOARD_PREBUILT_DTBOIMAGE ➡️ The source code include the dtbo file within \Split folder of recovery_ramdisk.
  • In case the dt file is unpacked - you can read the part of prebuilt - In addition, - and that need a special folder/directory BOARD_PREBUILT_DTBIMAGE_DIR := prebuilt/dtb/mt6xxx.dtb and the file will be build and copied by the source code to the correct path. Therefore when you use that so not write the BOARD_INCLUDE_DTB_IN_BOOTIMG variable.
  • BOARD_INCLUDE_DTB_IN_BOOTIMG ➡️ This allows for the inclusion of Device Tree Blob (DTB) files during the build process in the bootimage or recoveryimage or vendorbootimage.

  • BOARD_INCLUDE_RECOVERY_DTBO ➡️ This allows for the inclusion of Device Tree Blob Overlay (DTBO) files during the build process in the recoveryimage.

  • BOARD_FLASH_BLOCK_SIZE ➡️ Typically refers to the size of the flash memory block on the development board. The value of this variable depend of BOARD_KERNEL_PAGESIZE value and if the device have 32-bits or 64-bits.

    BOARD_KERNEL_PAGESIZE 32-bits 64-bits
    2048 65536 131072
    4096 131072 262144

TARGET_KERNEL_ARCH := arm64
TARGET_KERNEL_HEADER_ARCH := arm64
  • TARGET_KERNEL_ARCH & TARGET_KERNEL_HEADER_ARCH ➡️ Specific part of # Architecture similar to TARGET_ARCH. It determines the system-specific features, instructions and optimizations.

# Workaround for error copying vendor files to recovery ramdisk
TARGET_COPY_OUT_VENDOR := vendor
  • This will create a folder for certain required partition. But to avoid errors, it is necessary to have this partition specified in File systems and partitions part.
  • Example:
    # File systems and partitions
    BOARD_SYSTEM_EXTIMAGE_FILE_SYSTEM_TYPE := ext4
    
    # Workaround for error copying vendor files to recovery ramdisk
    TARGET_COPY_OUT_SYSTEM_EXT := system_ext

TARGET_USERIMAGES_USE_EXT4 := true
TARGET_USERIMAGES_USE_F2FS := true
  • TARGET_USERIMAGES_USE_EXT4 ➡️ This configuration setting specifies the system for managger userimages partition should formatted and build using the EXT4 fstype.
  • TARGET_USERIMAGES_USE_F2FS ➡️ This configuration setting specifies the system for managger userimages partition should formatted and build using the F2FS fstype.

# System as root
BOARD_BUILD_SYSTEM_ROOT_IMAGE := false
BOARD_SUPPRESS_SECURE_ERASE := true
  • BOARD_BUILD_SYSTEM_ROOT_IMAGE ➡️ For the A10+ the AOSP source code limited the use of SAR (System As ROOT = /system_root/system/). The Custom Recovery mount the system image as /. Therefore it must be set to false.
  • BOARD_SUPPRESS_SECURE_ERASE ➡️ Secure erase is a security feature that permanently deletes all data from a device to prevent unauthorized access or data recovery..

# AVB
BOARD_AVB_ENABLE := true
  • The AVB is Android Verified Boot and there are many websites that explain its in detail. So there is no need to delve into it. But you might be interested in something so read New Android requirements for bootloaders on page 15.
    • The most important thing in this part is to know the value of BOARD_KERNEL_PAGESIZE. If you are unsure if you want to use this or how to use this, then you can copy from any device tree that have img file compiled successfully.

# Hack: prevent anti rollback
PLATFORM_SECURITY_PATCH := 2099-12-31
VENDOR_SECURITY_PATCH := $(PLATFORM_SECURITY_PATCH)
BOOT_SECURITY_PATCH := $(PLATFORM_SECURITY_PATCH)
PLATFORM_VERSION := 99.87.36
PLATFORM_VERSION_LAST_STABLE := $(PLATFORM_VERSION)
  • PLATFORM_SECURITY_PATCH ➡️ Comes from prop.default file by ro.build.version.security_patch= line.
  • VENDOR_SECURITY_PATCH ➡️ Comes from prop.default file by ro.vendor.build.security_patch= line.
    • Resuming, with a future date means there are no problems with Rollback. But on some devices, depending on the encryption setting, the VENDOR_SECURITY_PATCH variable must have the same date.
  • BOOT_SECURITY_PATCH ➡️ Comes from BOARD_OS_PATCH_LEVEL of Split or files_info file line.
  • PLATFORM_VERSION ➡️ Comes from prop.default file by ro.build.version.release= line.
  • PLATFORM_VERSION_LAST_STABLE ➡️ Maybe comes from prop.default file by ro.build.version.release_or_codename= line.
    • If there is a line with the word stable or last, great. But usually there isn't. On newer devices with kernel version 5.xx usually with Android 12, the system version is updated and its differ, written as Android 13. Then you must confirm ro.build.version.release_or_codename= in the build.prop file of system.img file.

    • If you are unsure if you want to use this or how to use this, then you can copy from any device tree that have img file compiled successfully.


# Metadata
BOARD_USES_METADATA_PARTITION := true
BOARD_ROOT_EXTRA_FOLDERS += metadata
  • BOARD_USES_METADATA_PARTITION ➡️ Comes from /ramdisk/system/etc/recovery.fstab stock recovery_ramdisk file by mountpoint. You must look if a \metadata partition exists.
  • BOARD_ROOT_EXTRA_FOLDERS ➡️ This variable is used to create folders within of \ramdisk\ when compiling the Custom recovery with cases where there are no files inside them. With device tree in the device_brand_devicename/recovery/root/, the source code cannot create folders if not have files inside them.
    • You can write more folders if need. Example: BOARD_ROOT_EXTRA_FOLDERS += metadata transf

# Crypto
TW_INCLUDE_CRYPTO := true
TW_INCLUDE_CRYPTO_FBE := true
TW_INCLUDE_FBE_METADATA_DECRYPT := true
TW_USE_FSCRYPT_POLICY := 2
TW_PREPARE_DATA_MEDIA_EARLY := true

# Additional binaries & libraries needed for recovery
TARGET_RECOVERY_DEVICE_MODULES += libkeymaster4

TW_RECOVERY_ADDITIONAL_RELINK_LIBRARY_FILES += $(TARGET_OUT_SHARED_LIBRARIES)/libkeymaster4.so

Just pay attention to what the variable or flag is for. For encryption and decryption files and processes, there is another document for us to understand about how it works.

  • TW_INCLUDE_CRYPTO ➡️ It will enable encryption and decryption related processes and files.

    • If you not know about that so change trueto false.
  • TW_INCLUDE_CRYPTO_FBE ➡️ It will enable encryption and decryption related processes and files for FBE option.

    • Resuming, the source code will compile and copy the files into the Custom Recovery \ramdisk\system\bin and \ramdisk\system\lib_lib64 folders.
  • TW_INCLUDE_FBE_METADATA_DECRYPT ➡️ It will enable encryption and decryption related processes and files if Metadata has encryption mode.

  • TW_USE_FSCRYPT_POLICY ➡️ This will be different for devices coming with version 1 (v1) or version 2 (v2) options related to encryption and decryption. The source code will compile files and include information relating to each version. We usually know about this by looking at the \data partition in the /ramdisk/system/etc/recovery.fstab stock recovery_ramdisk file by flags. Note that only version 2 will be written v2 and therefore if this is not available, the option is version 1.

    Click to open recovery.fstab example

    ksnip_20240128-140332

  • TW_PREPARE_DATA_MEDIA_EARLY ➡️ Maybe this variable should relink /data/media/0 to /data. Solve specific decryption problems on some devices.

  • TARGET_RECOVERY_DEVICE_MODULES & TW_RECOVERY_ADDITIONAL_RELINK_LIBRARY_FILES ➡️ This variable tells you to compile a specific or necessary file that the Custom Recovery source code does not create. For convenience, a few years ago, the code was not yet updated and so the device tree needed extra files for the encryption/decryption process. This variable is not just for encryption/decryption and therefore you can "call" any file for compilation as long as it is in the Android source code and its specific version according to the Custom Recovery repository (minimal manifest).


# fastbootd A10+ ↪️ Additional binaries & libraries needed when have recovery.img
TARGET_RECOVERY_DEVICE_MODULES += \
          ashmemd_aidl_interface-cpp \
          libashmemd_client

TW_RECOVERY_ADDITIONAL_RELINK_LIBRARY_FILES += \
$(TARGET_OUT_SHARED_LIBRARIES)/libashmemd_client.so \
$(TARGET_OUT_SHARED_LIBRARIES)/ashmemd_aidl_interface-cpp.so
  • TARGET_RECOVERY_DEVICE_MODULES & TW_RECOVERY_ADDITIONAL_RELINK_LIBRARY_FILES ➡️ This variable tells you to compile a specific or necessary file that the Custom Recovery source code does not create. The ashmemd module files are required to start fastbootd when the device has the recovery.img partition active and starting with Android 10+.

    AOSP Source code moules for ashmemd.

    LOS Source code moules for ashmemd.

    • Ashmemd is a tool in Android that manages shared memory between processes. It stands for "Anonymous Shared Memory Device". It allows processes to allocate and share memory without the need for file-backed memory mappings. This can be useful for inter-process communication and sharing data efficiently between processes.

# Recovery
TARGET_RECOVERY_PIXEL_FORMAT := "BGRA_8888"
TARGET_RECOVERY_FSTAB := $(DEVICE_PATH)/recovery/root/system/etc/recovery.fstab
BOARD_HAS_NO_SELECT_BUTTON := true
RECOVERY_SDCARD_ON_DATA := true
  • TARGET_RECOVERY_PIXEL_FORMAT ➡️ This variable depends on how your device was configured to show certain colors in the screen. So there are some options like: RGB_565; RGB_888; RGBA_8888; RGBX_8888; BGRA_8888; BGRX_8888; ABGR_8888; RGBA_5551; RGBA_4444.
  • TARGET_RECOVERY_FSTAB ➡️ This variable is used to indicate the folder that the recovery.fstab file is in and is necessary when Custom Recovery starts, so it must mount main partitions. You can leave the recovery.fstab file anywhere, as long as you write the local in the variable. Even so, it will be automatically copied to the \recovery_ramdisk\system\etc folder in compiled Custom Recovery file.
  • BOARD_HAS_NO_SELECT_BUTTON ➡️ In short, most Custom Recoveries do not use physical buttons to select and confirm options on their interface. Even if your device has the three lower buttons, they will only serve the same Custom Recovery option (if any) such as Back, Menu and Show Processin the Screen. I only know of some like the current LOS Recovery and other old ones like CWM, Carliv, Philz and Dingdoing that need to use buttons like Power, Vol - and Vol + for certain actions.
  • RECOVERY_SDCARD_ON_DATA ➡️ This enables proper handling of /data/media on devices that have this folder for storage.

# Properties
TARGET_SYSTEM_PROP += $(DEVICE_PATH)/system.prop
TARGET_VENDOR_PROP += $(DEVICE_PATH)/vendor.prop
TARGET_RECOVERY_INITRC := $(DEVICE_PATH)/recovery/root/init.recovery.mt6762.rc
  • TARGET_SYSTEM_PROP ➡️ This variable is used to copy property lines coming from the system.img\build.prop part that are relevant for certain functions to work. With the device tree in device_brand_devicename/system.prop, the text inside the system.prop file will be copied in the Custom Recovery compiled file to the folder with the \recovery_ramdisk\prop.default file.
  • TARGET_VENDOR_PROP ➡️ This variable is used to copy property lines coming from the vendor.img\build.prop part that are relevant for certain functions to work. With the device tree in device_brand_devicename/vendor.prop, the text inside the vendor.prop file will be copied in the Custom Recovery compiled file to the folder with the \recovery_ramdisk\prop.default file.
  • TARGET_RECOVERY_INITRC ➡️ Use a custom init.rc file in the Custom Recovery to start necessary and/or special services and processes.
    • The init.recovery.{hardware}.rc file can also be seen as init.recovery.{platform}.rc and will serve to indicate the file paths, as well as to start the encryption/decryption mode process.

# Treble
BOARD_VNDK_VERSION := current

2.2.2.1 The *.mk files
part III of III
1️⃣ BoardConfig.mk
Click to open

# Display
TW_BRIGHTNESS_PATH := /sys/class/leds/lcd-backlight/brightness
TARGET_RECOVERY_LCD_BACKLIGHT_PATH := \"/sys/class/leds/lcd-backlight/brightness\"
TW_CUSTOM_CPU_TEMP_PATH := /sys/devices/virtual/thermal/thermal_zone1/temp
TW_MAX_BRIGHTNESS := 255
TW_DEFAULT_BRIGHTNESS := 150
TW_NO_SCREEN_BLANK := true
TW_SCREEN_BLANK_ON_BOOT := true
TW_INPUT_BLACKLIST := "hbtp_vm"

This part will define some hardware parts related to the screen configuration that your device has so that Custom Recovery informs and displays the information correctly. This can be used to set a nicer graphics mode and or fix presentation issues.

  • TW_BRIGHTNESS_PATH ➡️ Comes from /sys/class/leds/* for brightness works correctlly in the screen.

  • TARGET_RECOVERY_LCD_BACKLIGHT_PATH ➡️ Comes from /sys/class/leds/* for LCD works correctlly in the screen.

  • TW_CUSTOM_CPU_TEMP_PATH ➡️ Comes from /sys/devices/virtual/thermal* for show the CPU Temperature (thermal) ºC info in the screen.

  • TW_NO_SCREEN_BLANK ➡️ Don't blank screen (available optional inside recovery settings too).

  • TW_SCREEN_BLANK_ON_BOOT ➡️ It will jolt the screen/touch driver. If on the default settings the screen will only kick in to action/start AFTER it has gone to sleep once and has been woken up again with a key press, this will be needed to set to true. There is still a screen touch issue if this option is set to true.

    • On some legacy devices, the Custom Recovery will not boot without this flag.
  • TW_INPUT_BLACKLIST ➡️ It is used to indicate that a particular function is prohibited from access or use something because interfere with other anything. That allows users to blacklist certain input values or characters. When this setting is enabled, reject any input that contains blacklisted values or characters, preventing them from being processed further.

  • TW_MAX_BRIGHTNESS ➡️ Used to set the maximum brightness level to be displayed in the screen.

  • TW_DEFAULT_BRIGHTNESS ➡️ Sets the default brightness level to be used when Custom Recovery starts.

    • If you don't know the correct path, then remove any variables so there are no errors. In this sense, the Custom Recovery code itself tries to find the correct path directly on the device. There are some flags written with _CUSTOM_ and this serves to quickly indicate a path where the Custom Recovery code was unable to obtain information. Therefore, defining it exclusively serves to confirm the correct path. Some informations about \sys.

    • There are flags (TW_NO_*) that disable the source code from finding some functions. Example: TW_NO_BATT_PERCENT := true Disables the display of the battery percentage for devices that don't support it properly.

    • Use the adb tool for have informations from your device. Use this command: adb shell su -c "ls -R" > info.txt if you want. But look for have root priviledges or Root acess whit any apk process.


# Resolution
TW_THEME := portrait_hdpi
DEVICE_SCREEN_WIDTH := 720
DEVICE_SCREEN_HEIGHT := 1600
  • TW_THEME ➡️ Set your device's resolution mode with correct presentation and rotation in the screen.
    • There are still customized or exclusive themes, but this is another subject.
  • DEVICE_SCREEN_WIDTH ➡️ Enter the Screen Width value according to the resolution of your device.
  • DEVICE_SCREEN_HEIGHT ➡️ Enter the Screen Height value according to the resolution of your device.

# Statusbar icons flags 720 x 1600
TW_STATUS_ICONS_ALIGN := center
TW_CUSTOM_CPU_POS := 142
TW_CUSTOM_CLOCK_POS := 330
TW_CUSTOM_BATTERY_POS := 800

This part will define how the upper part (Battery Level, Clockstamp and CPU:Temperature °C) with information will be shown, and can be customized due to user choice or particularities, such as the location (POSition) of the camera cutout.

  • TW_STATUS_ICONS_ALIGN ➡️ Option to align information, therefore how it will be displayed on the screen.

  • TW_CUSTOM_CPU_POS ➡️ Option to align CPU:Temperature °C information according to the location value on the screen.

  • TW_CUSTOM_CLOCK_POS ➡️ Option to align Clockstamp information according to the location value on the screen.

  • TW_CUSTOM_BATTERY_POS ➡️ Option to align Battery Level % information according to the location value on the screen.

    Click to open - Some Examples

    Example POS

Has other flags. This is optional and depends on each case. Maybe it's deprecated?!

TW_H_OFFSET :=
TW_Y_OFFSET :=
TW_X_OFFSET :=
TW_W_OFFSET :=
  • TW_H_OFFSET ➡️ value of the Height axis displacement.
  • TW_Y_OFFSET ➡️ value Y from Axis offset for borked displays.
  • TW_X_OFFSET ➡️ value X from Axis offset for borked displays.
  • TW_W_OFFSET ➡️ value of the Width axis displacement. Example:
       TW_Y_OFFSET := 90
       TW_H_OFFSET := -90
    • The value depends on the resolution and you can see the black part from top to bottom in the 2 photos in Some Examples.

# TWRP specific build flags - Configuration
TW_USE_MODEL_HARDWARE_ID_FOR_DEVICE_ID := true
TW_USE_TOOLBOX := true
TW_EXTRA_LANGUAGES := false
TW_DEFAULT_LANGUAGE := en
TW_EXCLUDE_DEFAULT_USB_INIT := true
TW_INCLUDE_NTFS_3G := true
TARGET_USES_MKE2FS := true
TARGET_DISABLE_TRIPLE_BUFFERING := false
  • TW_USE_MODEL_HARDWARE_ID_FOR_DEVICE_ID ➡️ On some devices, the TWRP backup folder name will show 0000000000 because the CPU information has no serial number or 123456789ABCDEF if lost/erased. Using this flag it will use ro.product.model as the TWRP backup folder name.
  • TW_USE_TOOLBOX ➡️ Choose to compile and use ToyBox instead of Busybox.
  • TW_EXTRA_LANGUAGES ➡️ Add translated files for languages generally from the Asian region {Japanese, Chinese (Simplified), Chinese (Traditional) and Sinhala (Sri Lanka)}.
  • TW_DEFAULT_LANGUAGE ➡️ Sets the language when Custom Recovery starts on the device.
  • TW_EXCLUDE_DEFAULT_USB_INIT ➡️ Choose it not include the default init.recovery.usb.rc file (from source code), so need must provide your own (from device tree) or use the required definitions within the init.recovery.{hardware}.rc file.
  • TW_INCLUDE_NTFS_3G ➡️ It's include a NTFS driver file in the Custom Recovery. NTFS-3G allows for read and write access to NTFS partitions, commonly used by Windows OS.
  • TARGET_USES_MKE2FS ➡️ It will compile the files needed to use the "mke2fs" command to create an ext2, ext3 or ext4 filesystem.
  • TARGET_DISABLE_TRIPLE_BUFFERING ➡️ Set true to disable and false to not disable. Triple buffering is a technique used in computer graphics to reduce screen tearing and improve overall performance by using three buffers instead of two.

# Storage
TW_NO_USB_STORAGE := false
TW_INTERNAL_STORAGE_PATH := "/data/media/0"
TW_INTERNAL_STORAGE_MOUNT_POINT := "data"
TW_EXTERNAL_STORAGE_PATH := "/external_sd"
TW_EXTERNAL_STORAGE_MOUNT_POINT := "external_sd"
TW_HAS_MTP := true
TW_MTP_DEVICE := /dev/mtp_usb
TARGET_USE_CUSTOM_LUN_FILE_PATH := /config/usb_gadget/g1/functions/mass_storage.usb0/lun.%d/file
  • TW_NO_USB_STORAGE ➡️ Removes the USB storage button on devices that don't support USB storage.
  • TW_INTERNAL_STORAGE_PATH & TW_INTERNAL_STORAGE_MOUNT_POINT & TW_EXTERNAL_STORAGE_PATH & TW_EXTERNAL_STORAGE_MOUNT_POINT ➡️ Specify the dual storage partition (internal and external) for devices that have it. The mount point must match something in the files \ramdisk\system\etc\recovery.fstab or \device_brand_devicename\recovery\root\system\etc\twrp.fstab_flag or any correct storage mount point information.
  • TW_HAS_MTP ➡️ Indicates that Custom Recovery will support Media Transfer Protocol (MTP) for transferring files between the device and a computer. Make sure the device offers MTP. Check the stock init.{hardware}.usb file.
  • TARGET_USE_CUSTOM_LUN_FILE_PATH ➡️ Specify a custom path to the lun file on device that directing to internal storage.

# Debug
TWRP_INCLUDE_LOGCAT := true
TARGET_USES_LOGD := true
  • TWRP_INCLUDE_LOGCAT ➡️ The source code of Custom Recovery include logcat output. It's useful for debugging and troubleshooting issues in the recovery image. This allows developers to access the logcat logs from within Custom Recovery, providing additional information about device system events, errors, and crashes.
    • Including logcat output in the recovery image can make the image larger, so it is recommended to only enable this option for debugging purposes and disable it for release builds.
  • TARGET_USES_LOGD ➡️ Uses the logd log buffer for logging messages which can be accessed using the "logcat" command.

# Excludes
TW_EXCLUDE_TWRPAPP := true
TW_EXCLUDE_APEX := true
  • Any TW_EXCLUDE_* flag ➡️ It serves to avoid adding certain functions and thus the processes & files resulting from them. Remove/Exclude anything no need and or to have minimal img file size.

# Firmware version & Developer Display name
TW_DEFAULT_DEVICE_NAME := fpluspro_H166
TW_DEVICE_VERSION := 2-fpluspro_H166_SW09 - lopestom
  • TW_DEFAULT_DEVICE_NAME ➡️ Represents the default name assigned to a device when it is built with TWRP source code. The value of this variable is typically set to the device code name or model name or custom name to provide an identifiable name for the recovery image.

  • TW_DEVICE_VERSION ➡️ Used to show the author/developer name or custom name value for a specific device version, or to specify compatibility requirements for a specific firmware version. The value will localized below the Custom Recovery name in the main page's action bar and also on the splashscreen below of Custom Recovery version.

    Click to open the Example

    IMG_2023-24

    • For some custom recoveries, this flag does not work because it depends of maintainer's choice on the Custom Recovery source code. Other cases depend on the custom theme used and the value cannot be shown.


1️⃣ BoardConfig.mk for Recovery_ramdisk in the boot.img

This is a separate part for a special reason and will not be the only one.

  • In the firmware file, the recovery.img file does not exist, just look for the boot.img file. So Recovery_ramdisk is inside boot.img file and the filesystem mountpoint certainly does not contain the \recovery1 partition. So the Split or files_info part will not have the dtbo2 file.
Click to open

# Kernel
BOARD_KERNEL_CMDLINE += androidboot.force_normal_boot=1
BOARD_BOOT_HEADER_VERSION := 2
  • androidboot.force_normal_boot=1 ➡️ Added for Android 10+ Boot Reason or System-as-root changes.

    • Resuming, when you choose Reboot to System option, then bootloader can skip recovery and boot normal Android.
  • BOARD_BOOT_HEADER_VERSION ➡️ Note that it is with version 2. I am repeating it just to make it clear that there is no version 1 currently for recovery_ramdisk for the boot.img file.

    • Note that there is no reference to RECOVERY related to the partition and its size. Understand that's the part that will tell the Custom Recovery source code about the location of the recovery_ramdisk. Therefore, use the previous settings and flags, but without RECOVERY to uses to build the recovery.img file.

# Recovery
BOARD_USES_RECOVERY_AS_BOOT := true
TARGET_NO_RECOVERY := true
TW_HAS_NO_RECOVERY_PARTITION := true
  • BOARD_USES_RECOVERY_AS_BOOT ➡️ This variable indicates whether the device uses the recovery_ramdisk part in the boot image.

    • Setup instructions differ between devices launching with Android 12 or 13 and legacy devices.
      • Not use BOARD_RECOVERYIMAGE_PARTITION_SIZE variable!
  • TARGET_NO_RECOVERY ➡️ No build the recovery.img file. Strongly recommended for A/B target devices.

  • TW_HAS_NO_RECOVERY_PARTITION ➡️ To avoid the error about /boot partition not found. Required on devices without /recovery partition.

    • BOOT/RAMDISK also exists and contains the first stage ramdisk if not using BOARD_BUILD_SYSTEM_ROOT_IMAGE.

# Tools - magiskboot
TW_INCLUDE_REPACKTOOLS := true
  • TW_INCLUDE_REPACKTOOLS ➡️ Compiles and creates the magiskboot file so that Custom Recovery has the Install Recovery Ramdisk option in the Advanced tab to install recovery.lz4.cpio on the recovery ramdisk part in the boot_$slot partition.

    Click to open the Example

    Advanced_Recovery_Ramdisk_resized




1️⃣ BoardConfig.mk for Recovery_ramdisk in the vendor_boot.img

This is a separate part for a special reason and will not be the only one.

  • In the firmware file, the recovery.img file does not exist. But like every Android, the boot.img file will be on it. The big difference is that if you find the vendor_boot.img file in the firmware file, then you have the Recovery_ramdisk in the \vendor_boot partition. The filesystem mount point certainly does not contain the \recovery partition. Therefore, the Split or files_info part will not have the kernel3 files and also the dtbo.
Click to open

# Architecture
TARGET_2ND_ARCH_VARIANT := armv8-2a
  • TARGET_2ND_ARCH_VARIANT ➡️ It's implemented just the ARMv8 ABI saying update Architecture CPU.
    • Don't be surprised, they will soon release ARMv9.

# Kernel
TARGET_NO_KERNEL := true
BOARD_VENDOR_CMDLINE := bootopt=64S3,32N2,64N2
BOARD_PAGE_SIZE := 4096
BOARD_BOOT_HEADER_VERSION := 4
BOARD_HEADER_SIZE := 2128
BOARD_FLASH_BLOCK_SIZE := 262144 ## (BOARD_PAGE_SIZE * 64).
TARGET_PREBUILT_DTB := $(DEVICE_PATH)/prebuilt/dtb
BOARD_DTB_SIZE := 191249
BOARD_DTB_OFFSET := 0x07c88000

BOARD_KERNEL_SEPARATED_DTBO := true
BOARD_RAMDISK_USE_LZ4 := true

BOARD_MKBOOTIMG_ARGS += --dtb $(TARGET_PREBUILT_DTB)
BOARD_MKBOOTIMG_ARGS += --vendor_cmdline $(BOARD_VENDOR_CMDLINE)
BOARD_MKBOOTIMG_ARGS += --pagesize $(BOARD_PAGE_SIZE) --board ""
BOARD_MKBOOTIMG_ARGS += --header_version $(BOARD_BOOT_HEADER_VERSION)
BOARD_MKBOOTIMG_ARGS += --dtb_offset $(BOARD_DTB_OFFSET)
  • TARGET_NO_KERNEL ➡️ This variable indicates if the build uses a prebuilt boot image. Setting true indicates that the kernel file is not needed.
  • BOARD_VENDOR_CMDLINE ➡️ Just a name change for correct partition identification.
  • BOARD_PAGE_SIZE ➡️ Change made for devices that have [only 64-bits] according to the new flash memory block.
  • BOARD_BOOT_HEADER_VERSION ➡️ Updated header for vendor_boot, perhaps related to kernel 5.1.xxx
  • BOARD_HEADER_SIZE ➡️ It comes from the unpacked img file information.
  • BOARD_FLASH_BLOCK_SIZE ➡️ According the part II of III table.
  • TARGET_PREBUILT_DTB ➡️ According the part II of III in the # Kernel setting because the vendor_boot partition contains only dtb file.
  • BOARD_DTB_SIZE & BOARD_DTB_OFFSET ➡️ It comes from the unpacked img file information.
  • BOARD_KERNEL_SEPARATED_DTBO ➡️ You can see in the firmware file the dtbo.img file. In the unpacked vendor_boot.img you can see only the dtb file. So need inform the source code to not compile dtbo file.
  • BOARD_RAMDISK_USE_LZ4 ➡️ Better compression of the img file where the kernel has this capability.
  • BOARD_MKBOOTIMG_ARGS ➡️ Each part of BOARD_* needs BOARD_MKBOOTIMG_ARGS for the source code to create a file with the size value property defined.

# AVB
BOARD_AVB_ENABLE := true
BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS += --flags 3
BOARD_AVB_ROLLBACK_INDEX := $(PLATFORM_SECURITY_PATCH_TIMESTAMP)
BOARD_AVB_RECOVERY_ALGORITHM := SHA256_RSA4096
BOARD_AVB_RECOVERY_KEY_PATH := external/avb/test/data/testkey_rsa4096.pem
BOARD_AVB_RECOVERY_ROLLBACK_INDEX := $(PLATFORM_SECURITY_PATCH_TIMESTAMP)
BOARD_AVB_RECOVERY_ROLLBACK_INDEX_LOCATION := 1
  • BOARD_AVB_RECOVERY_ALGORITHM & BOARD_AVB_RECOVERY_KEY_PATH ➡️ According to the BOARD_PAGE_SIZE value and the reference of AVB source code configuration.

# File systems and partitions
BOARD_VENDOR_BOOTIMAGE_PARTITION_SIZE := 67108864

# Build a separate vendor_dlkm partition
BOARD_USES_VENDOR_DLKMIMAGE := true
BOARD_VENDOR_DLKMIMAGE_FILE_SYSTEM_TYPE := ext4
TARGET_COPY_OUT_VENDOR_DLKM := vendor_dlkm

# Build a separate odm_dlkm partition
BOARD_USES_ODM_DLKMIMAGE := true
BOARD_ODM_DLKMIMAGE_FILE_SYSTEM_TYPE := ext4
TARGET_COPY_OUT_ODM_DLKM := odm_dlkm
  • BOARD_VENDOR_BOOTIMAGE_PARTITION_SIZE ➡️ The real size of vendor_boot.img file. You can put Hexadecimal or Decimal value.
  • BOARD_USES_VENDOR_DLKMIMAGE & BOARD_USES_ODM_DLKMIMAGE ➡️ Set true when the ramdisk\system\etc\recovery.fstab file in mount point has these two extra partitions.
  • TARGET_COPY_OUT_VENDOR_DLKM & TARGET_COPY_OUT_ODM_DLKM ➡️ For copying partition files to recovery ramdisk of Custom Recovery. Same process of TARGET_COPY_OUT_VENDOR in the part II of III.
    • Pay attention here to the fstype (ext4 or erofs) of the system, system_ext, product, vendor, vendor_dlkm, odm_dlkm partitions. Same as fstype of userdata partition (ext4 or f2fs).
      • Example: BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE := erofs and BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE := f2fs

# Recovery
TARGET_NO_RECOVERY := true
BOARD_EXCLUDE_KERNEL_FROM_RECOVERY_IMAGE := true
BOARD_MOVE_RECOVERY_RESOURCES_TO_VENDOR_BOOT := true
BOARD_INCLUDE_RECOVERY_RAMDISK_IN_VENDOR_BOOT := true
  • TARGET_NO_RECOVERY ➡️ Recommended when there is no \recovery partition.

  • BOARD_EXCLUDE_KERNEL_FROM_RECOVERY_IMAGE ➡️ This variable controls whether the recovery image contains a kernel or not.

  • BOARD_MOVE_RECOVERY_RESOURCES_TO_VENDOR_BOOT ➡️ When set to true, recovery resources are built to vendor_ramdisk only and aren't built to recovery/root/.

  • BOARD_INCLUDE_RECOVERY_RAMDISK_IN_VENDOR_BOOT ➡️ To build recovery resources as a standalone recovery ramdisk in vendor_boot.

    • Note that there is no reference to RECOVERY related to the partition and its size. Understand that's the part that will tell the Custom Recovery source code about the location of the recovery_ramdisk. Therefore, use the previous settings and flags, but without the BOARD_USES_RECOVERY_AS_BOOT variable as it is not necessary to compile the boot.img file.

# TWRP Configuration
TW_CUSTOM_CPU_TEMP_PATH := /sys/devices/virtual/thermal/thermal_zoneNN/temp
  • TW_CUSTOM_CPU_TEMP_PATH ➡️ You should be careful with this, as the Custom Recovery source code was recently updated to automatically search for the path. So you can remove or just put # in front of the path to know that it depends on the addressing, as the thermal_zoneNN (NN is a number) folder is managed on the device.

# Modules & Sensors
TW_LOAD_VENDOR_MODULES := "aw862xx_haptic.ko"
TW_SUPPORT_INPUT_AIDL_HAPTICS := true
TW_SUPPORT_INPUT_AIDL_HAPTICS_FQNAME := "IVibrator/default"
  • TW_LOAD_VENDOR_MODULES ➡️ The Android source code already has others variables so that it can compile module *.ko files inside boot.img, recovery.img, vendor.img, vendor_boot.img and or vendor_dlkm.img. But we have the module files located in \vendor_boot\lib\modules` and so the TW_ flag only directs the path to use one or more module files. It appears that the Custom Recovery source code has some attempt to target this automatically, since we all know the location. In this sense, for Android 12+, the modules *.ko files are located inside the vendor_dlkm.img file.
  • TW_SUPPORT_INPUT_AIDL_HAPTICS ➡️ Set true to enable makefile building for certain hardware.
  • TW_SUPPORT_INPUT_AIDL_HAPTICS_FQNAME ➡️ Enter the correct path for a given hardware and this will compile the necessary files. In that's case, files for haptics vibrators.
    • Depending of hardware type the option can have support in AIDL (hal format=" aidl ") mode or support in HIDL mode (hal format="hidl").
      • Example: TW_SUPPORT_INPUT_1_2_HAPTICS := true
    • Perhaps Custom Recovery's source code may have updated to find automatically the vibration support. But I haven't really confirmed that. Anyway, personally I don't see this part as a priority and if there is no solution there is the TW_NO_HAPTICS := true flag to disable the vibration.

Footnotes

  1. Generally the \cache partition is inserted in the mountpoint filesystem in many cases related to the recovery.img file. But it's just a partition like any other and there are no dependencies. It can be relinked with other names like *\by-name\rescue.

  2. But there are some special cases that depend on the kernel version with parts of a legacy device. It is something that depends on the choice of the company that builds the partition structure - mount point and in this case Custom Recovery will only work if you insert the dtbo.img file that is in the firmware file.

  3. The kernel is located only in boot.img which will be called Generic Boot Partition. This entire structure with vendor_boot and Header v4 is called Generic Kernel Image (GKI).

2.2.2.2 The *.mk files
2️⃣ device.mk

For ramdisk recovery with recovery.img file, it is generally not necessary to have device.mk file. But for convenience and custom with the new way of having the device tree, we just reference something simple.

Click to open


LOCAL_PATH := device/fplus/H166
  • LOCAL_PATH ➡️ This variable indicates the location of the source files in the development tree. Here, the macro function my-dir, provided by the build system, returns the path of the current directory (the directory containing the Android.mk file itself). Note that it is the same path as DEVICE_PATH.

# Dynamic Partitions stuff
PRODUCT_USE_DYNAMIC_PARTITIONS := true

# VNDK
PRODUCT_TARGET_VNDK_VERSION := 30

# API
PRODUCT_SHIPPING_API_LEVEL := 30
  • PRODUCT_TARGET_VNDK_VERSION ➡️ The VNDK requires several changes to a codebase to separate concerns between vendor and system. The binaries files in each partition must be able to work with each other.
  • PRODUCT_SHIPPING_API_LEVEL ➡️ Since the kernel interface has changed, you need to ensure you set the correct value for this and it must contain the correct Android version if your device starts with Android 11+.

PRODUCT_PLATFORM := mt6765
PRODUCT_BOARD := k62v1_64_h5
  • PRODUCT_PLATFORM ➡️ To define a hardware platform that configures the processes and routes necessary to assemble a specific Product-Chipset. Copy the same value from TARGET_BOARD_PLATFORM.
  • PRODUCT_BOARD ➡️ Same idea as above. Copy the same value from TARGET_BOOTLOADER_BOARD_NAME.

# Fastbootd stuff
PRODUCT_PACKAGES += \
    android.hardware.fastboot@1.0-impl-mock \
    android.hardware.fastboot@1.0-impl-mock.recovery \
    fastbootd
  • PRODUCT_PACKAGES ➡️ List of the modules to build. In this case, the device needs fastbootd binary files.
  • fastbootd ➡️ An optional module is installed only if it's required by the product configuration with PRODUCT_PACKAGES. The Custom Recovery need the fastboot & fastbootd for manage and flash files in the super.img partition.

# health Hal
PRODUCT_PACKAGES += \
    android.hardware.health@2.1-impl \
    android.hardware.health@2.1-service \
  • health ➡️ The files are compiled to manage the health part. There are requirements depending on each Android version.


2️⃣ device.mk for Recovery_ramdisk in the boot.img
Click to open


 # VIRTUAL A/B
ENABLE_VIRTUAL_AB := true
 
# A/B
AB_OTA_UPDATER := true

AB_OTA_PARTITIONS += \
    system \
    vendor \
    product \
    boot \
    vbmeta_vendor \
    vbmeta_system

This part is connected with # Virtual A/B OTA because the recovery ramdisk is in the boot.img file. Don't expect any Custom Recovery to install OEM update files.

  • ENABLE_VIRTUAL_AB ➡️ Comes from prop.default file by ro.virtual_ab.enabled=true line. This variable Implement A/B updates.
  • AB_OTA_UPDATER ➡️ Comes from prop.default file by ro.build.ab_update=true line. Set true to enable updating partitions through update_engine.
  • AB_OTA_PARTITIONS ➡️ Comes from prop.default file by ro.product.ab_ota_partitions=boot,system,vendor,product line. Configured by the the payload generator defines an update for list of any pair of A/B partitions defined in the same disk.

AB_OTA_POSTINSTALL_CONFIG += \
    RUN_POSTINSTALL_system=true \
    POSTINSTALL_PATH_system=system/bin/otapreopt_script \
    FILESYSTEM_TYPE_system=ext4 \
    POSTINSTALL_OPTIONAL_system=true

# Boot control HAL
PRODUCT_PACKAGES += \
    android.hardware.boot@1.1-impl-recovery \
    android.hardware.boot@1.1-impl \
    android.hardware.boot@1.1-service
    bootctrl

PRODUCT_PACKAGES += \
    bootctrl.$(TARGET_BOARD_PLATFORM) \
    bootctrl.$(TARGET_BOARD_PLATFORM).recovery

PRODUCT_PACKAGES_DEBUG += \
    bootctrl \
    update_engine_client

PRODUCT_PACKAGES += \
    otapreopt_script \
    update_engine \
    update_verifier \
    update_engine_sideload
  • PRODUCT_PACKAGES_DEBUG ➡️ Optional for debug builds.
  • PRODUCT_PACKAGES ➡️ List of the modules to build. In this case, the update process needs some files to manage process.

# MTK PlPath Utils
PRODUCT_PACKAGES += \
    mtk_plpath_utils \
    mtk_plpath_utils.recovery
  • PRODUCT_PACKAGES ➡️ List of the modules to build. In this case, a set of path-related utility that manage MTK storage.

If your device has A12+ with emulated storage without sdcardfs, add the same variable as vendor_boot is defined.



2️⃣ device.mk for Recovery_ramdisk in the vendor_boot.img

For ramdisk recovery with vendor_boot.img file, the boot.img file is called Generic Boot Partition because contains the generic ramdisk and the GKI kernel.

Click to open


# Enable project quotas and casefolding for emulated storage without sdcardfs - 
# SDCard replacement functionality
$(call inherit-product, $(SRC_TARGET_DIR)/product/emulated_storage.mk)

2.2.2.3 The *.mk files
3️⃣ twrp_devicename.mk
Click to open

# Inherit from those products. Most specific first.
$(call inherit-product, $(SRC_TARGET_DIR)/product/core_64_bit.mk)
$(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_base.mk)
#$(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
  • core_64_bit.mk ➡️ It is determined by the AOSP source code. Always use for 64-bit devices, to compile binary files and leave the structure in accordance with the Architecture.
    • For 32-bit devices, remove the above 64-bit part and use:
         # Inherit from those products. Most specific first.
         $(call inherit-product, $(SRC_TARGET_DIR)/product/core_minimal.mk)
  • aosp_base.mk ➡️ It is determined by the AOSP source code. You can use this or base.mk if you want.

# Inherit from star device
$(call inherit-product, device/brand/devicename/device.mk)
  • device.mk ➡️ Comes from android_device_brand_devicename/device.mk file. This call all variables and flags in the device.mk file to build all necesssary.

# Inherit some common recovery stuff.
$(call inherit-product, vendor/twrp/config/common.mk)

# Device identifier. This must come after all inclusions
PRODUCT_DEVICE := H166
PRODUCT_NAME := twrp_H166
PRODUCT_BRAND := Fplus
PRODUCT_MODEL := H166
PRODUCT_MANUFACTURER := Fplus
  • PRODUCT_DEVICE ➡️ Comes from prop.default file by any *.device=.
  • PRODUCT_NAME ➡️ Comes from prop.default file by any *.device=.
    • It should actually come from prop.default file by any *.name=. But by Custom Recovery or AOSP source code rules, it must be the same as PRODUCT_DEVICE after twrp_.
  • PRODUCT_BRAND ➡️ Comes from prop.default file by any *.brand=.
  • PRODUCT_MODEL ➡️ Comes from prop.default file by any *.model=.
  • PRODUCT_MANUFACTURER ➡️ Comes from prop.default file by any *.manufacture=.
    • Some of the variables maintained in a PRODUCT_ definition file have a table.


3️⃣ twrp_devicename.mk for Recovery_ramdisk in the boot.img
Click to open

# Installs gsi keys into ramdisk, to boot a developer GSI with verified boot.
$(call inherit-product, $(SRC_TARGET_DIR)/product/gsi_keys.mk)
  • gsi_keys.mk ➡️ It is determined by the AOSP source code. Installs gsi keys into ramdisk, to boot a developer GSI with verified boot.

# Virtual A/B OTA
$(call inherit-product, $(SRC_TARGET_DIR)/product/virtual_ab_ota.mk)
  • virtual_ab_ota.mk ➡️ It is determined by the AOSP source code. It is determined by the AOSP source code. Install some files in \system\bin and \system\lib64 to correctly start updating the A/B structure and thus the OTA files.
    • Look, this mode is with boot_ramdisk and therefore, many files and processes change, specially in the device.mk file because of the Android11+ structure, so they need to be updated and redone. This line can inside in the device.mk file and if you choose that, so remove line from twrp_devicename.mk file.



3️⃣ twrp_devicename.mk for Recovery_ramdisk in the vendor_boot.img
Click to open

# Configure launch_with_vendor_ramdisk.mk
$(call inherit-product, $(SRC_TARGET_DIR)/product/virtual_ab_ota/launch_with_vendor_ramdisk.mk)
  • launch_with_vendor_ramdisk.mk ➡️ It is determined by the AOSP source code. Devices launching with Virtual A/B and has a vendor_boot partition is preferred to inherit from this makefile.
    • Look, this mode is with vendor_boot_ramdisk and therefore, many files and processes change, specially in the device.mk file because of the Android12+ structure, so they need to be updated and redone. This line can inside in the device.mk file and if you choose that, so remove line from twrp_devicename.mk file.

Note

Understand that you must change some parts and know the difference to compile Custom Recovery with omni_ for A9 and earlier versions, as well as with twrp_ for A10 and later versions. For A9 and earlier use the minimal manifest platform_manifest_twrp_omni. I think you understand why there is omni at the end of the word. For A10 and later use the minimal manifest platform_manifest_twrp_aosp.

2.2.2.4 The *.mk files
4️⃣ Android.mk
Click to open

LOCAL_PATH := $(call my-dir)

ifeq ($(TARGET_DEVICE), H166)
include $(call all-subdir-makefiles,$(LOCAL_PATH))
endif
  • TARGET_DEVICE ➡️ devicename comes from prop.default file by any *.device=.


2.2.2.5 The *.mk files
5️⃣ AndroidProducts.mk
Click to open

PRODUCT_MAKEFILES := \
     $(LOCAL_DIR)/twrp_H166.mk

COMMON_LUNCH_CHOICES := twrp_H166-eng
  • PRODUCT_MAKEFILES & COMMON_LUNCH_CHOICES ➡️ devicename comes from prop.default file by any he *.device=.
    • The AndroidProducts.mk has definitions in the item 4. and the -eng is a build variant, both is from Android source code

Caution

There are many different files that depend on what the device can have. You can read more about these files in the InfoGuide recovery. Therefore, the approach below only serves as an information base for a given device, but obviously it can have many characteristics that are the same or different from other devices.

2.3 The folders /recovery/root/

Click to open

ksnip_20240125-160848

The Device Tree has these folders containing files that will be inserted directly into ramdisk. The structure of this part is the same as any stock ramdisk recovery and therefore must also follow the structure of the img stock file. In this mode we can copy the folders with the files we need and want directly to the device tree. So pay close attention to the img stock file and its folders and files so that anything that needs to be copied is actually inserted into the Device Tree.

Important

By way of understanding, this part does not involve the inclusion of encryption/decryption files. This part is in item 3. Crypt-Decrypt and if you want a device tree with that part so can put everything together in one if that is your choice.

We start by understanding the need to check the folder and file structure of stock the recovery ramdisk so that if there are any folders and files to be included in the device tree, we should do that. But in most situations, we only interact with a maximum of 5 folders with files and some specific files directly in the \recovery\root\ folder. Don't be surprised if there is no folder or file on your stock recovery ramdisk like in the example below. Just copy what you need according to what exists on your recovery ramdisk!

In the root folder the device tree can have the correct file(s) mostly as the init.recovery.mtNNNN.rc; init.recovery.usb.rc and other init.*.rc or *.rc files for encrypt-decrypt process.

2.3.1 \recovery\root\

init.recovery.usb.rc

Inside this file, there are lines of programming that refer to information that might be important to start the addressing part of USB-related drivers like adb; fastboot; MTP; fastbootd and others you need. This file also contains permission lines, the references (letters and numbers) that will direct so that Custom Recovery can have access to the internal and external storage, in addition to being able to be seen by a file manager of a laptop, computer or even another smartphone. So the device with Custom Recovery can use too platform-tools (adb-fastboot-fastbootd) to access informations, folders, files, flash files, copying anything, etc.

There are many examples for many Mediatek devices. For this reason, the following example can be used, but you should be aware that it may not be good for your Chipset device. You should compare the examples with the stock file located at \vendor\etc\init\hw\init.mtNNNN.usb.rc for improvements and understanding.

Carry out tests and find the best file that can solve the case.

Example - Click to open

  on early-init
      write /sys/module/musb_hdrc/parameters/kernel_init_done 1

  on init
      setprop sys.usb.configfs 1
      setprop sys.usb.ffs.aio_compat 1
      setprop vendor.usb.controller "musb-hdrc"
      setprop vendor.usb.acm_cnt 0
      setprop vendor.usb.acm_port0 ""
      setprop vendor.usb.acm_port1 ""
      setprop vendor.usb.acm_enable 0

  on property:ro.boot.usbcontroller=*
      setprop sys.usb.controller ${ro.boot.usbcontroller}

  on fs
      mkdir /config
      mkdir /dev/usb-ffs 0770 shell shell
      mkdir /dev/usb-ffs/adb 0770 shell shell
      mount configfs none /config
      mkdir /config/usb_gadget/g1 0770 shell shell
      mkdir /config/usb_gadget/g1/strings/0x409 0770 shell shell
      write /config/usb_gadget/g1/bcdDevice 0x0223
      write /config/usb_gadget/g1/bcdUSB 0x0200
      write /config/usb_gadget/g1/os_desc/use 1
      write /config/usb_gadget/g1/strings/0x409/serialnumber ${ro.serialno}
      write /config/usb_gadget/g1/strings/0x409/manufacturer ${ro.product.manufacturer}
      write /config/usb_gadget/g1/strings/0x409/product ${ro.product.model}
      mkdir /config/usb_gadget/g1/functions/mass_storage.usb0
      mkdir /config/usb_gadget/g1/functions/ffs.adb
      mkdir /config/usb_gadget/g1/functions/mtp.gs0
      write /config/usb_gadget/g1/functions/mtp.gs0/os_desc/interface.MTP/compatible_id "MTP"
      mkdir /config/usb_gadget/g1/configs/b.1 0770 shell shell
      mkdir /config/usb_gadget/g1/configs/b.1/strings/0x409 0770 shell shell
      write /config/usb_gadget/g1/os_desc/b_vendor_code 0x1
      write /config/usb_gadget/g1/os_desc/qw_sign "MSFT100"
      write /config/usb_gadget/g1/configs/b.1/MaxPower 500
      symlink /config/usb_gadget/g1/configs/b.1 /config/usb_gadget/g1/os_desc/b.1
      mount functionfs adb /dev/usb-ffs/adb uid=2000,gid=2000
      write /sys/class/android_usb/android0/f_ffs/aliases adb

  on property:sys.usb.config=none && property:sys.usb.configfs=1
      write /config/usb_gadget/g1/UDC "none"
      stop adbd
      setprop sys.usb.ffs.ready 0
      setprop sys.usb.ffs.mtp.ready 0
      write /config/usb_gadget/g1/bDeviceClass 0
      write /config/usb_gadget/g1/bDeviceSubClass 0
      write /config/usb_gadget/g1/bDeviceProtocol 0
      rm /config/usb_gadget/g1/configs/b.1/f1
      rm /config/usb_gadget/g1/configs/b.1/f2
      #rmdir /config/usb_gadget/g1/functions/rndis.gs4
      write /sys/devices/platform/mt_usb/saving 0
      setprop sys.usb.state ${sys.usb.config}

  on property:sys.usb.ffs.ready=1 && property:sys.usb.config=adb && property:sys.usb.configfs=1
      write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "adb"
      write /config/usb_gadget/g1/idVendor 0x18d1
      write /config/usb_gadget/g1/idProduct 0xd001
      write /config/usb_gadget/g1/os_desc/use 1
      symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f1
      write /config/usb_gadget/g1/UDC ${sys.usb.controller}
      setprop sys.usb.state ${sys.usb.config}

  on property:sys.usb.config=sideload && property:sys.usb.ffs.ready=1 && property:sys.usb.configfs=1
      write /config/usb_gadget/g1/idVendor 0x18d1

  on property:sys.usb.config=mtp && property:sys.usb.configfs=1
      setprop sys.usb.ffs.mtp.ready 1
      write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "mtp"
      rm /config/usb_gadget/g1/configs/b.1/f1
      rm /config/usb_gadget/g1/configs/b.1/f2
      write /config/usb_gadget/g1/idVendor 0x22d9
      write /config/usb_gadget/g1/idProduct 0x2764
      write /config/usb_gadget/g1/os_desc/use 1
      symlink /config/usb_gadget/g1/functions/mtp.gs0 /config/usb_gadget/g1/configs/b.1/f1
      write /config/usb_gadget/g1/UDC ${sys.usb.controller}
      setprop sys.usb.state ${sys.usb.config}

  on property:sys.usb.config=mtp,adb
      start adbd

  on property:sys.usb.ffs.ready=1 && property:sys.usb.config=mtp,adb && property:sys.usb.configfs=1
      setprop sys.usb.ffs.mtp.ready 1
      write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "mtp_adb"
      rm /config/usb_gadget/g1/configs/b.1/f1
      rm /config/usb_gadget/g1/configs/b.1/f2
      write /config/usb_gadget/g1/idVendor 0x22d9
      write /config/usb_gadget/g1/idProduct 0x2765
      write /config/usb_gadget/g1/os_desc/use 1
      symlink /config/usb_gadget/g1/functions/mtp.gs0 /config/usb_gadget/g1/configs/b.1/f1
      symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2
      write /config/usb_gadget/g1/UDC ${sys.usb.controller}
      setprop sys.usb.state ${sys.usb.config}

For knowledge, you can read and try something with the guide Troubleshooting or/and if device is using configfs, check Linux USB gadget instructions.

init.recovery.mtNNNN.rc

Comes from stock ramdisk_recovery by init.recovery.mtNNNN.rc file. For Custom Recovery builds without encryption/decryption, we just copy the stock init.recovery.mtNNNN.rc file and add some small extra parts.

Example - Click to open

   on init
       setprop sys.usb.configfs 1
       setprop sys.usb.ffs.aio_compat 0

   on fs && property:ro.debuggable=0
       # distinguish USB shoulde connect or not, i.e. CDP vs SDP
       write /sys/class/udc/musb-hdrc/device/cmode 2
       # set charging free due to it wait for USB activation
       start adbd

   on post-fs
       # Support A/B feature for EMMC and UFS boot region
       symlink /dev/block/sda /dev/block/mmcblk0boot0
       symlink /dev/block/sdb /dev/block/mmcblk0boot1
       symlink /dev/block/mmcblk0boot0 /dev/block/platform/bootdevice/by-name/preloader_a
       symlink /dev/block/mmcblk0boot1 /dev/block/platform/bootdevice/by-name/preloader_b
       symlink /dev/block/mmcblk0boot0 /dev/block/by-name/preloader_a
       symlink /dev/block/mmcblk0boot1 /dev/block/by-name/preloader_b

       exec u:r:update_engine:s0 root root -- /system/bin/mtk_plpath_utils

The above part should come from your stock init.recovery.mtNNNN.rc file. The part below has extra inclusions. Combine the two parts into a single init.recovery.mtNNNN.rc file.

       start mtk.plpath.utils.link

   service mtk.plpath.utils.link /system/bin/mtk_plpath_utils
       class main
       user root
       group root system
       oneshot
       disabled
       seclabel u:r:recovery:s0

   on boot
        start boot-hal-1-2
        start health-hal-2-1

Tip

Pay attention to the version of the stock files boot-hal-*N-*n; health-hal-*N-*n as they may be different due to the Android version.

2.3.2 \recovery\root\lib\modules\

As we know from the InfoGuide Touchscreen not working for Android 12+ version, the *.ko file folder with hardware modules is located in certain folders of the stock recovery_ramdisk and/or also in the stock vendor.img file. These *.ko module files will be useful for mainly enabling touch screen.

Either way, copy the entire stock folder and ALL files.

2.3.3 \recovery\root\first_stage_ramdisk

As we know by the partition dependency information Table, the first_stage_ramdisk folder is only needed if your ramdisk_recovery does not have the recovery.img file.

Inside these folder has files or a unique file like fstab.mtNNNN or and fstab.emmc. Copy only the file(s) from the same stock recovery_ramdisk\first_stage_ramdisk folder.


Some folders are mandatory because they contain important files that must be included in the device tree. But depending on each case, device-Chipset and Android version, we may include folders and files in the device tree that do not exist in the stock recovery ramdisk. These new folders and files can be used to try to solve something or just customize, as long as they are for really useful purposes. By adding irrelevant folders and files, you will be adding empty and useless parts to Custom Recovery.

2.3.4 \recovery\root\system\

  • bin\

    mtk_plpath_utils

    Copy the file from the same stock recovery_ramdisk\bin folder.

  • etc\

    fstab.postinstall

    task_profiles.json

    Copy the files from the same stock system.img in the \system\etc folder.

    recovery.fstab

    Copy the fstab file from the same stock system.img in the \system\etc folder. But for quick and performance mounting important partition map, leave this file with only the some partitions.

    Example - Click to open

       # 341 "<built-in>" 3
       # 141 "vendor/mediatek/proprietary/hardware/fstab/mt6877/fstab.in.mt6877"
       system /system ext4 ro wait,slotselect,avb=vbmeta_system,logical,first_stage_mount,avb_keys=/avb/q-gsi.avbpubkey:/avb/r-gsi.avbpubkey:/avb/s-gsi.avbpubkey
       vendor /vendor ext4 ro wait,slotselect,avb,logical,first_stage_mount
       product /product ext4 ro wait,slotselect,avb,logical,first_stage_mount
     
       /dev/block/by-name/metadata    /metadata    ext4    noatime,nosuid,nodev,discard    wait,check,formattable,first_stage_mount
    
       /dev/block/by-name/userdata    /data    f2fs    noatime,nosuid,nodev,discard,noflush_merge,fsync_mode=nobarrier,reserve_root=134217,resgid=1065,inlinecrypt wait,check,formattable,quota,reservedsize=128m,latemount,resize,checkpoint=fs,fileencryption=aes-256-xts:aes-256-cts:v2+inlinecrypt_optimized,keydirectory=/metadata/vold/metadata_encryption,fsverity
    
       /dev/block/by-name/misc    /misc    emmc    defaults    defaults
       /dev/block/by-name/boot    /boot    emmc    defaults    first_stage_mount,nofail,slotselect

    twrp.flags

    The twrp.fstab or twrp.flags files must contain the necessary partitions for mounting, backup and also for the Custom Recovery to be able to make the MicroSD block partition (external_sd) and or OTG examine and mount (open) this in your internal filemanager or external filemanagers as well as give read and write capability. The twrp.flags files must be edited according to your stock recovery.fstab file. But as a rule of Custom Recovery, the way it is written will be different and therefore must follow the following sequence:

        |  mount point  |  fstype  |  device  |  [device2]  |  [options - flags]

    There are many Mediatek Chipset devices and for this reason, the following example can be used, but you should be aware that you MUST COMPARE the example with the stock recovery.fstab file and make all necessary changes in the twrp.flag file.

    Example - Click to open

       # Superimage Logical Partitions
       /system_image   emmc      /dev/block/bootdevice/by-name/system       flags=display="System_Image";backup=1;flashimg=1;slotselect
       /vendor_image   emmc      /dev/block/bootdevice/by-name/vendor       flags=display="Vendor_Image";backup=1;flashimg=1;slotselect
       /product_image  emmc      /dev/block/bootdevice/by-name/product      flags=display="Product_Image";backup=1;flashimg=1;slotselect
    
       # Dynamic Partitions
       /system_root   ext4   /dev/block/bootdevice/by-name/system      flags=display="System";backup=0;wipeingui;slotselect
       /vendor        ext4   /dev/block/bootdevice/by-name/vendor      flags=display="Vendor";backup=0;wipeingui;slotselect
       /product       ext4   /dev/block/bootdevice/by-name/product     flags=display="Product";backup=0;wipeingui;slotselect
    
    
       # mount point       fstype            device                                              flags
       /protect_f          ext4      /dev/block/platform/bootdevice/by-name/protect1         flags=display="protect_f";backup=1
       /protect_s          ext4      /dev/block/platform/bootdevice/by-name/protect2         flags=display="protect_s";backup=1
       /nvdata             ext4      /dev/block/platform/bootdevice/by-name/nvdata           flags=display="NvData";backup=1
       /nvcfg              ext4      /dev/block/platform/bootdevice/by-name/nvcfg            flags=display="NvCfg";backup=1
       /persist            ext4      /dev/block/platform/bootdevice/by-name/persist          flags=display="Persist";backup=1
       /persist_image      emmc      /dev/block/platform/bootdevice/by-name/persist          flags=display="Persist_Image";backup=1;flashimg=1
       /persistent         emmc      /dev/block/platform/bootdevice/by-name/frp              flags=display="frp";backup=1;flashimg=1
       /nvram              emmc      /dev/block/platform/bootdevice/by-name/nvram            flags=display="NvRam";backup=1;flashimg=1
       /proinfo            emmc      /dev/block/platform/bootdevice/by-name/proinfo
       /boot               emmc      /dev/block/platform/bootdevice/by-name/boot             flags=display="boot";flashimg=1;slotselect
       /logo               emmc      /dev/block/platform/bootdevice/by-name/logo             flags=display="logo";backup=1;flashimg=1;slotselect
       /expdb              emmc      /dev/block/platform/bootdevice/by-name/expdb
       /seccfg             emmc      /dev/block/platform/bootdevice/by-name/seccfg          
       /scp1               emmc      /dev/block/platform/bootdevice/by-name/scp1          
       /scp2               emmc      /dev/block/platform/bootdevice/by-name/scp2      
       /gz1                emmc      /dev/block/platform/bootdevice/by-name/gz1      
       /gz2                emmc      /dev/block/platform/bootdevice/by-name/gz2                 
       /spmfw              emmc      /dev/block/platform/bootdevice/by-name/spmfw                  
       /dtbo               emmc      /dev/block/platform/bootdevice/by-name/dtbo                  
       /otp                emmc      /dev/block/platform/bootdevice/by-name/otp             
       /lk                 emmc      /dev/block/platform/bootdevice/by-name/bootloader       flags=display="lk";backup=1;flashimg=1
       /lk2                emmc      /dev/block/platform/bootdevice/by-name/bootloader2      flags=display="lk2";backup=1;flashimg=1
       /tee1               emmc      /dev/block/platform/bootdevice/by-name/tee1
       /tee2               emmc      /dev/block/platform/bootdevice/by-name/tee2
    
       # AVB
       /vbmeta             emmc      /dev/block/platform/bootdevice/by-name/vbmeta           flags=display="vbmeta";backup=1;flashimg=1;slotselect
       /vbmeta_system      emmc      /dev/block/platform/bootdevice/by-name/vbmeta_system    flags=display="vbmeta_system";backup=1;flashimg=1;slotselect
       /vbmeta_vendor      emmc      /dev/block/platform/bootdevice/by-name/vbmeta_vendor    flags=display="vbmeta_vendor";backup=1;flashimg=1;slotselect
    
    
       # External Storage
       /external_sd      auto      /dev/block/mmcblk1p1      /dev/block/mmcblk1      flags=display="MicroSDCard";storage;wipeingui;removable
       /usb-otg          auto      /dev/block/sda1      /dev/block/sda      flags=display="Usb_Otg";storage;wipeingui;removable;fsflags="utf8"

    If the Custom Recovery not mount MicroSDCard and or OTG, you can get some informations from device using some tools like adb-fastboot, termux (need ROOT), ADB RUN or any other good tool. Insert MicroSDCard or and OTG of any size so that the external_sd / usb-otg address can look and later you should change correctlly in the twrp.flag file. The example below show how have the correct sizes.

    Example - Click to open

       c:\adb>adb -s XXXXXXXXX shell cat /proc/partitions`

    XXXXXXXXX ➡️ It's the device serial number.

       c:\adb>adb devices
       XXXXXXXXX        authorized

    ksnip_20240211-011159

    Copy the file from the same stock system.img in the \system\etc\vintf folder. You can add more files like compatibility_matrix.xml if you want.

  • lib64\

    • hw\

      android.hardware.boot@1.0-impl-1.2-mtkimpl.so

    Adding something in the lib64\ folder depends on each OEM firmware and the processes need to work. Copy the file from the same stock recovery_ramdisk\system\lib64\hw folder.

Tip

Pay attention to the version of the stock file android.hardware.boot@*N.*n-impl-*N.*n-mtkimpl.so as they may be different due to the Android version.


2.3.5 \recovery\root\vendor\

  • ueventd.rc

    Copy the file from the same stock vendor.img in the \vendor folder if firmware file have recovery.img file.

  • etc\

    • vintf\

      manifest.xml

    Copy the file from the same stock vendor.img in the \vendor\etc\vintf folder. You can add more files like compatibility_matrix.xml if you want.

    ueventd.rc

    With firmware file have only boot.img file or have vendor_boot.img file, copy the stock \vendor\etc\ueventd.rc file from the stock vendor.img file to device tree vendor\etc folder.

  • firmware\

    As we know from the InfoGuide Touchscreen not working for Android 10+ version, the firmware folder can have hardware binary files of the stock vendor.img file. These *.bin files will be useful for mainly enabling touch screen. But if the correct files are not in that folder, you should check the stock vendor.img file in the \vendor\lib\modules\ folder.

  • lib\

    • modules\

    As we know from the InfoGuide Touchscreen not working for Android 10+ version, the *.ko files with hardware modules is located in certain folders of the stock vendor.img file in the \vendor\lib\modules\ folder. These *.ko files will be useful for mainly enabling touch screen.

If the correct files are not in that folder, you should check the firmware file if have vendor_dlkm.img file and so confirm in the \vendor_dlkm\lib\modules\ folder.


To better understand the organization of the structure with files, the example below is for an MT6833 device:

Click to open

ksnip_20240210-112914


Note

This InfoGuide is not intended to cover extra topics about folders and files beyond what is necessary or for extra customization. So understand that if your Custom Recovery has problems that cannot be easily resolved, then it is time to ask for help and find experts or experienced developers.

3. Crypt-Decrypt

Many times, even with all the correct files and processes, there is a dependency on the Custom Recovery source code. Obviously, Custom Recovery being a type of OS, it needs to interact correctly and be updated in order to have functionality according to the Android version.

So being sure which files and how the encryption process works is important. Having confidence and conviction that everything is right makes you understand the limits on the Custom Recovery source code. Don't get frustrated if something doesn't work. Sometimes the Custom Recovery source code takes time to update, but in this case you must confirm who failed.

3.1 Process & Files

The way the encryption process occurs and how it can be decrypted is not the subject here! This requires a lot of programming knowledge and experience with firmware. Note that depending on the Android version originally shipped to the device, encryption modes may have FDE (deprecated in Android 11+) and currently FBE. The files to enable these modes can have FDE binaries + gatekeeper or FBE binaries + gatekeeper.

Important

This InfoGuide is only intended to highlight FBE mode how BoardConfig.mk is set in the # Crypto item. It can serve as something similar for FDE mode, but the flags must be different.

The fact is that there can be many encryption types, some of which are obsolete, others continue in a different form and others are still in use, and may have updates depending on the kernel and Android version. But currently there are three types of encryption for most Mediatek devices. In this document there will be no guidance for any type of encryption for a specific manufacturing company, because many devices from the same company may have different types of encryption.

First we must know what type of encryption is applied to the device. There are a few ways to identify that.

  • Unpack the stock recovery ramdisk img file and open the prop.default file. Find the trust or trustkernel or tee or beanpod or trustonic line;
  • Unzip the stock super.img\vendor.img file and find the \bin\hw folder look if have is some file called *-service.beanpod or *-service.trustkernel or *-service.trustonic;
  • Unzip the stock super.img\vendor.img file and find the \etc\init folder look if have is some file called microtrust.rc or trustkernel.rc or trustonic.rc;
  • With ROOT you can use adb with the adb getprop command to obtain information from the prop.default file and thus search for the type of encryption.

Tip

  • How to know which binary files are dependent on other binary files?

    Read and learn how to use ldcheck. Change the file reference in the vendor\bin\qseecomd folder to its reference in the vendor\bin\ folder of the file's encryption type.

  • If you want to read and understand about Actions and Services as a way of executing processes, then read Android Init Language.

3.2 Trustkernel

This type of encryption is not widely used. But when it exists on a device, it has been the most annoying and frustrating way to try to get it to work. Generally speaking, some developers with Android 9 devices were able to do something. But with the device shipping with Android 10, it didn't work the same way. But a smart and hardy guy developer named @ADeadTrousers took a while for other users to have something actually working on Android 10 and Android 11.

Click to open

Understanding this, you should find some files related to trustkernel. These files come from the stock vendor.img file and must be located in:

  • \vendor\bin
    • teed
  • \vendor\bin\hw
    • android.hardware.gatekeeper@1.0-service
    • android.hardware.keymaster@4.0-service.trustkernel
    • vendor.mediatek.hardware.keymaster_attestation@1.1-service
  • \vendor\etc\init
    • android.hardware.gatekeeper@1.0-service.rc
    • android.hardware.keymaster@4.0-service.trustkernel.rc
  • \vendor\etc\vintf
    • manifest.xml
  • \vendor\lib64
    • libkmsetkey.so
    • libteec.so
    • vendor.mediatek.hardware.keymaster_attestation@1.0.so
    • vendor.mediatek.hardware.keymaster_attestation@1.1.so
  • \vendor\lib64\hw
    • android.hardware.gatekeeper@1.0-impl.so
    • gatekeeper.trustkernel.so
    • kmsetkey.trustkernel.so
    • libSoftGatekeeper.so
    • vendor.mediatek.hardware.keymaster_attestation@1.1-impl.so
  • \vendor\app\t6 & \vendor\app\t6\data
    • Get the entire \app folder and all the files.

Pay attention to file updates! Example: The above android.hardware.keymaster@4.0-service.trustkernel file can change to android.hardware.keymaster@4.1-service.trustkernel or android.hardware.security.keymint-service.trustkernel.rc. So you must modify every part of files where this *-service.trustkernel file is being referenced.

There are other files, but they are optional (maybe):

  • \vendor\bin
    • kph
    • pld
    • tee_check_keybox
  • \vendor\lib64
    • libkphhelper.so
    • libkphproxy.so
    • libpl.so

As a preference, get a device tree that actually works, even if it is to compile the recovery.img file. It has been tested by compiling the Custom Recovery in boot.img file and it works. So don't forget to thank and give credits to @ADeadTrousers.

  • android\brand\devicename\recovery\root
    There may be differences between devices, so open the stock ramdisk\init.recovery.{hardware}.rc file and note the on post-fs line in the init.recovery.mtNNNN.rc file below.
    • init.recovery.mtNNNN.rc

      Click to open

       import /init.recovery.trustkernel.rc
       import /vendor/etc/init/trustkernel.rc
       import /vendor/etc/init/android.hardware.gatekeeper@1.0-service.rc
       import /vendor/etc/init/android.hardware.keymaster@4.0-service.trustkernel.rc
          
       on post-fs
       # **COPY YOUR STOCK ramdisk\init.recovery.{hardware}.rc `on post-fs` FILE HERE!!**
       
        start mtk.plpath.utils.link
      
       service mtk.plpath.utils.link /system/bin/mtk_plpath_utils
           class main
           user root
           group root system
           disabled
           oneshot
           seclabel u:r:recovery:s0
      
       on boot
           start boot-hal-1-1
           start health-hal-2-1

    • init.recovery.trustkernel.rc

      This is the script file that performs the decryption and is referenced (import) line in the init.recovery.mtNNNN.rc file. Note that there are processes and phases of file targeting so that decryption can be done.

      Click to open

       on fs
           mkdir /mnt/vendor 0755 system system
           mkdir /mnt/vendor/apd 0771 system system
           mkdir /mnt/vendor/protect_f 0770 system system
           mkdir /mnt/vendor/protect_s 0770 system system
           mkdir /mnt/vendor/persist 0755 system system
           mkdir /mnt/vendor/nvdata 0771 system system
           mkdir /mnt/vendor/nvcfg 0771 system system
           mount ext4 /dev/block/by-name/apd /mnt/vendor/apd rw wait
           mount ext4 /dev/block/by-name/protect1 /mnt/vendor/protect_f rw wait
           mount ext4 /dev/block/by-name/protect2 /mnt/vendor/protect_s rw wait
           mount ext4 /dev/block/by-name/persist /mnt/vendor/persist rw wait
           mount ext4 /dev/block/by-name/nvdata /mnt/vendor/nvdata rw wait
           mount ext4 /dev/block/by-name/nvcfg /mnt/vendor/nvcfg rw wait
           mkdir /mnt/vendor/persist/t6_twrp 0755 system system
           mkdir /mnt/vendor/protect_f/tee_twrp 0755 system system
           exec u:r:recovery:s0 system -- /vendor/bin/trustkernel.twrp.sh
           install_keyring
           setprop crypto.ready 1
      
       service keystore_auth /system/bin/keystore_auth
           oneshot
           user system
           group root
           disabled
           seclabel u:r:recovery:s0
      
       service keystore /system/bin/keystore /tmp/misc/keystore
           user root
           group root drmrpc readproc
           disabled
           seclabel u:r:recovery:s0
      
       on property:hwservicemanager.ready=true
           start vendor.keymaster-4-0-trustkernel
           start vendor.gatekeeper-1-0
      
       on property:ro.crypto.state=unsupported
           stop teed
           stop vendor.keymaster-4-0-trustkernel
           stop vendor.gatekeeper-1-0
      
       on property:ro.crypto.state=unencrypted
           stop teed
           stop vendor.keymaster-4-0-trustkernel
           stop vendor.gatekeeper-1-0
      
       on property:twrp.decrypt.done=true
           stop teed
           stop vendor.keymaster-4-0-trustkernel
           stop vendor.gatekeeper-1-0

Some text files are important to know how they are written and to place inside the init.recovery.mtNNNN.rc file like android.hardware.gatekeeper@1.0-service.rc and android.hardware.keymaster@4.0-service.trustkernel.rc. You can choose to remove these files from the folder and place them inside the init.recovery.mtNNNN.rc file. This is optional. So if you do that, remove the reference (symlink) line from the same file in the init.recovery.mtNNNN.rc file. Remove the aforementioned files from the \vendor\etc\init folder so there is no confusion.

Add the line below so that Custom Recovery has permission over the process. This should happen for all *-service files.

     seclabel u:r:recovery:s0

As we will copy what the script author did, it is necessary to compare the stock file vendor\etc\init\trustkernel.rc with the file below. If there are any modifications to be made, then do as the stock file has.

Click to open

  on post-fs
      write /proc/bootprof "tkcore: prepare system ta path"

      restorecon /mnt/vendor/persist
      mkdir /mnt/vendor/persist/t6_twrp
      chown system system /mnt/vendor/persist/t6_twrp
      restorecon /mnt/vendor/persist/t6_twrp

      restorecon /mnt/vendor/protect_f
      mkdir /mnt/vendor/protect_f/tee_twrp
      chown system system /mnt/vendor/protect_f/tee_twrp
      restorecon /mnt/vendor/protect_f/tee_twrp

      start teed

  on property:vendor.trustkernel.fs.state=prepare
      write /proc/bootprof "tkcore: prepare basic"
      mkdir /data/vendor/t6
      chown system system /data/vendor/t6
      restorecon /data/vendor/t6

      write /proc/bootprof "tkcore: prepare sfs"
      mkdir /data/vendor/t6/fs
      chown system system /data/vendor/t6/fs
      restorecon /data/vendor/t6/fs

      write /proc/bootprof "tkcore: prepare service provider ta path"
      mkdir /data/vendor/t6/app
      chown system system /data/vendor/t6/app
      restorecon /data/vendor/t6/app
      setprop vendor.trustkernel.fs.state ready

  # For non-encrypted case
  on property:ro.crypto.state=unencrypted
      setprop vendor.trustkernel.fs.mode 1
      setprop vendor.trustkernel.fs.state prepare

  # For FDE/encrypted successfully
  on property:vold.decrypt=trigger_restart_framework
      setprop vendor.trustkernel.fs.mode 2
      setprop vendor.trustkernel.fs.state prepare

  # For FBE/encrypted successfully
  on property:ro.crypto.type=file && property:ro.crypto.state=encrypted
      setprop vendor.trustkernel.fs.mode 3
      setprop vendor.trustkernel.fs.state prepare

  on property:vendor.trustkernel.log.state=ready
      write /proc/bootprof "tkcore: prepare log file"
      restorecon /data/vendor/t6/tkcore.log
      setprop vendor.trustkernel.log.state enable

  on property:vendor.trustkernel.ready=true
      start tee_check_keybox

  service teed /vendor/bin/teed \
      --datapath /data/vendor/t6/fs \
      --sptapath /data/vendor/t6/app \
      --systapath /vendor/app/t6 \
      --rpmbdev /dev/mmcblk0rpmb \
      --rpmbdev /dev/rpmb0 \
      --prot /mnt/vendor/persist/t6_twrp \
      --prot /mnt/vendor/protect_f/tee_twrp \
      --logpath /data/vendor/t6/tkcore.log \
      --proprefix vendor.trustkernel
      capabilities SYS_RAWIO
      user system
      group system
      class core
      seclabel u:r:recovery:s0

  service tee_check_keybox /vendor/bin/tee_check_keybox
      user system
      group system
      class main
      disabled
      oneshot
      seclabel u:r:recovery:s0

If everything is ok, then copy the above script with the name trustkernel.rc as it came from stock in the same folder in the device tree.

Again there is another script file that the author made, but we just copied it to the android\brand\devicename\recovery\root\vendor\bin\trustkernel.twrp.sh folder as you can see below.

Click to open

   #!/sbin/sh

    rm -rf /mnt/vendor/persist/t6_twrp/*
    cp -rfp /mnt/vendor/persist/t6/* /mnt/vendor/persist/t6_twrp

    rm -rf /mnt/vendor/protect_f/tee_twrp/*
    cp -rfp /mnt/vendor/protect_f/tee/* /mnt/vendor/protect_f/tee_twrp

Files come from the stock system.img file and must be located in:

  • \system\etc\vintf
    • manifest.xml

Copy all folders and all files within \vendor to the device tree under android\brand\devicename\recovery\root\vendor\ and all files within \system to the device tree under android\brand\devicename\recovery\root\system\. Remember that the files init.recovery.mtNNNN.rc and init.recovery.trustkernel.rc must be in android\brand\devicename\recovery\root.

To better understand the organization of the structure with encryption/decryption files, an example below for an MT6762 device:

Click to open

ksnip_20240206-215700_resized

Currently I have seen two devices shipping with Android 12 - kernel 5.1.xxx which has trustkernel. But it hasn't worked yet (tests in one device MT6789 carried out until October 2023) as far as I know. Maybe someone sucessded.

3.3 Beanpod (microtrust)

This type of encryption is one of the smoothest types there is to run on a device. Not only because of the simplicity of just a few files, but because since before Android 9, it has always worked without difficulties and extra efforts. Well, for Android 11+ versions it all depends on the Custom Recovery source code.

Click to open

Understanding this, you should find some files related to beanpod. These files come from the stock vendor.img file and must be located in:

  • \vendor\bin
    • teei_daemon
  • \vendor\bin\hw
    • android.hardware.gatekeeper@1.0-service
    • android.hardware.keymaster@4.1-service.beanpod
    • vendor.mediatek.hardware.keymaster_attestation@1.1-service
  • \vendor\etc\vintf
    • manifest.xml
  • \vendor\lib64
    • libimsg_log.so
    • libTEECommon.so
    • libteei_daemon_vfs.so
    • vendor.mediatek.hardware.keymaster_attestation@1.0.so
    • vendor.mediatek.hardware.keymaster_attestation@1.1.so
  • \vendor\lib64\hw
    • android.hardware.gatekeeper@1.0-impl.so
    • gatekeeper.beanpod.so
    • gatekeeper.default.so
    • kmsetkey.beanpod.so
    • libSoftGatekeeper.so
    • vendor.mediatek.hardware.keymaster_attestation@1.1-impl.so
  • \vendor\thh\ta
    • Get the entire \thh folder and all the files.

Pay attention to file updates! Example: The above android.hardware.keymaster@4.1-service.beanpod file can change to android.hardware.keymaster@4.0-service.beanpod or android.hardware.security.keymint-service.beanpod.rc. So you must modify every part of files where this *-service.beanpod file is being referenced.

In tests carried out with Custom Recoveries, they did not need to include files with vendor.mediatek.hardware.keymaster_attestation**, as decryption worked without them. So that's optional.

  • android\brand\devicename\recovery\root
    There may be differences between devices, so open the stock ramdisk\init.recovery.{hardware}.rc file and note the line on post-fs through on post-fs in the init.recovery.mtNNNN.rc file below.
    • init.recovery.mtNNNN.rc

      Click to open

         import /init.recovery.microtrust.rc
      
         on init
             # Create a more standard /dev/block layout for our scripts
             symlink /dev/block/platform/bootdevice /dev/block/bootdevice
             export LD_LIBRARY_PATH /system/lib64:/vendor/lib64:/vendor/lib64/hw:/system/lib64/hw
      
         on fs
             mkdir /mnt/vendor/persist 0771 root root
             mount ext4 /dev/block/platform/bootdevice/by-name/persist /mnt/vendor/persist
      
             install_keyring
             setprop crypto.ready 1
      
         service keystore_auth /system/bin/keystore_auth
             oneshot
             user system
             group root
             disabled
             seclabel u:r:recovery:s0
      
         service keystore /system/bin/keystore /tmp/misc/keystore
             user root
             group root drmrpc readproc
             disabled
             seclabel u:r:recovery:s0
      
         service gatekeeper-1-0 /vendor/bin/hw/android.hardware.gatekeeper@1.0-service
             interface android.hardware.gatekeeper@1.0::IGatekeeper default
             class hal
             user root
             group root
             disabled
             seclabel u:r:recovery:s0
      
         service keymaster-4-1 /vendor/bin/hw/android.hardware.keymaster@4.1-service.beanpod
             interface android.hardware.keymaster@4.0::IKeymasterDevice default
             interface android.hardware.keymaster@4.1::IKeymasterDevice default
             class early_hal
             user root
             group root drmrpc
             disabled
             seclabel u:r:recovery:s0
      
         on property:vendor.sys.listener.registered=true
             start gatekeeper-1-0
             start keymaster-4-1
      
         on property:crypto.ready=1
             start keymaster-4-1
      
         on property:hwservicemanager.ready=true
             start keymaster-4-1
             start gatekeeper-1-0
      
         on property:ro.crypto.state=unsupported
             stop teei_daemon
             stop keymaster-4-1
             stop gatekeeper-1-0
      
         on property:ro.crypto.state=unencrypted
             stop teei_daemon
             stop keymaster-4-1
             stop gatekeeper-1-0
      
         on property:twrp.decrypt.done=true
             stop teei_daemon
             stop keymaster-4-1
             stop gatekeeper-1-0
      
         on init
         # **COPY YOUR STOCK ramdisk\init.recovery.{hardware}.rc `oon init` FILE HERE!!**
      
         on fs && property:ro.debuggable=0
         # **COPY YOUR STOCK ramdisk\init.recovery.{hardware}.rc `on fs` FILE HERE!!**
      
         on post-fs
             # Support A/B feature for EMMC and UFS boot region
          # **COPY YOUR STOCK ramdisk\init.recovery.{hardware}.rc `on post-fs` FILE HERE!!**
       
             start mtk.plpath.utils.link
      
         service mtk.plpath.utils.link /system/bin/mtk_plpath_utils
             class main
             user root
             group root system
             oneshot
             disabled
             seclabel u:r:recovery:s0
      
         on boot
             start boot-hal-1-2
             start health-hal-2-1

Some text files are important to know how they are written and place them inside the init.recovery.mtNNNN.rc file, such as android.hardware.gatekeeper@1.0-service.rc and android.hardware.keymaster@4.1-service.beanpod.rc. You can choose to remove these files from the folder and place them inside the init.recovery.mtNNNN.rc file. This is optional and please note this is what I did. Also note that there is no inclusion (import) line of the same file in init.recovery.mtNNNN.rc related to the files mentioned in the stock folder \vendor\etc\init.

  • init.recovery.microtrust.rc

    This is the script file that performs the decryption and is referenced (import) line in the init.recovery.mtNNNN.rc file. Note that there are processes and phases of file targeting so that decryption can be done. It is necessary to compare the stock file vendor\etc\init\microtrust.rc with the file below. If there are any modifications to be made, do so according to the stock file.

    Click to open

     
     # For MTK DRM integration:
     service teei_daemon /vendor/bin/teei_daemon \
         -r 020b0000000000000000000000000000 \
         -r 020f0000000000000000000000000000 \
         -r 06090000000000000000000000000000 \
         -r 05120000000000000000000000000000 \
         -r 40188311faf343488db888ad39496f9a \
         -r 07060000000000000000000000007169 \
         -r 4be4f7dc1f2c11e5b5f7727283247c7f \
         -r 9073f03a9618383bb1856eb3f990babd \
         -r 08050000000000000000000000003419 \
         -r 5020170115e016302017012521300000 \
         -r 0f5eed3c3b5a47afacca69a84bf0efad \
         -r 07407000000000000000000000000000 \
         -r 05160000000000000000000000000000 \
         -r 91dba524a6e24909acc48abd7163121a \
         -r 08070000000000000000000000008270 \
         -r 09080000000000000000000000009381 \
         -t 08030000000000000000000000000000 \
         -t 85f630e0f0964c5fa2cc268ce04e3da3 \
         -t 98fb95bcb4bf42d26473eae48690d7ea \
         -t 7b66512021214487ba710a51d7ea78fe \
         -t 09010000000000000000000000000000
         user root
         group root
         disabled
         seclabel u:r:recovery:s0
         # oneshot
    
     on boot
         chown system system /sys/bus/platform/devices/utos/dcih_notify_test
         chown system system /sys/bus/platform/devices/utos/dcih_wait_notify_test
         chown system system /sys/bus/platform/devices/utos/load_ut_drv
         chown system system /sys/bus/platform/devices/utos/unload_ut_drv
         chown system system /sys/bus/platform/devices/utos/notify_ree_dci_handler
    
     #for All mode
     on load_persist_props_action
         write /proc/bootprof "start teei cfg (on load_persist_props_action)"
         mkdir /data/vendor/thh
    
         mkdir /data/vendor/thh/system
         mkdir /data/vendor/thh/tee_00
         mkdir /data/vendor/thh/tee_01
         mkdir /data/vendor/thh/tee_02
         mkdir /data/vendor/thh/tee_03
         mkdir /data/vendor/thh/tee_04
         mkdir /data/vendor/thh/tee_05
         mkdir /data/vendor/thh/tee_06
         mkdir /data/vendor/thh/tee_07
         mkdir /data/vendor/thh/tee
         mkdir /data/vendor/thh/tee/tas
         mkdir /data/vendor/thh/tee_08
         mkdir /data/vendor/thh/tee_09
         mkdir /data/vendor/thh/tee_0A
         mkdir /data/vendor/thh/tee_0B
         mkdir /data/vendor/thh/tee_0C
         mkdir /data/vendor/thh/tee_0D
         mkdir /data/vendor/thh/tee_0E
         mkdir /data/vendor/thh/tee_0F
         mkdir /data/vendor/thh/ta
         mkdir /data/vendor/thh/tee_log
         mkdir /data/vendor/key_provisioning
         chmod 0755 /data/vendor/thh
         chown system system /data/vendor/thh
         chmod 0755 /data/vendor/thh/tee_00
         chown system system /data/vendor/thh/tee_00
         chmod 0755 /data/vendor/thh/tee_01
         chown system system /data/vendor/thh/tee_01
         chmod 0755 /data/vendor/thh/tee_02
         chown system system /data/vendor/thh/tee_02
         chmod 0755 /data/vendor/thh/tee_03
         chown system system /data/vendor/thh/tee_03
         chmod 0755 /data/vendor/thh/tee_04
         chown system system /data/vendor/thh/tee_04
         chmod 0755 /data/vendor/thh/tee_05
         chown system system /data/vendor/thh/tee_05
    
         chmod 0755 /data/vendor/thh/tee_06
         chown system system /data/vendor/thh/tee_06
         chmod 0755 /data/vendor/thh/tee_07
         chown system system /data/vendor/thh/tee_07
         chmod 0755 /data/vendor/thh/tee
         chown system system /data/vendor/thh/tee
         chmod 0755 /data/vendor/thh/tee/tas
         chown system system /data/vendor/thh/tee/tas
         chmod 0755 /data/vendor/thh/tee_08
         chown system system /data/vendor/thh/tee_08
         chmod 0755 /data/vendor/thh/tee_09
         chown system system /data/vendor/thh/tee_09
         chmod 0755 /data/vendor/thh/tee_0A
         chown system system /data/vendor/thh/tee_0A
         chmod 0755 /data/vendor/thh/tee_0B
         chown system system /data/vendor/thh/tee_0B
         chmod 0755 /data/vendor/thh/tee_0C
         chown system system /data/vendor/thh/tee_0C
         chmod 0755 /data/vendor/thh/tee_0D
         chown system system /data/vendor/thh/tee_0D
         chmod 0755 /data/vendor/thh/tee_0E
         chown system system /data/vendor/thh/tee_0E
         chmod 0755 /data/vendor/thh/tee_0F
         chown system system /data/vendor/thh/tee_0F
         chmod 0755 /data/vendor/thh/tee_log
         chown system system /data/vendor/thh/tee_log
         chmod 0755 /data/vendor/thh/ta
         chown system system /data/vendor/thh/ta
         chmod 0755 /data/vendor/thh/system
         chown system system /data/vendor/thh/system
         restorecon_recursive /data/vendor/thh
         chmod 0771 /data/vendor/key_provisioning
         chown system system /data/vendor/key_provisioning
         write /proc/bootprof "start teei cfg end (on load_persist_props_action)"
    
     on property:vold.decrypt=trigger_restart_framework
         write /proc/bootprof "start teei cfg (on trigger_restart_framework)"
         mkdir /data/vendor/thh
         mkdir /data/vendor/thh/system
         mkdir /data/vendor/thh/tee_00
         mkdir /data/vendor/thh/tee_01
         mkdir /data/vendor/thh/tee_02
         mkdir /data/vendor/thh/tee_03
         mkdir /data/vendor/thh/tee_04
         mkdir /data/vendor/thh/tee_05
         mkdir /data/vendor/thh/tee_06
         mkdir /data/vendor/thh/tee_07
         mkdir /data/vendor/thh/tee
         mkdir /data/vendor/thh/tee/tas
         mkdir /data/vendor/thh/tee_08
         mkdir /data/vendor/thh/tee_09
         mkdir /data/vendor/thh/tee_0A
         mkdir /data/vendor/thh/tee_0B
         mkdir /data/vendor/thh/tee_0C
         mkdir /data/vendor/thh/tee_0D
         mkdir /data/vendor/thh/tee_0E
         mkdir /data/vendor/thh/tee_0F
         mkdir /data/vendor/thh/ta
         mkdir /data/vendor/key_provisioning
         mkdir /data/vendor/thh/tee_log
         chmod 0755 /data/vendor/thh
         chown system system /data/vendor/thh
         chmod 0755 /data/vendor/thh/tee_00
         chown system system /data/vendor/thh/tee_00
         chmod 0755 /data/vendor/thh/tee_01
         chown system system /data/vendor/thh/tee_01
         chmod 0755 /data/vendor/thh/tee_02
         chown system system /data/vendor/thh/tee_02
         chmod 0755 /data/vendor/thh/tee_03
         chown system system /data/vendor/thh/tee_03
         chmod 0755 /data/vendor/thh/tee_04
         chown system system /data/vendor/thh/tee_04
         chmod 0755 /data/vendor/thh/tee_05
         chown system system /data/vendor/thh/tee_05
    
         chmod 0755 /data/vendor/thh/tee_06
         chown system system /data/vendor/thh/tee_06
         chmod 0755 /data/vendor/thh/tee_07
         chown system system /data/vendor/thh/tee_07
         chmod 0755 /data/vendor/thh/tee
         chown system system /data/vendor/thh/tee
         chmod 0755 /data/vendor/thh/tee/tas
         chown system system /data/vendor/thh/tee/tas
         chmod 0755 /data/vendor/thh/tee_08
         chown system system /data/vendor/thh/tee_08
         chmod 0755 /data/vendor/thh/tee_09
         chown system system /data/vendor/thh/tee_09
         chmod 0755 /data/vendor/thh/tee_0A
         chown system system /data/vendor/thh/tee_0A
         chmod 0755 /data/vendor/thh/tee_0B
         chown system system /data/vendor/thh/tee_0B
         chmod 0755 /data/vendor/thh/tee_0C
         chown system system /data/vendor/thh/tee_0C
         chmod 0755 /data/vendor/thh/tee_0D
         chown system system /data/vendor/thh/tee_0D
         chmod 0755 /data/vendor/thh/tee_0E
         chown system system /data/vendor/thh/tee_0E
         chmod 0755 /data/vendor/thh/tee_0F
         chown system system /data/vendor/thh/tee_0F
         chmod 0755 /data/vendor/thh/tee_log
         chown system system /data/vendor/thh/tee_log
         chmod 0755 /data/vendor/thh/ta
         chown system system /data/vendor/thh/ta
         chmod 0755 /data/vendor/thh/system
         chown system system /data/vendor/thh/system
         chmod 0771 /data/vendor/key_provisioning
         chown system system /data/vendor/key_provisioning
         restorecon_recursive /data/vendor/thh
         write /proc/bootprof "start teei cfg end (on trigger_restart_framework)"
    
     on post-fs
         # Set /mnt/vendor/persist/rpmb
         chown system system /mnt/vendor/persist
         chmod 0771 /mnt/vendor/persist
         restorecon_recursive /mnt/vendor/persist
    
         mkdir /mnt/vendor/persist/rpmb
         chown system system /mnt/vendor/persist/rpmb
         chmod 0771 /mnt/vendor/persist/rpmb
         restorecon_recursive /mnt/vendor/persist/rpmb
    
         # Set other rpmb
         mkdir /persist/rpmb
         mkdir /vendor/persist/rpmb
         chmod 0771 /persist/rpmb
         chmod 0771 /vendor/persist/rpmb
         chown system system /persist/rpmb
         chown system system /vendor/persist/rpmb
         restorecon_recursive /persist
         restorecon_recursive /vendor/persist
    
     on fs
         chmod 0660 /dev/teei_client
         chown system system /dev/teei_client
         chmod 0660 /dev/teei_config
         chown system system /dev/teei_config
         # 666 for SVP
         chmod 0666 /dev/isee_tee0
         chown system drmrpc /dev/isee_tee0
         chmod 0660 /dev/tz_vfs
         chown system system /dev/tz_vfs
         chmod 0660 /dev/teei_fp
         chown system /dev/teei_fp
         chown system drmrpc /dev/ut_keymaster
         chmod 0660 /dev/ut_keymaster
         # rpmb device
         chmod 0660 /dev/rpmb0
         chown system system /dev/rpmb0
         chmod 0660 /dev/mmcblk0rpmb
         chown root system /dev/mmcblk0rpmb
         # legacy rpmb device for cross-platform compatibility
         chmod 0660 /dev/emmcrpmb0
         chown system system /dev/emmcrpmb0
         chown system system /dev/utr_tui
         chmod 0660 /dev/utr_tui
         write /proc/bootprof "start teei_daemon (on fs)"
         start teei_daemon
         write /proc/bootprof "start teei_daemon end (on fs)"
    
     on property:vendor.crypto.fake_encrypt=1 && property:vold.post_fs_data_done=1
         setprop vendor.soter.teei.crypto.state unencrypted

Files come from the stock system.img file and must be located in:

  • \system\etc\vintf
    • manifest.xml

Copy all folders and all files within \vendor to the device tree under android\brand\devicename\recovery\root\vendor\ and all files within \system to the device tree under android\brand\devicename\recovery\root\system\. Remember that the files init.recovery.mtNNNN.rc and init.recovery.microtrust.rc must be in android\brand\devicename\recovery\root.

To better understand the organization of the structure with encryption/decryption files, an example below for an MT6877 device:

Click to open

ksnip_20240207-181841_resized

From my experience, there are devices shipped with Android 11 with kernel 4.19, devices shipped with Android 12 with kernel 4.14 and with kernel 5.1.xxx that have beanpod with fully functional decryption.

3.4 Trustonic

This type of encryption is one of the most used in devices from the Infinix, Tecno, Realme and some Xiaomi-Poco brands. It has been used since before Android 9 and for the most part it has always worked well. So for Android 11+ versions, it all depends on the Custom Recovery source code.

Click to open

Understanding this, you should find some files related to trustonic. These files come from the stock vendor.img file and must be located in:

  • \vendor\app\mcRegistry
    • Get the entire \app folder and all the files.
  • \vendor\bin
    • mcDriverDaemon
  • \vendor\bin\hw
    • android.hardware.gatekeeper@1.0-service
    • android.hardware.keymaster@4.0-service.trustonic
    • vendor.trustonic.tee@1.1-service
  • \vendor\etc\vintf
    • manifest.xml
  • \vendor\lib64
    • libkmsetkey.so
    • libladder.so
    • libMcClient.so
    • libTEECommon.so
    • vendor.trustonic.tee.tui@1.0.so
    • vendor.trustonic.tee@1.0.so
    • vendor.trustonic.tee@1.1.so
  • \vendor\lib64\hw
    • android.hardware.gatekeeper@1.0-impl.so
    • gatekeeper.default.so
    • gatekeeper.trustonic.so
    • kmsetkey.default.so
    • kmsetkey.trustonic.so
    • libMcGatekeeper.so
    • libSoftGatekeeper.so

Depending on the Android and kernel version, your device has a few more dependent binary files. You can check the \vendor\ stock folders for the files in the:

  • bin\
    • paytrigger_test
  • bin\hw\
    • vendor.mediatek.hardware.paytrigger@1.0-service
  • lib64\
    • libmtk_bsg.so
    • liburee_meta_drmkeyinstall.so
    • vendor.mediatek.hardware.paytrigger@1.0.so
  • lib\hw\
    • paytrigger.trustonic.so

Pay attention to file updates! Example: The above android.hardware.keymaster@4.0-service.trustonic file can change to android.hardware.keymaster@4.1-service.trustonic or android.hardware.security.keymint-service.trustonic.rc. So you must modify every part of files where this *-service.trustonic file is being referenced.

  • android\brand\devicename\recovery\root
    There may be differences between devices, so open the stock ramdisk\init.recovery.{hardware}.rc file and note the line on post-fs through on post-fs in the init.recovery.mtNNNN.rc file below.
    • init.recovery.mtNNNN.rc

      Click to open

         import /trustonic.rc
         import /init.tee.rc
         
         on init
             symlink /dev/block/platform/bootdevice /dev/block/bootdevice
             export LD_LIBRARY_PATH /system/lib:/vendor/lib:/vendor/lib/hw:/system/lib/hw
      
         on fs
             mkdir /mnt/vendor 0700 root root
             mkdir /mnt/vendor/persist 0700 root root
             mount ext4 /dev/block/by-name/persist /mnt/vendor/persist
       
         on post-fs
                 # **COPY YOUR STOCK ramdisk\init.recovery.{hardware}.rc `on post-fs` FILE HERE!!**
      
      
             start mtk.plpath.utils.link
      
         on fs
             install_keyring
      
         service mtk.plpath.utils.link /system/bin/mtk_plpath_utils
             class main
             user root
             group root system
             disabled
             oneshot
             seclabel u:r:recovery:s0
      
         service keystore_auth /system/bin/keystore_auth
             oneshot
             user system
             group root
             disabled
             seclabel u:r:recovery:s0
      
         service keystore /system/bin/keystore /tmp/misc/keystore
             user root
             group root drmrpc readproc log
             disabled
             seclabel u:r:recovery:s0
      
         service gatekeeper-1-0 /system/bin/android.hardware.gatekeeper@1.0-service
             user root
             group root
             disabled
             seclabel u:r:recovery:s0
      
         service keymaster-4-0 /system/bin/android.hardware.keymaster@4.0-service.trustonic
             user root
             group root drmrpc
             disabled
             oneshot
             seclabel u:r:recovery:s0
      
         service tee-1-1 /system/bin/vendor.trustonic.tee@1.1-service
             user root
             group root
             disabled
             seclabel u:r:recovery:s0
      
         on property:vendor.sys.listener.registered=true
             start mobicore
             start gatekeeper-1-0
             start keymaster-4-0
             start tee-1-1
      
         on property:hwservicemanager.ready=true
             write /proc/bootprof "MOBICORE: create /data/vendor/mcRegistry ++ (FBE encrypted)"
             start mobicore
             write /proc/bootprof "MOBICORE: create /data/vendor/mcRegistry -- (FBE encrypted)"
             start gatekeeper-1-0
             start keymaster-4-0
             start tee-1-1
      
         on property:ro.crypto.state=unsupported
             stop mobicore
             stop gatekeeper-1-0
             stop keymaster-4-0
             stop tee-1-1
      
         on property:ro.crypto.state=unencrypted
             stop mobicore
             stop gatekeeper-1-0
             stop keymaster-4-0
             stop tee-1-1
      
         on property:twrp.decrypt.done=true
             stop mobicore
             stop gatekeeper-1-0
             stop keymaster-4-0
             stop tee-1-1
      
         on boot
             start boot-hal-1-2
             start health-hal-2-1

Some text files are important to know how they are written and place them inside the init.recovery.mtNNNN.rc file, such as android.hardware.gatekeeper@1.0-service.rc and android.hardware.keymaster@4.0-service.trustonic.rc. You can choose to remove these files from the folder and place them inside the init.recovery.mtNNNN.rc file. This is optional and please note this is what I did. Also note that there is no inclusion (import) line of the same file in init.recovery.mtNNNN.rc related to the files mentioned in the stock folder \vendor\etc\init.

The files below are script files that perform decryption and are referenced in the (import) lines in the init.recovery.mtNNNN.rc file. Note that there are processes and phases of file targeting so that decryption can be done. It is necessary to compare the stock files vendor\etc\init\tee.rc; vendor\etc\init\trustonic.rc and vendor\etc\init\vendor.trustonic.tee@1.1-service.rc with the file below. If there are any modifications to be made, do so according to the stock file.

  • tee.rc

    Click to open

     
     on init
        #create mountpoint for /mnt/vendor/persist partition
        mkdir /mnt/vendor/persist 0771 system system
    
        on post-fs
            chown system system /mnt/vendor/persist
            chmod 0771 /mnt/vendor/persist
    
        # We restorecon /mnt/vendor/persist to set SEPolicy label.
        restorecon /mnt/vendor/persist
    
        # Create mcRegistry to store failure record
        mkdir /mnt/vendor/persist/mcRegistry 0771 system system
        mkdir /mnt/vendor/persist/paytrigger
        chown system system /mnt/vendor/persist/paytrigger
        chmod 0777 /mnt/vendor/persist/paytrigger
    
        on post-fs-data
            # Create /data/vendor/key_provisioning dir and get proper encryption policy installed
            # Key Installation
            mkdir /data/vendor/key_provisioning 0771 system system
    
        # For META/FACTORY mode
        on property:ro.crypto.state=unencrypted
            write /proc/bootprof "MOBICORE: create /data/vendor/mcRegistry ++ (unencrypted)"
            mkdir /data/vendor/mcRegistry 0775 system system
            write /proc/bootprof "MOBICORE: create /data/vendor/mcRegistry -- (unencrypted)"
    
        # Normal mode, FBE
        on property:ro.crypto.type=file && property:ro.crypto.state=encrypted
            write /proc/bootprof "MOBICORE: create /data/vendor/mcRegistry ++ (FBE encrypted)"
            mkdir /data/vendor/mcRegistry 0775 system system
            write /proc/bootprof "MOBICORE: create /data/vendor/mcRegistry -- (FBE encrypted)"
    
        # Normal mode, FDE
        on property:vold.decrypt=trigger_restart_framework
            write /proc/bootprof "MOBICORE: create /data/vendor/mcRegistry ++ (FDE encrypted)"
            mkdir /data/vendor/mcRegistry 0775 system system
            write /proc/bootprof "MOBICORE: create /data/vendor/mcRegistry -- (FDE encrypted)"

Depending on the Android and kernel version, your device has a few more dependent binary files and need more services files. You can check the vendor\etc\init\vendor.mediatek.hardware.paytrigger@1.0-service.rc. Add the line below so that Custom Recovery has permission over the process. This should happen for all *-service files.

     seclabel u:r:recovery:s0
  • trustonic.rc

    Click to open

     
     # Start Daemon (Registry directories should already be present)
     service mobicore /vendor/bin/mcDriverDaemon --sfs-reformat --P1 /mnt/vendor/persist/mcRegistry \
             -r /vendor/app/mcRegistry/06090000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/020f0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/05120000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/05120000000000000000000000000001.drbin \
             -r /vendor/app/mcRegistry/05160000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/020b0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/05070000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/030b0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/03100000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/030c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/031c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/032c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/033c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/034c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/035c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/036c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/037c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/40188311faf343488db888ad39496f9a.drbin \
             -r /vendor/app/mcRegistry/070c0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/090b0000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/0f5eed3c3b5a47afacca69a84bf0efad.drbin \
             -r /vendor/app/mcRegistry/07060000000000000000000000007169.drbin \
             -r /vendor/app/mcRegistry/4be4f7dc1f2c11e5b5f7727283247c7f.drbin \
             -r /vendor/app/mcRegistry/08070000000000000000000000008270.drbin \
             -r /vendor/app/mcRegistry/07070000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/07407000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/9073f03a9618383bb1856eb3f990babd.drbin \
             -r /vendor/app/mcRegistry/07090000000000000000000000000000.drbin \
             -r /vendor/app/mcRegistry/6b3f5fa0f8cf55a7be2582587d62d63a.drbin \
             -r /vendor/app/mcRegistry/5020170115e016302017012521300000.drbin
         user root
         group root
         disabled
         seclabel u:r:recovery:s0
    
     # t-Drv naming
     # 020f0000000000000000000000000000.drbin : utils
     # 05120000000000000000000000000000.drbin : sec
     # 070b0000000000000000000000000000.drbin : tplay
     # 020b0000000000000000000000000000.drbin : cmdq
     # 05070000000000000000000000000000.drbin : goodix_fp
     # 030b0000000000000000000000000000.drbin : spi
     # 030c0000000000000000000000000000.drbin : spi5
     # 07070000000000000000000000000000.drbin : MtkH264Venc
     # 07060000000000000000000000007169.drbin : MtkH264Vdec
     # 4be4f7dc1f2c11e5b5f7727283247c7f.drbin : MtkH265Vdec
     # 08070000000000000000000000008270.drbin : MtkVP9Vdec
     # 5020170115e016302017012521300000.drbin : drm_hdcp_common
     # 40188311faf343488db888ad39496f9a.drbin : widevine
     # 070c0000000000000000000000000000.drbin : IRIS_GPIO
     # 070c0000000000000000000000000000.drbin : DrTui
     # 090b0000000000000000000000000000.drbin : IRIS_I2C
     # 0f5eed3c3b5a47afacca69a84bf0efad.drbin : isp
     # 07407000000000000000000000000000.drbin : sensor
     # 06090000000000000000000000000000.drbin : drm keyinstall
     # 9073f03a9618383bb1856eb3f990babd.drbin : m4u
     # 6b3f5fa0f8cf55a7be2582587d62d63a.drbin : hdcp

Files come from the stock system.img file and must be located in:

  • \system\etc\vintf
    • manifest.xml
  • \system\lib64
    • libTeeClient.so
    • vendor.trustonic.tee@1.0.so
    • vendor.trustonic.tee@1.1.so

Copy all folders and all files within \vendor to the device tree under android\brand\devicename\recovery\root\vendor\ and all files within \system to the device tree under android\brand\devicename\recovery\root\system\. Remember that the files init.recovery.mtNNNN.rc and init.recovery.trustonic.rc must be in android\brand\devicename\recovery\root.

To better understand the organization of the structure with encryption/decryption files, an example below for an MT6877 device:

Click to open

ksnip_20240208-191107

From my experience, there are devices shipped with Android 11 with kernel 4.19, devices shipped with Android 12-13 with kernel 4.14 and with kernel 5.1.xxx that have beanpod with fully functional decryption.

The final directory structure of device tree with recovery_CustomRecovery.img looks like below:

Click to open

android_device_brand_devicename

├── prebuilt
|   ├── Image.gz
│   ├── dtb.img
│   └── dtbo.img
├── recovery
|   └── root
|       ├── system
|       |   ├── bin
|       |   |   └── *.so or *.service
|       |   ├── etc
|       |   |   ├── vintf
|       |   |   |   └── manifest.xml
|       |   |   ├── recovery.fstab
|       |   |   ├── task_profile.json
|       |   |   └── twrp.fstab
|       |   └── lib64
|       |        └── hw
|       |            └── *.so
|       ├── vendor
|       |   ├── bin
|       |   |   ├── hw
|       |   |   |   └── *.service
|       |   |   └── *.so
|       |   ├── etc
|       |   |   └── vintf
|       |   |       ├── compatibility_matrix.xml
|       |   |       └── manifest.xml
|       |   ├── firmware
|       |   |   └── *.bin
|       |   ├── lib64
|       |   |   ├── hw
|       |   |   |   └── *.so
|       |   |   └── *.so
|       ├── init.recovery.mtNNNN.rc
|       ├── init.recovery.usb.rc
|       └── ueventd.mt6xxx.rc
├── Android.mk
├── AndroidProducts.mk
├── BoardConfig.mk
├── README.md
├── device.mk
├── [system or and vendor].prop
└── twrp_devicename.mk


The final directory structure of device tree boot_CustomRecovery.img looks like below:

Click to open

android_device_brand_devicename

├── prebuilt
│   ├── Image.gz
│   └── dtb.img
├── recovery
|   └── root
|       ├── first_stage_ramdisk
|       |   └── fstab.*
|       ├── system
|       |   ├── bin
|       |   |   └── *.so or *.service
|       |   ├── etc
|       |   |   ├── vintf
|       |   |   |   └── manifest.xml
|       |   |   ├── fstab.postinstall
|       |   |   ├── recovery.fstab
|       |   |   ├── task_profile.json
|       |   |   └── twrp.fstab
|       |   └── lib64
|       |        └── hw
|       |            └── *.so
|       ├── vendor
|       |   ├── bin
|       |   |   ├── hw
|       |   |   |   └── *.service
|       |   |   └── *.so
|       |   ├── etc
|       |   |   └── vintf
|       |   |       ├── compatibility_matrix.xml
|       |   |       └── manifest.xml
|       |   ├── firmware
|       |   |   └── *.bin
|       |   ├── lib
|       |   |   └── modules
|       |   |       └── *.ko
|       |   ├── lib64
|       |   |   ├── hw
|       |   |   |   └── *.so
|       |   |   └── *.so
|       |   └── ueventd.rc
|       ├── init.recovery.mtNNNN.rc
|       └── init.recovery.usb.rc
├── Android.mk
├── AndroidProducts.mk
├── BoardConfig.mk
├── README.md
├── device.mk
├── [system or and vendor].prop
└── twrp_devicename.mk


The final directory structure of device tree vendorboot_CustomRecovery.img looks like below:

Click to open

android_device_brand_devicename

├── prebuilt
│   └── dt
├── recovery
|   └── root
|       ├── first_stage_ramdisk
|       |   └── fstab.*
|       ├── lib
|       |   └── modules
|       |       └── *.ko
|       ├── system
|       |   ├── bin
|       |   |   └── *.so or *.service
|       |   ├── etc
|       |   |   ├── vintf
|       |   |   |   └── manifest.xml
|       |   |   ├── recovery.fstab
|       |   |   ├── task_profile.json
|       |   |   └── twrp.fstab
|       |   └── lib64
|       |        └── hw
|       |            └── *.so
|       ├── vendor
|       |   ├── bin
|       |   |   ├── hw
|       |   |   |   └── *.service
|       |   |   └── *.so
|       |   ├── etc
|       |   |   ├── vintf
|       |   |   |   ├── compatibility_matrix.xml
|       |   |   |   └── manifest.xml
|       |   |   └── ueventd.rc
|       |   ├── firmware
|       |   |   └── *.bin
|       |   ├── lib
|       |   |   └── modules
|       |   |       └── *.ko
|       |   └── lib64
|       |       ├── hw
|       |       |   └── *.so
|       |       └── *.so
|       |
|       ├── init.recovery.mtNNNN.rc
|       └── init.recovery.usb.rc
├── Android.mk
├── AndroidProducts.mk
├── BoardConfig.mk
├── README.md
├── device.mk
├── [system or and vendor].prop
└── twrp_devicename.mk


As you can see, all of this was not easy or quick to write.
So if you've read everything up to this point, congratulations! Go ahead and enjoy.

lopestorm_gist


Thanks and Notes

If you have time, so read more with the book Android System Programming - Porting, customizing, and debugging Android HAL by Roger Ye ---- First published: May 2017 - 464 pages

Thanks of the Android Source Code AOSP and to all developers ope source who help and update that.

Thanks to the 4pda forum and everyone on this forum who contribute to the development in general for Custom Recovery, Custom ROMs/GSI and tools to use with device development.

Thank you very much to yuweng because this guy is not only humble and generous, he was a forerunner for Mediatek devices to actually have Custom Recovery. I had the opportunity to communicate with him and it was great! This guy created tools and tutorials to make everything easier for newbies. Well, I didn't use it much because I prefer to do the Portability process manually. Among the tools, [PORT] [TOOL] Carliv Touch Recovery for MediaTek, Easy Magic PhilZ Touch Installer for MediaTek and Easy Magic TWRP Installer for all MediaTek stand out. Also, he wrote a great tutorial on how to compile PhilZ Touch 6 Custom Recovery. I also highlight his ability to help other users with the tutorial [GUIDE] How to 'unbrick' your Mediatek MT65xx and [TUT] [TOOL] MT65xx ROM Porting, to add knowledge and develop in relation to the Android. I could still write many other things about him made, but it would go far beyond the subject.

Thanks to Phil3759 because he did a CWM/PhilZ Touch Custom Recovery - very interesting and still needed today. I learned how to improve the PORT Custom Recovery process with this Custom Recovery.

Thanks to Carliv aka bluefirebird because I learned more from him about compiling CTR.img is better than exchanging files with PORT Custom Recovery process. Furthermore, this guy also developed CTR for Mediatek devices. Well, you might know him more because of CarlivImageKitchen that he developed.

Thanks of the Source Code Custom Recovery to @TeamWin and to all the people who help update that, as well as the people who help Mediatek devices to have a more functional Custom Recovery.

Thanks of the Source Code Custom Recovery to @OrangeFox and to all the people who help update that, as well as the people who help Mediatek devices to have a more functional Custom Recovery.

Thanks of the Source Code Custom Recovery to @PitchBlack and to all the people who help update that, as well as the people who help Mediatek devices to have a more functional Custom Recovery.

Thanks to @osm0sis for keeping AIK always up to date for use.

Thanks to @SebaUbuntu for twrpdtgen.

Thanks to all the people who left some Mediatek device tree repository available so that other users can fork and not waste too much time creating a device tree from nothing.

How I write in gist: Writing on github

How I compile img file with Action in github: Using online resource to build custom recovery - TeamWin - Fox - SHRP - PBRP

What Is a Custom Android Recovery?

Team Win Recovery Project 2.0 goes gold

What Is TWRP Recovery & How To Install & Use It On Android Devices [Guide]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment