├── tools ├── unpack_bin_super.sh ├── unpack_gsi_super.sh ├── unpack_img_super.sh ├── repack_gsi_super.sh ├── repack_super_from_bin.sh └── repack_super_from_img.sh ├── README.md └── howtos ├── FlashCustomImages.md ├── UnpackRepackSuper.md ├── BackupFlash.md └── WorkingWithGSI.md /tools/unpack_bin_super.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | lpunpack super.bin 4 | fallocate -l 1G system.img 5 | resize2fs system.img 1G 6 | mkdir -p mnt/system 7 | sudo mount -t ext4 -o loop system.img mnt/system 8 | fallocate -l 512M product.img 9 | resize2fs product.img 512M 10 | mkdir -p mnt/product 11 | sudo mount -t ext4 -o loop product.img mnt/product 12 | fallocate -l 512M vendor.img 13 | resize2fs vendor.img 512M 14 | mkdir -p mnt/vendor 15 | sudo mount -t ext4 -o loop vendor.img mnt/vendor 16 | -------------------------------------------------------------------------------- /tools/unpack_gsi_super.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -z "$1" ] 4 | then 5 | echo "No argument supplied, usage: ./unpack_img_super.sh superimagefile.img" 6 | exit 7 | fi 8 | simg2img $1 temp-super-temp.img 9 | lpunpack temp-super-temp.img 10 | if [[ -f "product.img" ]]; then 11 | rm -f product.img 12 | rm -f system.img 13 | else 14 | fallocate -l 2G system.img 15 | resize2fs system.img 2G 16 | mkdir -p mnt/system 17 | sudo mount -t ext4 -o loop system.img mnt/system 18 | fi 19 | fallocate -l 512M vendor.img 20 | resize2fs vendor.img 512M 21 | mkdir -p mnt/vendor 22 | sudo mount -t ext4 -o loop vendor.img mnt/vendor 23 | -------------------------------------------------------------------------------- /tools/unpack_img_super.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -z "$1" ] 4 | then 5 | echo "No argument supplied, usage: ./unpack_img_super.sh superimagefile.img" 6 | exit 7 | fi 8 | simg2img $1 temp-super-temp.img 9 | lpunpack temp-super-temp.img 10 | fallocate -l 1G system.img 11 | resize2fs system.img 1G 12 | mkdir -p mnt/system 13 | sudo mount -t ext4 -o loop system.img mnt/system 14 | fallocate -l 512M product.img 15 | resize2fs product.img 512M 16 | mkdir -p mnt/product 17 | sudo mount -t ext4 -o loop product.img mnt/product 18 | fallocate -l 512M vendor.img 19 | resize2fs vendor.img 512M 20 | mkdir -p mnt/vendor 21 | sudo mount -t ext4 -o loop vendor.img mnt/vendor 22 | -------------------------------------------------------------------------------- /tools/repack_gsi_super.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -d "./mnt/system" ]; then 4 | sudo umount mnt/system 5 | fi 6 | e2fsck -yf system.img 7 | resize2fs -M system.img 8 | e2fsck -yf system.img 9 | sudo umount mnt/vendor 10 | e2fsck -yf vendor.img 11 | resize2fs -M vendor.img 12 | e2fsck -yf vendor.img 13 | system=`stat -c '%n %s' system.img` 14 | system=${system#* } 15 | vendor=`stat -c '%n %s' vendor.img` 16 | vendor=${vendor#* } 17 | suma=$((system + vendor)) 18 | ext4=`stat -c '%n %s' temp-super-temp.img` 19 | ext4=${ext4#* } 20 | lpmake --metadata-size 65536 --super-name super --metadata-slots 1 --device super:$ext4 --group main:$suma --partition system:readonly:$system:main --image system=./system.img --partition vendor:readonly:$vendor:main --image vendor=./vendor.img --sparse --output ./super.new.img 21 | rm -rf mnt 22 | rm -f system.img vendor.img temp-super-temp.img 23 | -------------------------------------------------------------------------------- /tools/repack_super_from_bin.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | sudo umount mnt/system 4 | e2fsck -yf system.img 5 | resize2fs -M system.img 6 | e2fsck -yf system.img 7 | sudo umount mnt/product 8 | e2fsck -yf product.img 9 | resize2fs -M product.img 10 | e2fsck -yf product.img 11 | sudo umount mnt/vendor 12 | e2fsck -yf vendor.img 13 | resize2fs -M vendor.img 14 | e2fsck -yf vendor.img 15 | system=`stat -c '%n %s' system.img` 16 | system=${system#* } 17 | product=`stat -c '%n %s' product.img` 18 | product=${product#* } 19 | vendor=`stat -c '%n %s' vendor.img` 20 | vendor=${vendor#* } 21 | total=$((system + product + vendor)) 22 | old=`stat -c '%n %s' super.bin` 23 | old=${old#* } 24 | lpmake --metadata-size 65536 --super-name super --metadata-slots 1 --device super:$old --group main:$total --partition system:readonly:$system:main --image system=./system.img --partition vendor:readonly:$vendor:main --image vendor=./vendor.img --partition product:readonly:$product:main --image product=./product.img --sparse --output ./NEW_super.img 25 | rm -rf mnt 26 | rm -f product.img system.img vendor.img 27 | -------------------------------------------------------------------------------- /tools/repack_super_from_img.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | sudo umount mnt/system 4 | e2fsck -yf system.img 5 | resize2fs -M system.img 6 | e2fsck -yf system.img 7 | sudo umount mnt/product 8 | e2fsck -yf product.img 9 | resize2fs -M product.img 10 | e2fsck -yf product.img 11 | sudo umount mnt/vendor 12 | e2fsck -yf vendor.img 13 | resize2fs -M vendor.img 14 | e2fsck -yf vendor.img 15 | system=`stat -c '%n %s' system.img` 16 | system=${system#* } 17 | product=`stat -c '%n %s' product.img` 18 | product=${product#* } 19 | vendor=`stat -c '%n %s' vendor.img` 20 | vendor=${vendor#* } 21 | total=$((system + product + vendor)) 22 | old=`stat -c '%n %s' temp-super-temp.img` 23 | old=${old#* } 24 | lpmake --metadata-size 65536 --super-name super --metadata-slots 1 --device super:$old --group main:$total --partition system:readonly:$system:main --image system=./system.img --partition vendor:readonly:$vendor:main --image vendor=./vendor.img --partition product:readonly:$product:main --image product=./product.img --sparse --output ./NEW_super.img 25 | rm -rf mnt 26 | rm -f product.img system.img vendor.img temp-super-temp.img 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # x04g_tools 2 | Xiaomi Smart Clock - Global variant (X04G) development tools 3 | 4 | [More on this XDA thread](https://forum.xda-developers.com/t/xiaomi-mi-smart-clock-development-guide-gsi.4629771/) 5 | 6 | ## -------- English -------- 7 | 8 | This repo contains several useful tools for (Xiaomi) Mi Smart Clock development, mainly for X04G global version, but also working with chinese LX04 version. 9 | 10 | Main difference between variants is their software: 11 | 12 | - LX04 variant is a Xiao AI voice assistant, for chinese market, based on Android 8.1. 13 | - X04G variant is a Google Assistant device, based on Android Go 10. 14 | 15 | Both variants share the same hardware, so you can install both software versions on them. 16 | 17 | ### Technical specs 18 | 19 | - **CPU**: MTK 8167 (MT8167), 4 Cortex-A35 cores @ 1.5GHz 20 | - **RAM**: 1GB DDR3 21 | - **Screen**: 4 inches 800x480 22 | - **WiFi/BT**: WiFi 2.4GHz, BT5.0 23 | - **Ports**: microUSB power/data 24 | - **Buttons**: volume +/-, mute 25 | - **Mic**: 2 mics array 26 | - **Speaker**: 1 x 1.5 inches 27 | - **Sensors**: light/proximity 28 | 29 | ### HOWTOs 30 | 31 | [Backup whole flash](howtos/BackupFlash.md) 32 | 33 | [Working with super image](howtos/UnpackRepackSuper.md) 34 | 35 | [GSI compatibility](howtos/WorkingWithGSI.md) 36 | 37 | ### Included tools 38 | 39 | Linux only, requires lpunpack/lpmake and simg2img 40 | 41 | [Tools folder](tools) 42 | 43 | ### External tools 44 | 45 | - **MTKClient**: https://github.com/bkerler/mtkclient 46 | 47 | - **Android Image Kitchen**: https://forum.xda-developers.com/t/tool-android-image-kitchen-unpack-repack-kernel-ramdisk-win-android-linux-mac.2073775/ 48 | 49 | - **Magisk**: https://github.com/topjohnwu/Magisk 50 | 51 | - **GSI images**: https://github.com/phhusson/treble_experimentations/wiki/Generic-System-Image-%28GSI%29-list 52 | 53 |
54 | 55 | ## -------- Spanish -------- 56 | 57 | Este repositorio contiene una lista de herramientas útiles para el (Xiaomi) Mi Smart Clock, versión global X04G, aunque también sirven para la versión china LX04. 58 | 59 | La principal diferencia entre ambas variantes está en su software; 60 | - la variante LX04 funciona como asistente de Xiao AI, dirigida al mercado chino, y con la ROM basada en Android 8.1. 61 | - la variante global X04G es un dispositivo asistente de Google, con una ROM basada en Android Go 10. 62 | 63 | Ambas variantes cuentan con el mismo hardware y puede saltarse de una a otra versión simplemente cambiando su ROM. 64 | 65 | ### Especificaciones 66 | 67 | - **CPU**: MTK 8167 (MT8167), 4 cores Cortex-A35 a 1.5GHz 68 | - **RAM**: 1GB DDR3 69 | - **Pantalla**: 4 pulgadas 800x480 70 | - **WiFi/BT**: WiFi 2.4GHz, BT5.0 71 | - **Puertos**: microUSB alimentación/datos 72 | - **Botones**: físicos de volumen +/- y mute 73 | - **Micrófono**: 2 micrófonos en la parte superior 74 | - **Altavoz**: mono, 1.5 pulgadas 75 | - **Sensores**: luminosidad/proximidad 76 | 77 | ### Guías 78 | 79 | [Hacer copia de la flash completa](howtos/BackupFlash.md) 80 | 81 | [Trabajando con una imagen super](howtos/UnpackRepackSuper.md) 82 | 83 | [Compatibilidad de GSI](howtos/WorkingWithGSI.md) 84 | 85 | ### Herramientas incluidas 86 | 87 | [Carpeta de herramientas](tools) 88 | 89 | ### Herramientas externas 90 | 91 | - **MTKClient**: https://github.com/bkerler/mtkclient 92 | 93 | - **Android Image Kitchen**: https://forum.xda-developers.com/t/tool-android-image-kitchen-unpack-repack-kernel-ramdisk-win-android-linux-mac.2073775/ 94 | 95 | - **Magisk**: https://github.com/topjohnwu/Magisk 96 | 97 | - GSI images: https://github.com/phhusson/treble_experimentations/wiki/Generic-System-Image-%28GSI%29-list 98 | -------------------------------------------------------------------------------- /howtos/FlashCustomImages.md: -------------------------------------------------------------------------------- 1 | ## -------- English -------- 2 | 3 | It is important to make a backup before doing anything else in order to be able to restore the device if necessary. There are no recovery images for this device available online, therefore you will only be able to solve any problem derived from this procedure by restoring the backup that you should have made in the first place. 4 | 5 | [Backup whole flash](BackupFlash.md) 6 | 7 | ### Unlocking bootloader 8 | 9 | We need MTKClient (which we already have installed and running). Run this command to delete these partitions: 10 | 11 | python mtk e metadata,userdata,md_udc 12 | 13 | Connect device with volume + pressed and wait for it to finish. Once done, run this other command: 14 | 15 | python mtk da seccfg unlock 16 | 17 | Followed by: 18 | 19 | python mtk reset 20 | 21 | Disconnect the device, wait for a few seconds and reconnect it. Mi logo will show along with a text indicating that the device is in "Orange State". Bootloader is now unlocked. 22 | 23 | 24 | ### Installing system 25 | 26 | Disconnect device from PC, and press three upper buttons to reconnect it. After 5 seconds release the mute button and leave the other two buttons pressed until the text "No command" shows on the screen. 27 | Kepp mute pressed and press volume + button once to reveal the usual recovery menu. Select "Reboot to bootloader". 28 | 29 | Once in fastboot mode, execute the following commands: 30 | 31 | fastboot flash boot boot.img 32 | fastboot flash super super.img 33 | fastboot --disable-verity --disable-verification flash vbmeta vbmeta.img 34 | fastboot reboot 35 | 36 | boot.img file must be the original boot.img file modified as described at the end of the [guide for working with GSI](WorkingWithGSI.md). 37 | super.img file must be the result of our previous work. 38 | vbmeta.img file is located in the MTKClient root folder as vbmeta.img.empty. 39 | 40 | Once the reboot command has been executed, we must wait a few minutes for the system to boot. Depending on many factors it may take longer, so it is advisable to be patient. 41 | 42 | 43 | 44 | 45 | ## -------- Spanish -------- 46 | 47 | Para instalar sistemas o imágenes custom debemos seguir el siguiente proceso. Es importante realizar una copia de seguridad previamente para poder restaurar el dispositivo en caso de necesidad. No hay disponibles online imágenes de recuperación del dispositivo, por lo tanto sólo podrás resolver cualquier problema derivado de este procedimiento restaurando la copia de seguridad que debes haber realizado en primera instancia. 48 | 49 | [Hacer copia de la flash completa](BackupFlash.md) 50 | 51 | 52 | ### Desbloquear el bootloader 53 | 54 | Necesitamos MTKClient (que ya tenemos instalado y funcionando). Ejecutamos este comando para borrar estas particiones: 55 | 56 | python mtk e metadata,userdata,md_udc 57 | 58 | Conectamos el dispositivo con el volumen + presionado y esperamos a que termine. Una vez hecho, ejecutamos este otro comando: 59 | 60 | python mtk da seccfg unlock 61 | 62 | Seguido de: 63 | 64 | python mtk reset 65 | 66 | Desconectamos el dispositivo, esperamos unos segundos y volvemos a conectarlo. Aparecerá el logo de Mi junto con un texto indicando que el dispositivo está en "Orange State". Ya tenemos desbloqueado el bootloader. 67 | 68 | 69 | ### Instalar el sistema 70 | 71 | Desconectamos el dispositivo del PC, y presionando los tres botones superiores lo volvemos a conectar. Pasados 5 segundos soltamos el boton de mute y dejamos los otros dos pulsados hasta que aparezca el texto "Sin comandos" en pantalla. 72 | Mantenemos presionado mute y pulsamos volumen + una vez para que aparezca el menú habitual de recovery. Seleccionamos "Reboot to bootloader". 73 | 74 | Una vez en modo fastboot ejecutamos los siguientes comandos: 75 | 76 | fastboot flash boot boot.img 77 | fastboot flash super super.img 78 | fastboot --disable-verity --disable-verification flash vbmeta vbmeta.img 79 | fastboot reboot 80 | 81 | El archivo boot.img debe ser el boot.img original modificado tal y como se describe al final de la [guía para trabajar con GSI](WorkingWithGSI.md) 82 | El archivo super.img debe ser el resultado de nuestro trabajo previo. 83 | El archivo vbmeta.img se encuentra en la carpeta raíz de MTKClient como vbmeta.img.empty 84 | 85 | Una vez ejecutado el comando de reboot debemos esperar unos minutos a que el sistema arranque. Dependiendo de múltiples factores puede alargarse, así que conviene ser pacientes. 86 | -------------------------------------------------------------------------------- /howtos/UnpackRepackSuper.md: -------------------------------------------------------------------------------- 1 | ## -------- English -------- 2 | 3 | If we already have a device partitions backup we should have a folder containing several files with ".bin" extension. We will need "super.bin", so we copy it to a new folder. It is important to keep the original backup files as they were extracted from device and do not work directly with them. 4 | 5 | ### Unpacking super partition 6 | 7 | To unpack "super" partition we will use a script called "unpack_bin_super.sh", contained in the tools folder. We should place this file in the same folder we copied "super.bin" previously. 8 | After running it we will see how 4 new elements are created; an "mnt" folder and 3 disk image files (product.img, system.img and vendor.img). Inside the "mnt" folder there will be 3 subfolders (product, system and vendor) where the 3 disk images will be mounted. 9 | 10 | To make any change it is necessary to have root permissions, since the images are mounted as such, either from the console or the file explorer. 11 | 12 | ### Creating a new super image 13 | 14 | Once we have made the changes we wanted, it is time to re-create the super partition that we will write to the device. 15 | We must make sure that the console or file explorer is not located inside the "mnt" folder so that the unmount process does not fail. 16 | 17 | Now we will use the script "repack_super_from_bin.sh", previously placed in the same folder. If we run it, the image files and the folder created in the previous step will disappear and a new file "NEW_super.img" will be created. 18 | 19 | If we want to make any further change using this newly created file we must use another set of scripts; "unpack_img_super.sh" and "repack_super_from_img.sh". 20 | 21 | ### FYI 22 | 23 | It is important not to mix the use of the scripts; the ones we have used in the first step are only needed to unpack/repack "super.bin" file extracted directly from the device, while other two scripts are meant to be used with a "*_super.img" file created using the scripts set. 24 | 25 | The "repack" scripts will always create a file called "NEW_super.img" as output after execution, so any existing file with the same name will be overwritten. Please rename the files you don't want to lose. 26 | 27 |
28 | 29 | ## -------- Spanish -------- 30 | 31 | Si ya hemos completado la copia por particiones del dispositivo tendremos una carpeta conteniendo varios archivos con extensión ".bin". Copiaremos uno de ellos, "super.bin", a una carpeta nueva donde trabajaremos con él. Es importante guardar una copia de todos los archivos antes de trabajar con ellos, por si algo sale mal. 32 | 33 | ### Desempaquetando la partición super 34 | 35 | Para desempaquetar la partición "super" usaremos el script "unpack_bin_super.sh", contenido en la carpeta de herramientas de este repositorio. Para ello, debemos colocarlo en la misma carpeta que el archivo "super.bin" que copiamos previamente. 36 | Al ejecutarlo veremos como se crean 4 elementos nuevos; una carpeta "mnt" y 3 archivos de imagen de disco (product.img, system.img y vendor.img). Dentro de la carpeta "mnt" habrá a su vez 3 subcarpetas (product, system y vendor) donde se habrán montado las 3 imágenes de disco. 37 | 38 | Para hacer cambios es necesario tener permisos de root, puesto que las imágenes están montadas como tal, bien sea desde la consola o el explorador de archivos. 39 | 40 | ### Creando una nueva imagen de super 41 | 42 | Una vez realizados los cambios que hemos considerado oportunos, es momento de volver a crear la partición super que escribiremos en el dispositivo. 43 | Debemos asegurarnos de que la consola o el explorador de archivos no se encuentran posicionados dentro de la carpeta "mnt" para que no falle el proceso de desmontaje. 44 | 45 | En este caso usaremos el script "repack_super_from_bin.sh", colocado previamente en la misma carpeta. Al ejecutarlo desaparecerán los archivos de imagen y la carpeta creados en el punto anterior y veremos como aparece un nuevo archivo "NEW_super.img", nuestra recién creada imagen de la partición "super" lista para escribir en el dispositivo. 46 | 47 | Para trabajar usando de base ese archivo recién creado debemos usar otro conjunto de scripts; "unpack_img_super.sh" y "repack_super_from_img.sh", conveniente sobre todo para poder hacer cambios y pruebas sin tener que partir siempre desde el archivo base. 48 | 49 | ### Información relevante 50 | 51 | Es importante no mezclar el uso de los scripts; los que hemos usando en primer lugar sólo sirven para trabajar desde el archivo "super.bin" extraído directamente del dispositivo, mientras que los otros dos sirven para trabajar usando de base un archivo "*_super.img" creado con el conjunto de scripts. 52 | 53 | Los scripts "repack" siempre crearán un archivo llamado "NEW_super.img" como salida tras su ejecución, por lo que cualquier archivo existente con el mismo nombre será sobreescrito. Por favor, renombra los archivos que no quieras perder. 54 | -------------------------------------------------------------------------------- /howtos/BackupFlash.md: -------------------------------------------------------------------------------- 1 | ## -------- English -------- 2 | 3 | First step before modifying software running on device (ROM) is to make a backup of the flash contents. This will allow us to get back to factory state if we need it, as well as getting a copy of the installed software. 4 | 5 | There is no firmware download available for X04G, either officially or unofficially, so it is really important to follow this procedure to get the basis for our modifications. 6 | The author of these guides will not provide a backup of the device or the software in flashtool format, as it contains both proprietary files and unique device IDs. 7 | For the same reason, it is recommended that you do not share your own backup. 8 |
9 | 10 | ### MTKClient 11 | 12 | Thanks to **MTKClient** (https://github.com/bkerler/mtkclient) we will be able to make a complete backup of device flash. 13 | This includes both the software running (Android Go 10) with Google Assistant and other partitions, as well as user data and device IDs (serial number, WiFI/BT MAC). 14 | Since there is no package download available for SP Flash Tool containing the device software, this is a simple way to fill that gap. 15 | 16 | Once MTKClient has been installed following the steps in its repository, it will be enough to execute "mtk_gui" with python ("python mtk_gui") to display its graphical interface window. In the same way, the terminal window from which we have executed the command will indicate that the program is waiting for the device. 17 | While we hold down the volume up button we connect the USB cable between device and PC, it will be then detected and after a few seconds all of the available options will be shown. 18 | 19 | First thing to do is to backup flash memory. In the "Flash tools" tab click on the "Read flash" button, select the path where you want to save the file and wait patiently as it may take some time, depending on factors such as our USB controller, quality of connection cable or operating system version. 20 | 21 | Once this process is finished, we will do the same with "Read preloader" and "Read boot2" buttons. 22 | Then, in the "Read partition(s)" tab, check "Select all partitions" and press the "Read partition(s)" button to make a copy of the device's memory again, this time split into partitions. 23 | 24 | If everything went well the backup size should be close to 4GB (both the full backup and the sum of the files from the partitions backup), which is the same size of the device's flash memory. 25 | 26 |
27 | 28 | ## -------- Spanish -------- 29 | 30 | El primer paso antes de modificar el software del dispositivo es hacer una copia de seguridad del contenido de su memoria flash. Esto nos permitirá volver al estado inicial si lo necesitamos en algún momento, así como obtener el software que se está ejecutando en el dispositivo y sobre el que haremos las modificaciones. 31 | 32 | No hay disponible ninguna descarga del firmware para X04G, ni oficial ni extraoficialmente, por lo que es realmente importante seguir este procedimiento para conseguir la base sobre la que realizar nuestras modificaciones. 33 | El autor de estas guías no facilitará un backup del dispositivo ni el software en formato usable, ya que éste contiene tanto archivos propietarios del fabricante como identificadores únicos del dispositivo del que se obtiene. 34 | Por el mismo motivo, es recomendable que no compartas tu propio backup. 35 |
36 | 37 | ### MTKClient 38 | 39 | Gracias a **MTKClient** (https://github.com/bkerler/mtkclient) podremos hacer una copia de seguridad completa del contenido del dispositivo. 40 | Esto incluye tanto el software que está ejecutando (Android Go 10) con Google Assistant como las particiones auxiliares, así como los datos de usuario y los identificativos del dispositivo (número de serie, MAC de WiFI/BT, etc). 41 | Debido a que no hay disponible ninguna descarga del paquete para SP Flash Tool conteniendo el software del dispositivo, esta es una forma sencilla de suplir esa carencia. 42 | 43 | Una vez instalado MTKClient siguiendo los pasos de su repositorio, bastará con ejecutar "mtk_gui" con python ("python mtk_gui") para que se muestren la ventana de su interfaz gráfica. Del mismo modo en la ventana del terminal desde la que hemos ejecutado el comando se nos indicará que el programa está esperando al dispositivo. 44 | Mientras mantenemos presionado el botón de subir volumen conectamos el cable USB entre el dispositivo y el PC, éste será detectado y tras unos segundos se mostrarán todas las opciones disponibles en la interfaz. 45 | 46 | Lo primero que haremos será la copia de seguridad de la memoria completa. Para ello en la pestaña "Flash tools" pulsaremos el botón "Read flash", le indicaremos la ruta donde guardar el archivo y esperaremos pacientemente ya que puede tardar bastante tiempo, dependiendo de factores como nuestra controladora USB, la calidad del cable de conexión o la versión del sistema operativo. 47 | 48 | Una vez terminado este proceso haremos lo mismo con los botones "Read preloader" y "Read boot2". 49 | Después, en la pestaña "Read partition(s)" marcaremos "Select all partitions" y pulsaremos el botón "Read partition(s)" para de nuevo hacer una copia de la memoria del dispositivo, esta vez separada en particiones. 50 | 51 | Si todo ha ido bien la copia de seguridad debe tener un tamaño cercano a los 4GB (tanto la completa como la suma de los archivos de la otra), que es el tamaño de la memoria flash del dispositivo. 52 | -------------------------------------------------------------------------------- /howtos/WorkingWithGSI.md: -------------------------------------------------------------------------------- 1 | ## -------- English -------- 2 | 3 | It is possible to install GSI ROMs on Mi Smart Clock thanks to the fact that it is based on Android 10, leading to compatibility with the Treble project that enables this functionality. However there are two limitations that, although they do not detract from the functionality, must be taken into account: 4 | 5 | 1.- To install a GSI image on the device you have to insert it previously in a "super" image, due to the fact that the product, system and vendor logical partitions are not exposed through fastboot, either in bootloader or fastbootd. 6 | 7 | 2.- Because the precompiled SELinux policies are very restrictive, GSI ROMs do not boot with SELinux enabled. In order to use them we must disable this feature (as we don't have a better solution yet). 8 | 9 | ### Unpacking super for GSI 10 | 11 | Steps are similar to those we followed previously with stock ROM, and in fact we need the result of that work (one of the NEW_super.img files we have verified is working properly) as a base to get a GSI ROM installed. 12 | 13 | We will use the "unpack_gsi_super.sh" script, contained in the tools folder. 14 | 15 | This script, if used in conjunction with a "super.img" like the one we generated with the previous guide, will delete the product and system images, leaving only vendor.img and this same file mounted in "mnt/vendor". 16 | Because the GSI images have a larger size than the one originally intended for the logical partition system, it is necessary to get rid of product, which we will not need anyway, to make space. 17 | Similarly, system.img is deleted as it contains the system we want to replace, and will not serve any function in this case. 18 | 19 | If instead we use it together with a super.img that has already been prepared containing a GSI image, it will mount the system and vendor partitions inside "mnt" to work normally with them. 20 | 21 | ### Creating super for GSI 22 | 23 | If when unpacking our super image we have run out of system.img file, it means that the super image has not yet been modified to contain a GSI image. Therefore we must manually copy the GSI image we have chosen renamed to "system.img", so that after running the unpacking script and copying this file we will find vendor.img, "mnt/vendor" mounted and system.img. 24 | 25 | If on the other hand system.img exists and is mounted in "mnt/system", the super image we are using was already correctly prepared to host the GSI image. 26 | 27 | In either case, just run the "repack_gsi_super.sh" script to get a super image with the changes made, as in the previous guide. 28 | 29 | ### Modifying boot 30 | 31 | To get the GSI ROM to boot we have to modify the cmdline of the boot partition, otherwise we will find an infinite bootloop, which if we debug via ADB, we will find SELinux policies contained in the vendor partition prohibit access to critical configuration files to different system services. 32 | 33 | The easy way to solve this, although not the most appropriate, is to disable SELinux. At least, until there is a better solution. 34 | 35 | We will use Android Image Kitchen (linked in the main page of the repository), which will allow us to unpack the boot.bin file that we obtained with the backup of the device using MTKClient. 36 | 37 | Once unpacked, it will be enough to replace its original cmdline: 38 | 39 | bootopt=64S3,32N2,32N2 buildvariant=user 40 | 41 | with this one and repack it: 42 | 43 | bootopt=64S3,32N2,32N2 buildvariant=userdebug enforcing=0 androidboot.selinux=permissive 44 | 45 | To find out how to write the new boot.img to the device, refer to the "FlashingPartitions" guide in this repository. 46 | 47 | 48 | 49 | 50 | ## -------- Spanish -------- 51 | 52 | Es posible usar ROMs GSI en el Mi Smart Clock gracias a que está basado en Android 10, conllevando esto la compatibilidad con el proyecto Treble que habilita esta funcionalidad. Sin embargo hay dos limitaciones que, si bien no nos restan funcionalidad, hay que tener en cuenta: 53 | 54 | 1.- Para instalar una imagen GSI en el dispositivo hay que insertar ésta previamente en una imagen "super", debido a que las particiones lógicas product, system y vendor no están expuestas a través de fastboot, ya sea en el bootloader o en fastbootd. 55 | 56 | 2.- Debido a que las políticas SELinux precompiladas dentro de vendor son muy restrictivas las ROMs GSI no arrancan con SELinux habilitado. Para poder usarlas debemos deshabilitar esta característica (a falta de una mejor solución por el momento). 57 | 58 | ### Desempaquetando super para GSI 59 | 60 | Los pasos son parecidos a los que hemos seguido previamente para trabajar con la ROM stock, y de hecho necesitamos el producto de ese trabajo (uno de los archivos NEW_super.img que funcione correctamente) como base para conseguir instalar una ROM GSI. 61 | 62 | Usaremos el script "unpack_gsi_super.sh", contenido en la carpeta de herramientas, junto con el archivo creado anteriormente (un super.img que hayamos generado nosotros y hayamos verificado que funciona correctamente). 63 | 64 | Este script, si lo usamos en conjunción con un "super.img" como el que hemos generado con la guía anterior, borrará las imágenes product y system, dejando sólo vendor.img y éste mismo archivo montado en "mnt/vendor". 65 | Debido a que las imágenes GSI tienen un mayor tamaño que el destinado en principio para la partición lógica system, es necesario deshacerse de product, que igualmente no necesitaremos, para hacer espacio. 66 | Del mismo modo, system.img es borrado ya que contiene el sistema que queremos sustituir, y no cumplirá ninguna función para este caso. 67 | 68 | Si en cambio lo usamos junto con un super que ya ha sido preparado conteniendo una imagen GSI montará las particiones system y vendor dentro de "mnt" para trabajar normalmente con ellas. 69 | 70 | ### Creando super para GSI 71 | 72 | Si al desempaquetar nuestra imagen de super nos hemos quedado sin archivo system.img quiere decir que esa imagen de super aún no había sido modificada para contener una imagen GSI. Por ello debemos copiar manualmente la imagen GSI que hemos elegido renombrada a "system.img", de forma que tras la ejecución del script de desempaquetado y la copia de este archivo nos encontremos con vendor.img, "mnt/vendor" montado y system.img. 73 | 74 | Si por el contrario system.img existe y está montado en "mnt/system", la imagen de super que estamos usando estaba ya correctamente preparada para alojar la imagen GSI. 75 | 76 | En cualquier de los dos casos, bastará con ejecutar el script "repack_gsi_super.sh" para obtener una imagen de super con los cambios realizados, como en la guía anterior. 77 | 78 | ### Modificando boot 79 | 80 | Para conseguir que la ROM GSI arranque es necesario hacer una modificación dentro del cmdline de la partición boot del dispositivo, de lo contrario nos encontraremos con un bootloop infinito, que si depuramos mediantes ADB, veremos que se debe a que las políticas de SELinux contenidas en la partición vendor prohíben el acceso a archivos críticos de configuración a diferentes servicios del sistema. 81 | 82 | El modo más sencillo de solventar esto, si bien no el más adecuado, es deshabilitar SELinux. Al menos, hasta que haya una solución mejor. 83 | 84 | Usaremos Android Imagen Kitchen (enlazado en la página principal del repositorio), que nos permitirá desempaquetar el archivo boot.bin que obtuvimos con la copia de seguridad del dispositivo mediante MTKClient. 85 | 86 | Una vez desempaquetado, bastará con sustituir su cmdline original: 87 | 88 | bootopt=64S3,32N2,32N2 buildvariant=user 89 | 90 | con este y volver a empaquetarlo: 91 | 92 | bootopt=64S3,32N2,32N2 buildvariant=userdebug enforcing=0 androidboot.selinux=permissive 93 | 94 | Para saber cómo escribir el nuevo boot.img en el dispositivo, dirígete a la guía "FlashingPartitions" en este mismo repositorio. 95 | --------------------------------------------------------------------------------