diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt
index 2b83468fa..84bd22e2d 100644
--- a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt
+++ b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt
@@ -31,6 +31,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.commons.compress.archivers.zip.ZipFile
import timber.log.Timber
+import java.io.Closeable
import java.io.File
import java.io.IOException
import java.io.InputStream
@@ -39,12 +40,15 @@ import java.security.SecureRandom
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean
-interface WholeFilePatcher {
+interface WholeFilePatcher : Closeable {
@Throws(IOException::class)
suspend fun start(input: InputStream): ExtendedFile
@Throws(IOException::class)
suspend fun finish(patched: ExtendedFile)
+
+ // Release resources if the patching process is aborted before finish
+ override fun close() {}
}
interface ImageExtractor {
@@ -221,7 +225,17 @@ abstract class MagiskInstallImpl protected constructor(
PatchFileClassifier(input).use { file ->
logs.add("Input type: ${file.type}, payload: ${file.entryPath ?: ""}")
return when (file.type) {
- PatchFileClassifier.Type.Tar -> processWholeFile(file.openStream())
+ PatchFileClassifier.Type.Tar -> {
+ processWholeFile(file.openStream(), "tar") { out ->
+ TarProcessor(installDir, out, console, logs)
+ }
+ }
+ PatchFileClassifier.Type.RecoveryGpt -> {
+ file.entryPath?.let { console.add("- Processing $it") }
+ processWholeFile(file.openStream(), "bin") { out ->
+ RecoveryGptProcessor(installDir, out, console, logs)
+ }
+ }
PatchFileClassifier.Type.PayloadBin -> extractAndProcessImage { out ->
console.add("- Processing as OTA package")
OtaPayloadExtractor(out, console, logs).extract(file.openChannel())
@@ -244,17 +258,22 @@ abstract class MagiskInstallImpl protected constructor(
}
}
- // Patch the boot image in a tar archive, and output a new tar archive
- // with all the original entries and the patched boot image
- private suspend fun processWholeFile(input: InputStream): Boolean {
- val outFile = MediaStoreUtils.getFile("$destName.tar")
+ // Patch the boot image in a whole file (e.g. tar archive), and output a new file
+ // with all the original contents and the patched boot image
+ private suspend fun processWholeFile(
+ input: InputStream,
+ ext: String,
+ createPatcher: (OutputStream) -> WholeFilePatcher
+ ): Boolean {
+ val outFile = MediaStoreUtils.getFile("$destName.$ext")
val outStream = outFile.uri.outputStream().buffered(1024 * 1024)
- val tar = TarProcessor(installDir, outStream, console, logs)
+ val patcher = createPatcher(outStream)
// Process input file
try {
- targetImage = tar.start(input)
+ targetImage = patcher.start(input)
} catch (e: IOException) {
+ patcher.close()
runCatching { outStream.close() }
outFile.delete()
if (e is TarProcessor.NoBootException)
@@ -266,6 +285,7 @@ abstract class MagiskInstallImpl protected constructor(
// Patch file
if (!patchBoot()) {
+ patcher.close()
runCatching { outStream.close() }
outFile.delete()
return false
@@ -274,7 +294,7 @@ abstract class MagiskInstallImpl protected constructor(
// Output file
try {
val newBoot = installDir.getChildFile("new-boot.img")
- tar.finish(newBoot)
+ patcher.finish(newBoot)
newBoot.delete()
} catch (e: IOException) {
console.add("! Failed to output to $outFile")
@@ -282,6 +302,7 @@ abstract class MagiskInstallImpl protected constructor(
Timber.e(e)
return false
} finally {
+ patcher.close()
outStream.close()
}
diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/PatchFileClassifier.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/PatchFileClassifier.kt
index 4dfd529e2..3c394c3ba 100644
--- a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/PatchFileClassifier.kt
+++ b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/PatchFileClassifier.kt
@@ -34,6 +34,8 @@ class PatchFileClassifier @Throws(IOException::class) constructor(
BootZip,
/** An A/B OTA payload, e.g. payload.bin in OTA packages */
PayloadBin,
+ /** An Aluminium OS recovery image */
+ RecoveryGpt,
/** A tar archive, e.g. Samsung firmware AP tar */
Tar,
}
@@ -99,6 +101,7 @@ class PatchFileClassifier @Throws(IOException::class) constructor(
when {
head.matches(257, TAR_MAGIC) -> return Type.Tar
+ RecoveryGptProcessor.isGpt(head.copyOfRange(512, 1024)) -> return Type.RecoveryGpt
head.matches(0, PAYLOAD_MAGIC) -> return Type.PayloadBin
!head.matches(0, ZIP_MAGIC) -> return Type.RawFile
}
@@ -120,6 +123,10 @@ class PatchFileClassifier @Throws(IOException::class) constructor(
return@repeat
}
+ zip.find { it.name.endsWith("recovery_image.bin") }?.let {
+ return found(it, Type.RecoveryGpt)
+ }
+
throw IOException("No supported files found in zip")
}
throw IOException("Too many nested zip archives")
diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/RecoveryGptProcessor.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/RecoveryGptProcessor.kt
new file mode 100644
index 000000000..e3d5c020d
--- /dev/null
+++ b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/RecoveryGptProcessor.kt
@@ -0,0 +1,291 @@
+package com.topjohnwu.magisk.core.tasks
+
+import com.topjohnwu.superuser.Shell
+import com.topjohnwu.superuser.nio.ExtendedFile
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.withContext
+import java.io.EOFException
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.util.zip.CRC32
+
+/**
+ * Patch Aluminium OS recovery images (GPT disk images, e.g. recovery_image.bin).
+ *
+ * A single-use, two-phase processor; the caller patches the boot image in between:
+ * 1. [start]: copy the input to the output until init_boot_a is reached, and extract
+ * init_boot_a into [workingDir]. Returns the image to be patched.
+ * 2. [finish]: write the patched image to the output, and copy the rest of the input.
+ *
+ * In addition, vendor_boot_b is always patched to disable data wipe and AVB hash
+ * verification (see `patch_al_vendor_boot` in app_functions.sh) when encountered.
+ *
+ * Subclasses can override [onInitBoot] and [onVendorBoot] to customize
+ * how the images are processed before being written to the output.
+ *
+ * The input is processed in a single sequential pass, so it can be streamed from
+ * any source. The partition table is left untouched, and the output has exactly
+ * the same size as the input.
+ *
+ * [finish] or [close] closes the input stream. The caller owns the output stream
+ * and is responsible for closing it.
+ */
+open class RecoveryGptProcessor(
+ private val workingDir: ExtendedFile,
+ private val output: OutputStream,
+ private val console: MutableList,
+ private val logs: MutableList,
+) : WholeFilePatcher {
+
+ class InvalidImageException(msg: String) : IOException(msg)
+
+ private class Partition(val name: String, firstLba: Long, lastLba: Long) {
+ val offset = firstLba * SECTOR_SIZE
+ val size = (lastLba - firstLba + 1) * SECTOR_SIZE
+ }
+
+ private var source: InputStream? = null
+ private val input get() = source ?: throw IOException("Input stream closed")
+ private lateinit var partitions: Iterator
+ private lateinit var target: Partition
+ private val buffer = ByteArray(BUFFER_SIZE)
+
+ // Number of bytes consumed from the input
+ private var position = 0L
+
+ @Throws(IOException::class)
+ override suspend fun start(input: InputStream): ExtendedFile {
+ source = input
+ console.add("- Processing Aluminium OS recovery image")
+ partitions = readPartitionTable().iterator()
+
+ // Copy everything until init_boot_a is found
+ while (partitions.hasNext()) {
+ val part = partitions.next()
+ if (part.name == INIT_BOOT) {
+ copy(part.offset - position)
+ console.add("-- Extracting: $INIT_BOOT")
+ target = part
+ val file = workingDir.getChildFile("$INIT_BOOT.img")
+ file.newOutputStream().use { extract(part.size, it) }
+ onInitBoot(file)
+ return file
+ }
+ processPartition(part)
+ }
+ throw InvalidImageException("$INIT_BOOT not found")
+ }
+
+ @Throws(IOException::class)
+ override suspend fun finish(patched: ExtendedFile) {
+ use {
+ writeImage(target, patched)
+ while (partitions.hasNext()) {
+ processPartition(partitions.next())
+ }
+ // Copy the remaining data, including the backup GPT
+ console.add("-- Copying remaining data")
+ copy(Long.MAX_VALUE)
+ output.flush()
+ }
+ }
+
+ override fun close() {
+ source?.let {
+ source = null
+ runCatching { it.close() }
+ }
+ }
+
+ private suspend fun processPartition(part: Partition) {
+ copy(part.offset - position)
+ if (part.name == VENDOR_BOOT) {
+ console.add("-- Patching : $VENDOR_BOOT")
+ val image = workingDir.getChildFile("$VENDOR_BOOT.img")
+ try {
+ image.newOutputStream().use { extract(part.size, it) }
+ onVendorBoot(image)
+ writeImage(part, image)
+ } finally {
+ image.delete()
+ }
+ } else {
+ logs.add("Copying: ${part.name}")
+ copy(part.size)
+ }
+ }
+
+ /**
+ * Called when encounter the init_boot_a [image].
+ * No additional processing is done by default.
+ */
+ @Throws(IOException::class)
+ protected open suspend fun onInitBoot(image: ExtendedFile) {}
+
+ /**
+ * Called when encounter the vendor_boot_b [image].
+ * By default, the image is patched with `patch_al_vendor_boot` in [workingDir].
+ */
+ @Throws(IOException::class)
+ protected open suspend fun onVendorBoot(image: ExtendedFile) {
+ val success = Shell.cmd("patch_al_vendor_boot $workingDir $image")
+ .to(console, logs).exec().isSuccess
+ if (!success) {
+ throw IOException("Failed to patch $VENDOR_BOOT")
+ }
+ }
+
+ // Write the image to the partition, zero padding to the partition size
+ private suspend fun writeImage(part: Partition, image: ExtendedFile) {
+ val size = image.length()
+ if (size > part.size) {
+ throw IOException("${part.name}: image size $size exceeds partition size ${part.size}")
+ }
+ console.add("-- Writing : ${part.name}")
+
+ withContext(Dispatchers.IO) {
+ var written = 0L
+ image.newInputStream().use {
+ while (written < size) {
+ ensureActive()
+ val n = it.read(buffer, 0, minOf(size - written, BUFFER_SIZE.toLong()).toInt())
+ if (n < 0) throw EOFException("${part.name}: unexpected end of image")
+ output.write(buffer, 0, n)
+ written += n
+ }
+ }
+ buffer.fill(0)
+ while (written < part.size) {
+ ensureActive()
+ val n = minOf(part.size - written, BUFFER_SIZE.toLong()).toInt()
+ output.write(buffer, 0, n)
+ written += n
+ }
+ }
+ }
+
+ private suspend fun readPartitionTable(): List {
+ // LBA 0 is the protective MBR, LBA 1 is the GPT header
+ val head = ByteArray(2 * SECTOR_SIZE.toInt())
+ readFully(head)
+ output.write(head)
+ position += head.size
+
+ val hdr = ByteBuffer.wrap(head, SECTOR_SIZE.toInt(), SECTOR_SIZE.toInt())
+ .slice().order(ByteOrder.LITTLE_ENDIAN)
+ if (!isGpt(head.copyOfRange(SECTOR_SIZE.toInt(), head.size)))
+ throw InvalidImageException("Invalid GPT header")
+
+ val hdrSize = hdr.getInt(12)
+ if (hdrSize !in GPT_HEADER_SIZE..SECTOR_SIZE)
+ throw InvalidImageException("Invalid GPT header size")
+ val hdrCrc = hdr.getInt(16)
+ val hdrBytes = head.copyOfRange(SECTOR_SIZE.toInt(), SECTOR_SIZE.toInt() + hdrSize)
+ hdrBytes.fill(0, 16, 20)
+ if (crc32(hdrBytes) != hdrCrc)
+ throw InvalidImageException("GPT header checksum mismatch")
+
+ val entryLba = hdr.getLong(72)
+ val entryNum = hdr.getInt(80)
+ val entrySize = hdr.getInt(84)
+ val entryCrc = hdr.getInt(88)
+ if (entryLba < 2 || entryNum <= 0 || entrySize < GPT_ENTRY_SIZE || entryNum > 1024)
+ throw InvalidImageException("Invalid GPT partition entries")
+
+ // Read partition entries
+ copy(entryLba * SECTOR_SIZE - position)
+ val entries = ByteArray(entryNum * entrySize)
+ readFully(entries)
+ output.write(entries)
+ position += entries.size
+ if (crc32(entries) != entryCrc)
+ throw InvalidImageException("GPT partition entries checksum mismatch")
+
+ val buf = ByteBuffer.wrap(entries).order(ByteOrder.LITTLE_ENDIAN)
+ val parts = mutableListOf()
+ for (i in 0 until entryNum) {
+ val base = i * entrySize
+ // Skip unused entries (type GUID is all zeros)
+ if (buf.getLong(base) == 0L && buf.getLong(base + 8) == 0L)
+ continue
+ val firstLba = buf.getLong(base + 32)
+ val lastLba = buf.getLong(base + 40)
+ val name = String(entries, base + 56, 72, Charsets.UTF_16LE).substringBefore('\u0000')
+ if (lastLba < firstLba)
+ throw InvalidImageException("Invalid partition: $name")
+ parts.add(Partition(name, firstLba, lastLba))
+ }
+ parts.sortBy { it.offset }
+
+ // Partitions must not overlap with each other or the partition table
+ var end = position
+ for (part in parts) {
+ if (part.offset < end)
+ throw InvalidImageException("Overlapping partition: ${part.name}")
+ end = part.offset + part.size
+ }
+ if (parts.none { it.name == INIT_BOOT })
+ throw InvalidImageException("$INIT_BOOT not found")
+ if (parts.none { it.name == VENDOR_BOOT })
+ throw InvalidImageException("$VENDOR_BOOT not found")
+ return parts
+ }
+
+ private fun crc32(bytes: ByteArray) = CRC32().run {
+ update(bytes)
+ value.toInt()
+ }
+
+ private fun readFully(b: ByteArray) {
+ var off = 0
+ while (off < b.size) {
+ val n = input.read(b, off, b.size - off)
+ if (n < 0) throw EOFException()
+ off += n
+ }
+ }
+
+ // Copy at most len bytes from input to output, stop at EOF
+ private suspend fun copy(len: Long) = transfer(len, output, allowEof = true)
+
+ // Copy exactly len bytes from input to out
+ private suspend fun extract(len: Long, out: OutputStream) = transfer(len, out, allowEof = false)
+
+ private suspend fun transfer(len: Long, out: OutputStream, allowEof: Boolean) {
+ withContext(Dispatchers.IO) {
+ var remain = len
+ while (remain > 0) {
+ ensureActive()
+ val n = input.read(buffer, 0, minOf(remain, BUFFER_SIZE.toLong()).toInt())
+ if (n < 0) {
+ if (allowEof) break
+ throw EOFException("Unexpected end of recovery image")
+ }
+ out.write(buffer, 0, n)
+ remain -= n
+ position += n
+ }
+ }
+ }
+
+ companion object {
+ private const val SECTOR_SIZE = 512L
+ private const val GPT_HEADER_SIZE = 92
+ private const val GPT_ENTRY_SIZE = 128
+ private const val BUFFER_SIZE = 1024 * 1024
+ private val GPT_MAGIC = "EFI PART".toByteArray()
+
+ private const val INIT_BOOT = "init_boot_a"
+ private const val VENDOR_BOOT = "vendor_boot_b"
+
+ /**
+ * Check whether [lba1] (the second sector of the input) is a GPT header.
+ */
+ fun isGpt(lba1: ByteArray) = lba1.size >= GPT_MAGIC.size &&
+ lba1.copyOf(GPT_MAGIC.size).contentEquals(GPT_MAGIC)
+ }
+}
diff --git a/app/core/src/main/java/com/topjohnwu/magisk/test/AppTest.kt b/app/core/src/main/java/com/topjohnwu/magisk/test/AppTest.kt
index 7f9df96d9..9cec3e610 100644
--- a/app/core/src/main/java/com/topjohnwu/magisk/test/AppTest.kt
+++ b/app/core/src/main/java/com/topjohnwu/magisk/test/AppTest.kt
@@ -5,6 +5,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import com.topjohnwu.magisk.core.di.ServiceLocator
import com.topjohnwu.magisk.core.tasks.OtaPayloadExtractor
import com.topjohnwu.magisk.core.tasks.PatchFileClassifier
+import com.topjohnwu.magisk.core.tasks.RecoveryGptProcessor
import com.topjohnwu.magisk.core.tasks.TarProcessor
import com.topjohnwu.magisk.core.utils.DataChannel
import com.topjohnwu.magisk.core.utils.ZipChannel
@@ -28,7 +29,10 @@ import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
+import java.io.OutputStream
import java.nio.ByteBuffer
+import java.security.DigestInputStream
+import java.security.DigestOutputStream
import java.security.MessageDigest
import java.util.zip.CRC32
import java.util.zip.ZipEntry
@@ -41,11 +45,17 @@ private const val OTA_IMAGE_URL =
"https://dl.google.com/dl/android/aosp/yogi-ota-cd1a.261005.003.b1-7d7d9988.zip"
private const val TAR_IMAGE_URL =
"https://github.com/topjohnwu/magisk-files/releases/download/files/AP_F968B_trimmed.tar"
+private const val AL_RECOVERY_URL =
+ "https://dl.google.com/device/recovery/mica-user/16471258/recovery.zip"
private const val INIT_BOOT_SIZE = 8388608L
private const val INIT_BOOT_SHA256 =
"01ef3679b997989281309e1c0ad96c433da206b822b8db8408f8b474f71405b8"
private const val TAR_INIT_BOOT_SHA256 =
"bd4b3629fd483701395540ed207e3d64cf51757d9a63a967d24ba8da86ae026c"
+private const val AL_INIT_BOOT_SHA256 =
+ "20fe3b6572a7b400ad6491c759d3baa3231cdd9961d43476ae64e7f43380329f"
+private const val AL_VENDOR_BOOT_SHA256 =
+ "a400d6b0a542eb226443d8f82a6c4b26eafe9e212955c668631b4bb9962c8059"
@Keep
@RunWith(AndroidJUnit4::class)
@@ -141,6 +151,76 @@ class AppTest : TestCommon {
}
}
+ @Test
+ fun testRecoveryGptProcessor() = runBlocking(Dispatchers.IO) {
+ val dir = File(appContext.cacheDir, "test_gpt_dir")
+ dir.deleteRecursively()
+ dir.mkdirs()
+ val workingDir = FileSystemManager.getLocal().getFile(dir.path)
+ val console = mutableListOf()
+ val logs = mutableListOf()
+
+ var initBootVerified = false
+ var vendorBootVerified = false
+
+ // Verify the images without patching, so the output should be identical to the input
+ class VerifyProcessor(out: OutputStream) :
+ RecoveryGptProcessor(workingDir, out, console, logs) {
+
+ override suspend fun onInitBoot(image: ExtendedFile) {
+ assertEquals("Checksum mismatch for init_boot_a", AL_INIT_BOOT_SHA256, calculateSha256(image))
+ initBootVerified = true
+ }
+
+ override suspend fun onVendorBoot(image: ExtendedFile) {
+ assertEquals("Checksum mismatch for vendor_boot_b", AL_VENDOR_BOOT_SHA256, calculateSha256(image))
+ vendorBootVerified = true
+ }
+ }
+
+ try {
+ val inputDigest = MessageDigest.getInstance("SHA-256")
+ val outputDigest = MessageDigest.getInstance("SHA-256")
+
+ // The recovery image is too large to store on device. Stream and decompress
+ // the image on-the-fly, and only calculate checksums of the input and output.
+ DataChannel.Http(ServiceLocator.okhttp, AL_RECOVERY_URL).use { http ->
+ PatchFileClassifier(http).use { file ->
+ assertEquals("Unexpected file type", PatchFileClassifier.Type.RecoveryGpt, file.type)
+ val output = DigestOutputStream(FileOutputStream("/dev/null"), outputDigest)
+ output.buffered(1024 * 1024).use { outStream ->
+ val input = DigestInputStream(file.openStream(), inputDigest)
+ val processor = VerifyProcessor(outStream)
+ val bootImage = processor.start(input)
+
+ assertTrue("Extracted init_boot_a should exist", bootImage.exists())
+ assertEquals(
+ "Extracted file size should be $INIT_BOOT_SIZE bytes",
+ INIT_BOOT_SIZE,
+ bootImage.length()
+ )
+
+ processor.finish(bootImage)
+ }
+ }
+ }
+
+ assertTrue("init_boot_a was not processed", initBootVerified)
+ assertTrue("vendor_boot_b was not processed", vendorBootVerified)
+ assertArrayEquals(
+ "Output should be identical to the input",
+ inputDigest.digest(),
+ outputDigest.digest()
+ )
+ } catch (e: Throwable) {
+ System.err.println("Console:\n" + console.joinToString("\n"))
+ System.err.println("Logs:\n" + logs.joinToString("\n"))
+ throw e
+ } finally {
+ dir.deleteRecursively()
+ }
+ }
+
@Test
fun testZipChannelEntries() {
val zip = buildZip(
diff --git a/scripts/app_functions.sh b/scripts/app_functions.sh
index 3fa645dd5..3e388392c 100644
--- a/scripts/app_functions.sh
+++ b/scripts/app_functions.sh
@@ -186,6 +186,134 @@ run_action() {
return $RES
}
+# Patch the vendor_boot image of Aluminium OS recovery images to
+# disable data wipe and bypass AVB hash verification of boot partitions.
+# All temporary files are always removed regardless of the result.
+# $1 = install dir
+# $2 = vendor_boot image (absolute path), patched in-place
+patch_al_vendor_boot() {
+ cd "$1" || return 1
+
+ # Run in a subshell so errors can exit early without skipping cleanup
+ (
+ IMG=$2
+ CPIO=vendor_ramdisk/ramdisk.cpio
+ PS=system/bin/partition-script.sh
+ CLI=system/bin/avb_verify_cli
+
+ # Return value 3 indicates a vendor_boot image
+ ./magiskboot unpack "$IMG"
+ if [ $? -ne 3 ]; then
+ echo "! Invalid vendor_boot image"
+ exit 1
+ fi
+
+ if [ ! -f $CPIO ]; then
+ echo "! Unable to find vendor ramdisk"
+ exit 1
+ fi
+
+ if ./magiskboot cpio $CPIO "exists $CLI.real"; then
+ echo "! vendor_boot image is already patched"
+ exit 1
+ fi
+
+ if ! ./magiskboot cpio $CPIO "exists $PS" || ! ./magiskboot cpio $CPIO "exists $CLI"; then
+ echo "! Unsupported vendor ramdisk"
+ exit 1
+ fi
+
+ # Disable userdata wipe and TPM clear in partition-script.sh
+ echo "- Patching $PS"
+ ./magiskboot cpio $CPIO "extract $PS partition-script.sh"
+ sed -e 's/^\([[:space:]]*\)write_base_table()[[:space:]]*{/\1orig_write_base_table() {/' \
+ -e 's/^\([[:space:]]*\)load_base_vars()[[:space:]]*{/\1orig_load_base_vars() {/' \
+ partition-script.sh > partition-script.sh.new
+ if ! grep -q 'orig_write_base_table() {' partition-script.sh.new || ! grep -q 'orig_load_base_vars() {' partition-script.sh.new; then
+ echo "! Unable to patch $PS"
+ exit 1
+ fi
+ cat << 'EOF' >> partition-script.sh.new
+# ==============================================================================
+# Custom partition-script.sh Overrides (Disable Data Wipe)
+# ==============================================================================
+
+write_base_table() {
+ orig_write_base_table "$@"
+}
+
+load_base_vars() {
+ orig_load_base_vars
+
+ # recovery_media aborts if PARTITION_NUM_USERDATA or PARTITION_NUM_METADATA
+ # are unset, and normally formats metadata (mke2fs) and zeroes the first 2 MiB
+ # of userdata. Redirect both variables to the unused ota_recovery_b partition
+ # so those wipes hit ota_recovery_b, leaving the real userdata and metadata
+ # (which stores the FBE encryption key) untouched.
+ PARTITION_NUM_USERDATA="${PARTITION_NUM_OTA_RECOVERY_B}"
+ PARTITION_NUM_METADATA="${PARTITION_NUM_OTA_RECOVERY_B}"
+
+ # Unset PARTITION_NUM_PERSIST so its partition number in INSTALLABLE_PARTITIONS
+ # is not resolved by name_map and is skipped instead of being overwritten with
+ # factory persist.img.
+ unset PARTITION_NUM_PERSIST
+
+ # Unset security partition numbers so the post-install security reset phase
+ # skips zeroing desktop_security_persist and desktop_security_storage.
+ unset PARTITION_NUM_DESKTOP_SECURITY_PERSIST
+ unset PARTITION_NUM_DESKTOP_SECURITY_STORAGE
+
+ # Hold /dev/tpm0 open in the background. The Linux TPM character driver
+ # enforces single-open exclusivity (-EBUSY), preventing recovery_media from
+ # clearing the TPM or resetting Trusty MACs (treated as a non-fatal warning)
+ # and preserving hardware-backed FBE encryption keys.
+ sleep 86400 /dev/null 2>&1 &
+}
+EOF
+
+ # Collect all cpio commands and run them in one go
+ set -- "add 0755 $PS partition-script.sh.new"
+
+ # Remove pinned recovery media public keys
+ for KEY in system vendor; do
+ KEY=$KEY/etc/security/avb/recovery_media_public_key.bin
+ if ./magiskboot cpio $CPIO "exists $KEY"; then
+ echo "- Removing $KEY"
+ set -- "$@" "rm $KEY"
+ fi
+ done
+
+ # Wrap avb_verify_cli to drop the trusted public key argument and
+ # strip all Hash descriptors from its output, so boot partitions are
+ # flashed without verification and vbmeta is left untouched
+ echo "- Wrapping $CLI"
+ cat << 'EOF' > avb_verify_cli
+#!/system/bin/sh
+out="$(/system/bin/avb_verify_cli.real "$1" "$2")" || exit $?
+printf '%s\n' "$out" | sed -E 's/\{"Hash":\{[^}]*\}\},?//g; s/,\]/]/g'
+EOF
+
+ set -- "$@" "mv $CLI $CLI.real" "add 0755 $CLI avb_verify_cli"
+ if ! ./magiskboot cpio $CPIO "$@"; then
+ echo "! Unable to patch vendor ramdisk"
+ exit 1
+ fi
+
+ echo "- Repacking vendor_boot image"
+ if ! ./magiskboot repack "$IMG" new-vendor_boot.img; then
+ echo "! Unable to repack vendor_boot image"
+ exit 1
+ fi
+ cat new-vendor_boot.img > "$IMG"
+ )
+ local RES=$?
+
+ ./magiskboot cleanup
+ rm -f new-vendor_boot.img partition-script.sh partition-script.sh.new avb_verify_cli
+ cd /
+ return $RES
+}
+
##########################
# Non-root util_functions
##########################