Refactor adb patching and emulator setup

Add support for patching boot images directly via adb
with the build.py script.
This commit is contained in:
topjohnwu
2026-09-21 01:40:07 -07:00
parent 89d3100ffc
commit aed0261c3d
8 changed files with 123 additions and 91 deletions
@@ -40,7 +40,7 @@ class Environment : BaseTest {
@JvmStatic
fun before() = BaseTest.prerequisite()
// Whether we're running with live setup (patches through live_setup.sh)
// Whether we're running with live setup (patches through avd_setup.sh)
fun isLiveSetup(): Boolean {
val liveMarker = ShellUtils.fastCmd("echo \$MAGISKTMP/.magisk/live")
return RootUtils.fs.getFile(liveMarker).exists()
+68 -32
View File
@@ -9,6 +9,7 @@ import stat
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.request
from pathlib import Path
@@ -31,6 +32,10 @@ abi_alias = {
"arm64": "arm64-v8a",
"x64": "x86_64",
}
abi32_map = {
"arm64-v8a": "armeabi-v7a",
"x86_64": "x86",
}
default_abis = support_abis.keys() - {"riscv64"}
support_targets = {"magisk", "magiskinit", "magiskboot", "magiskpolicy", "resetprop"}
default_targets = support_targets - {"resetprop"}
@@ -621,7 +626,7 @@ def setup_rustup():
##################
def push_files(script: Path):
def push_files(files: list[Path], push_apk: bool = False):
if args.build:
build_all()
@@ -635,53 +640,81 @@ def push_files(script: Path):
name = "app-release.apk" if args.release else "app-debug.apk"
apk = Path(config["outdir"], name)
# Extract busybox from APK
busybox = Path(config["outdir"], "busybox")
with ZipFile(apk) as zf:
with zf.open(f"lib/{abi}/libbusybox.so") as libbb:
with open(busybox, "wb") as bb:
bb.write(libbb.read())
if not apk.is_file():
error(f"Cannot find {apk}")
try:
proc = execv([adb_path(), "push", busybox, script, "/data/local/tmp"])
with tempfile.TemporaryDirectory() as tmp_dir:
tmp = Path(tmp_dir)
to_push = list(files)
with ZipFile(apk) as zf:
# Extract stub.apk
stub = tmp / "stub.apk"
stub.write_bytes(zf.read("assets/stub.apk"))
to_push.append(stub)
# Extract assets/*.sh
for name in zf.namelist():
if name.startswith("assets/") and name.endswith(".sh") and name.count("/") == 1:
dest = tmp / Path(name).name
dest.write_bytes(zf.read(name))
to_push.append(dest)
# Extract native libs for target ABI
prefix = f"lib/{abi}/"
for name in zf.namelist():
if name.startswith(prefix):
base_name = Path(name).name
if base_name.startswith("lib") and base_name.endswith(".so"):
dest = tmp / base_name[3:-3]
dest.write_bytes(zf.read(name))
to_push.append(dest)
# Extract 32-bit magisk if exist in the APK
abi32 = abi32_map.get(abi)
if abi32:
magisk32_entry = f"lib/{abi32}/libmagisk.so"
if magisk32_entry in zf.namelist():
dest = tmp / "magisk32"
dest.write_bytes(zf.read(magisk32_entry))
to_push.append(dest)
execv([adb_path(), "shell", "rm", "-rf", "/data/local/tmp/*"])
proc = execv([adb_path(), "push", *to_push, "/data/local/tmp"])
if proc.returncode != 0:
error("adb push failed!")
finally:
rm_rf(busybox)
proc = execv([adb_path(), "push", apk, "/data/local/tmp/magisk.apk"])
if proc.returncode != 0:
error("adb push failed!")
if push_apk:
proc = execv([adb_path(), "push", apk, "/data/local/tmp/magisk.apk"])
if proc.returncode != 0:
error("adb push failed!")
def setup_avd():
header("* Setting up emulator")
push_files(Path("scripts", "live_setup.sh"))
push_files([Path("scripts", "avd_setup.sh")], push_apk=True)
proc = execv([adb_path(), "shell", "sh", "/data/local/tmp/live_setup.sh"])
proc = execv([adb_path(), "shell", "sh", "/data/local/tmp/avd_setup.sh"])
if proc.returncode != 0:
error("live_setup.sh failed!")
error("avd_setup.sh failed!")
def patch_avd_file():
def patch():
input_file = Path(args.image)
output = Path(args.output)
header(f"* Patching {input_file.name}")
push_files(Path("scripts", "host_patch.sh"))
proc = execv([adb_path(), "push", input_file, "/data/local/tmp"])
if proc.returncode != 0:
error("adb push failed!")
script = "avd_patch.sh" if args.avd else "adb_patch.sh"
push_files([Path("scripts", script), input_file])
src_file = f"/data/local/tmp/{input_file.name}"
out_file = f"{src_file}.magisk"
proc = execv([adb_path(), "shell", "sh", "/data/local/tmp/host_patch.sh", src_file])
proc = execv([adb_path(), "shell", "sh", f"/data/local/tmp/{script}", src_file])
if proc.returncode != 0:
error("host_patch.sh failed!")
error(f"{script} failed!")
proc = execv([adb_path(), "pull", out_file, output])
if proc.returncode != 0:
@@ -819,13 +852,16 @@ def parse_args():
"-b", "--build", action="store_true", help="build before patching"
)
avd_patch_parser = subparsers.add_parser(
"avd_patch", help="patch AVD ramdisk.img or init_boot.img"
patch_parser = subparsers.add_parser(
"patch", help="patch boot image or AVD ramdisk.img via ADB"
)
avd_patch_parser.add_argument("image", help="path to ramdisk.img or init_boot.img")
avd_patch_parser.add_argument("output", help="output file name")
avd_patch_parser.add_argument("--apk", help="a Magisk APK to use")
avd_patch_parser.add_argument(
patch_parser.add_argument("image", help="path to image to patch")
patch_parser.add_argument("output", help="output file name")
patch_parser.add_argument("--apk", help="a Magisk APK to use")
patch_parser.add_argument(
"--avd", action="store_true", help="the input file is an AVD ramdisk.img"
)
patch_parser.add_argument(
"-b", "--build", action="store_true", help="build before patching"
)
@@ -865,7 +901,7 @@ def parse_args():
stub_parser.set_defaults(func=build_stub)
test_parser.set_defaults(func=build_test)
emu_parser.set_defaults(func=setup_avd)
avd_patch_parser.set_defaults(func=patch_avd_file)
patch_parser.set_defaults(func=patch)
clean_parser.set_defaults(func=cleanup)
ndk_parser.set_defaults(func=setup_ndk)
+37
View File
@@ -0,0 +1,37 @@
#####################################################################
# ADB Magisk Boot Image Patcher
#####################################################################
#
# With a device accessible via ADB, usage:
# ./build.py patch path/to/boot.img
#
#####################################################################
if [ ! -f /system/build.prop ]; then
# Running on PC
echo 'Please run `./build.py patch` instead of directly executing the script!'
exit 1
fi
cd /data/local/tmp
chmod 755 busybox magisk*
if [ -z "$FIRST_STAGE" ]; then
export FIRST_STAGE=1
export ASH_STANDALONE=1
# Re-exec script with busybox
exec ./busybox sh $0 "$@"
fi
TARGET_FILE="$1"
OUTPUT_FILE="$1.magisk"
# Fetch env flags using non-root functions in app_functions
. ./app_functions.sh
mount_partitions
get_flags
# Patch the boot image to the target path
sh boot_patch.sh $TARGET_FILE
mv new-boot.img $OUTPUT_FILE
./magiskboot cleanup
+1 -1
View File
@@ -249,7 +249,7 @@ test_main() {
local images=()
for apk in "${apks[@]}"; do
images+=("magisk-$(basename $apk .apk).img")
./build.py -v avd_patch --apk "$apk" "$ramdisk" "${images[-1]}"
./build.py -v patch --avd --apk "$apk" "$ramdisk" "${images[-1]}"
done
adb emu kill
+7 -33
View File
@@ -5,7 +5,7 @@
# Support API level: 23 - 36
#
# With an emulator booted and accessible via ADB, usage:
# ./build.py avd_patch path/to/booted/avd-image/ramdisk.img
# ./build.py patch --avd path/to/booted/avd-image/ramdisk.img
#
# The purpose of this script is to patch AVD ramdisk.img and do a
# full integration test of magiskinit under several circumstances.
@@ -23,12 +23,12 @@
if [ ! -f /system/build.prop ]; then
# Running on PC
echo 'Please run `./build.py avd_patch` instead of directly executing the script!'
echo 'Please run `./build.py patch --avd` instead of directly executing the script!'
exit 1
fi
cd /data/local/tmp
chmod 755 busybox
chmod 755 busybox magisk*
if [ -z "$FIRST_STAGE" ]; then
export FIRST_STAGE=1
@@ -40,29 +40,7 @@ fi
TARGET_FILE="$1"
OUTPUT_FILE="$1.magisk"
if echo "$TARGET_FILE" | grep -q 'ramdisk'; then
IS_RAMDISK=true
else
IS_RAMDISK=false
fi
# Extract files from APK
unzip -oj magisk.apk 'assets/util_functions.sh' 'assets/stub.apk'
. ./util_functions.sh
api_level_arch_detect
unzip -oj magisk.apk "lib/$ABI/*" -x "lib/$ABI/libbusybox.so"
for file in lib*.so; do
chmod 755 $file
mv "$file" "${file:3:${#file}-6}"
done
if $IS_RAMDISK; then
./magiskboot decompress "$TARGET_FILE" ramdisk.cpio
else
./magiskboot unpack "$TARGET_FILE"
fi
./magiskboot decompress "$TARGET_FILE" ramdisk.cpio
cp ramdisk.cpio ramdisk.cpio.orig
export KEEPVERITY=true
@@ -73,7 +51,8 @@ echo "KEEPFORCEENCRYPT=$KEEPFORCEENCRYPT" >> config
echo "PREINITDEVICE=$(./magisk --preinit-device)" >> config
# For API 28, we also manually disable SystemAsRoot
# Explicitly override skip_initramfs by setting RECOVERYMODE=true
[ $API = "28" ] && echo 'RECOVERYMODE=true' >> config
API=$(getprop ro.build.version.sdk)
[ "$API" = "28" ] && echo 'RECOVERYMODE=true' >> config
cat config
./magiskboot compress=xz magisk magisk.xz
@@ -93,9 +72,4 @@ cat config
"add 000 .backup/.magisk config"
rm -f ramdisk.cpio.orig config *.xz
if $IS_RAMDISK; then
./magiskboot compress=gzip ramdisk.cpio "$OUTPUT_FILE"
else
./magiskboot repack "$TARGET_FILE" "$OUTPUT_FILE"
./magiskboot cleanup
fi
./magiskboot compress=gzip ramdisk.cpio "$OUTPUT_FILE"
+8 -21
View File
@@ -37,7 +37,7 @@ if [ ! -f /system/build.prop ]; then
fi
cd /data/local/tmp
chmod 755 busybox
chmod 755 busybox magisk*
if [ -z "$FIRST_STAGE" ]; then
export FIRST_STAGE=1
@@ -53,24 +53,6 @@ fi
pm install -r -g $(pwd)/magisk.apk
# Extract files from APK
unzip -oj magisk.apk 'assets/util_functions.sh' 'assets/stub.apk'
. ./util_functions.sh
api_level_arch_detect
unzip -oj magisk.apk "lib/$ABI/*" -x "lib/$ABI/libbusybox.so"
for file in lib*.so; do
chmod 755 $file
mv "$file" "${file:3:${#file}-6}"
done
if $IS64BIT && [ -e "/system/bin/linker" ]; then
unzip -oj magisk.apk "lib/$ABI32/libmagisk.so"
mv libmagisk.so magisk32
chmod 755 magisk32
fi
# Stop zygote (and previous setup if exists)
magisk --stop 2>/dev/null
stop
@@ -125,14 +107,19 @@ else
fi
# Magisk stuff
MAGISKBIN=/data/adb/magisk
mkdir -p $MAGISKBIN 2>/dev/null
unzip -oj magisk.apk 'assets/*.sh' -d $MAGISKBIN
mkdir /data/adb/modules 2>/dev/null
mkdir /data/adb/post-fs-data.d 2>/dev/null
mkdir /data/adb/service.d 2>/dev/null
for file in magisk magisk32 magiskpolicy stub.apk; do
if [ ! -e $file ]; then continue; fi
MAGISK_FILES="magisk magiskpolicy stub.apk"
if [ -e /system/bin/linker ] && [ -e /system/bin/linker64 ]; then
MAGISK_FILES="$MAGISK_FILES magisk32"
fi
for file in $MAGISK_FILES; do
chmod 755 ./$file
cp -af ./$file $MAGISKTMP/$file
cp -af ./$file $MAGISKBIN/$file
-2
View File
@@ -55,8 +55,6 @@ if [ -z $SOURCEDMODE ]; then
cd "$(getdir "${BASH_SOURCE:-$0}")"
# Load utility functions
. ./util_functions.sh
# Check if 64-bit
api_level_arch_detect
fi
BOOTIMAGE="$1"
+1 -1
View File
@@ -87,7 +87,7 @@ test_main() {
local images=()
for apk in "${apks[@]}"; do
images+=("magisk-$(basename $apk .apk).img")
./build.py -v avd_patch --apk "$apk" "$CF_HOME/init_boot.img" "${images[-1]}"
./build.py -v patch --apk "$apk" "$CF_HOME/init_boot.img" "${images[-1]}"
done
for i in "${!apks[@]}"; do