Merge "tests: Temporarily add bcc.dat symlink" into main
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
index 086ff3d..50aaa33 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
@@ -19,6 +19,7 @@
 import android.os.FileUtils
 import android.system.ErrnoException
 import android.system.Os
+import android.system.OsConstants
 import android.util.Log
 import com.android.virtualization.terminal.MainActivity.Companion.TAG
 import java.io.BufferedReader
@@ -83,7 +84,7 @@
     }
 
     @Throws(IOException::class)
-    fun getSize(): Long {
+    fun getApparentSize(): Long {
         return Files.size(rootPartition)
     }
 
@@ -118,7 +119,7 @@
     @Throws(IOException::class)
     fun resize(desiredSize: Long): Long {
         val roundedUpDesiredSize = roundUp(desiredSize)
-        val curSize = getSize()
+        val curSize = getApparentSize()
 
         runE2fsck(rootPartition)
 
@@ -127,10 +128,47 @@
         }
 
         if (roundedUpDesiredSize > curSize) {
-            allocateSpace(rootPartition, roundedUpDesiredSize)
+            if (!allocateSpace(roundedUpDesiredSize)) {
+                return curSize
+            }
         }
         resizeFilesystem(rootPartition, roundedUpDesiredSize)
-        return getSize()
+        return getApparentSize()
+    }
+
+    @Throws(IOException::class)
+    private fun allocateSpace(sizeInBytes: Long): Boolean {
+        val curSizeInBytes = getApparentSize()
+        try {
+            RandomAccessFile(rootPartition.toFile(), "rw").use { raf ->
+                Os.posix_fallocate(raf.fd, 0, sizeInBytes)
+            }
+            Log.d(TAG, "Allocated space to: $sizeInBytes bytes")
+            return true
+        } catch (e: ErrnoException) {
+            Log.e(TAG, "Failed to allocate space", e)
+            if (e.errno == OsConstants.ENOSPC) {
+                Log.d(TAG, "Trying to truncate disk into the original size")
+                truncate(curSizeInBytes)
+                return false
+            } else {
+                throw IOException("Failed to allocate space", e)
+            }
+        }
+    }
+
+    @Throws(IOException::class)
+    fun shrinkToMinimumSize(): Long {
+        // Fix filesystem before resizing.
+        runE2fsck(rootPartition)
+
+        val p: String = rootPartition.toAbsolutePath().toString()
+        runCommand("/system/bin/resize2fs", "-M", p)
+        Log.d(TAG, "resize2fs -M completed: $rootPartition")
+
+        // resize2fs may result in an inconsistent filesystem state. Fix with e2fsck.
+        runE2fsck(rootPartition)
+        return getApparentSize()
     }
 
     @Throws(IOException::class)
@@ -139,8 +177,8 @@
             RandomAccessFile(rootPartition.toFile(), "rw").use { raf -> Os.ftruncate(raf.fd, size) }
             Log.d(TAG, "Truncated space to: $size bytes")
         } catch (e: ErrnoException) {
-            Log.e(TAG, "Failed to allocate space", e)
-            throw IOException("Failed to allocate space", e)
+            Log.e(TAG, "Failed to truncate space", e)
+            throw IOException("Failed to truncate space", e)
         }
     }
 
@@ -161,19 +199,6 @@
         }
 
         @Throws(IOException::class)
-        private fun allocateSpace(path: Path, sizeInBytes: Long) {
-            try {
-                RandomAccessFile(path.toFile(), "rw").use { raf ->
-                    Os.posix_fallocate(raf.fd, 0, sizeInBytes)
-                }
-                Log.d(TAG, "Allocated space to: $sizeInBytes bytes")
-            } catch (e: ErrnoException) {
-                Log.e(TAG, "Failed to allocate space", e)
-                throw IOException("Failed to allocate space", e)
-            }
-        }
-
-        @Throws(IOException::class)
         private fun runE2fsck(path: Path) {
             val p: String = path.toAbsolutePath().toString()
             runCommand("/system/bin/e2fsck", "-y", "-f", p)
@@ -213,7 +238,7 @@
             }
         }
 
-        private fun roundUp(bytes: Long): Long {
+        internal fun roundUp(bytes: Long): Long {
             // Round up every diskSizeStep MB
             return ceil((bytes.toDouble()) / RESIZE_STEP_BYTES).toLong() * RESIZE_STEP_BYTES
         }
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
index d85242b..52afef4 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
@@ -50,6 +50,7 @@
 import com.android.internal.annotations.VisibleForTesting
 import com.android.microdroid.test.common.DeviceProperties
 import com.android.system.virtualmachine.flags.Flags
+import com.android.virtualization.terminal.ErrorActivity.Companion.start
 import com.android.virtualization.terminal.VmLauncherService.VmLauncherServiceCallback
 import com.google.android.material.tabs.TabLayout
 import com.google.android.material.tabs.TabLayoutMediator
@@ -368,7 +369,7 @@
                 )
                 .build()
 
-        val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getSize())
+        val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getApparentSize())
 
         val intent =
             VmLauncherService.getIntentForStart(
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsActivity.kt
index a4a0a84..1183b46 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsActivity.kt
@@ -19,6 +19,7 @@
 import androidx.appcompat.app.AppCompatActivity
 import androidx.recyclerview.widget.LinearLayoutManager
 import androidx.recyclerview.widget.RecyclerView
+import com.android.system.virtualmachine.flags.Flags
 import com.google.android.material.appbar.MaterialToolbar
 
 class SettingsActivity : AppCompatActivity() {
@@ -29,27 +30,34 @@
 
         val toolbar: MaterialToolbar = findViewById(R.id.settings_toolbar)
         setSupportActionBar(toolbar)
-        val settingsItems =
-            arrayOf(
+        var settingsItems = mutableListOf<SettingsItem>()
+        if (!Flags.terminalStorageBalloon()) {
+            settingsItems.add(
                 SettingsItem(
                     resources.getString(R.string.settings_disk_resize_title),
                     resources.getString(R.string.settings_disk_resize_sub_title),
                     R.drawable.baseline_storage_24,
                     SettingsItemEnum.DiskResize,
-                ),
-                SettingsItem(
-                    resources.getString(R.string.settings_port_forwarding_title),
-                    resources.getString(R.string.settings_port_forwarding_sub_title),
-                    R.drawable.baseline_call_missed_outgoing_24,
-                    SettingsItemEnum.PortForwarding,
-                ),
-                SettingsItem(
-                    resources.getString(R.string.settings_recovery_title),
-                    resources.getString(R.string.settings_recovery_sub_title),
-                    R.drawable.baseline_settings_backup_restore_24,
-                    SettingsItemEnum.Recovery,
-                ),
+                )
             )
+        }
+        settingsItems.add(
+            SettingsItem(
+                resources.getString(R.string.settings_port_forwarding_title),
+                resources.getString(R.string.settings_port_forwarding_sub_title),
+                R.drawable.baseline_call_missed_outgoing_24,
+                SettingsItemEnum.PortForwarding,
+            )
+        )
+        settingsItems.add(
+            SettingsItem(
+                resources.getString(R.string.settings_recovery_title),
+                resources.getString(R.string.settings_recovery_sub_title),
+                R.drawable.baseline_settings_backup_restore_24,
+                SettingsItemEnum.Recovery,
+            )
+        )
+
         val settingsListItemAdapter = SettingsItemAdapter(settingsItems)
 
         val recyclerView: RecyclerView = findViewById(R.id.settings_list_recycler_view)
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
index af1ae95..da07b19 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
@@ -33,6 +33,7 @@
 import androidx.core.view.isVisible
 import com.android.virtualization.terminal.VmLauncherService.VmLauncherServiceCallback
 import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.google.android.material.snackbar.Snackbar
 import java.util.Locale
 import java.util.regex.Pattern
 
@@ -46,6 +47,7 @@
     private lateinit var cancelButton: View
     private lateinit var resizeButton: View
     private lateinit var diskSizeText: TextView
+    private lateinit var diskMaxSizeText: TextView
     private lateinit var diskSizeSlider: SeekBar
 
     private fun bytesToMb(bytes: Long): Long {
@@ -56,6 +58,13 @@
         return bytes shl 20
     }
 
+    private fun getAvailableSizeMb(): Long {
+        val usableSpaceMb =
+            bytesToMb(Environment.getDataDirectory().getUsableSpace()) and
+                (diskSizeStepMb - 1).inv()
+        return diskSizeMb + usableSpaceMb
+    }
+
     private fun mbToProgress(bytes: Long): Int {
         return (bytes / diskSizeStepMb).toInt()
     }
@@ -71,15 +80,12 @@
         diskSizeStepMb = 1L shl resources.getInteger(R.integer.disk_size_round_up_step_size_in_mb)
 
         val image = InstalledImage.getDefault(this)
-        diskSizeMb = bytesToMb(image.getSize())
+        diskSizeMb = bytesToMb(image.getApparentSize())
         val minDiskSizeMb = bytesToMb(image.getSmallestSizePossible()).coerceAtMost(diskSizeMb)
-        val usableSpaceMb =
-            bytesToMb(Environment.getDataDirectory().getUsableSpace()) and
-                (diskSizeStepMb - 1).inv()
-        val maxDiskSizeMb = defaultMaxDiskSizeMb.coerceAtMost(diskSizeMb + usableSpaceMb)
+        val maxDiskSizeMb = defaultMaxDiskSizeMb.coerceAtMost(getAvailableSizeMb())
 
         diskSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_assigned)!!
-        val diskMaxSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_max)
+        diskMaxSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_max)
         diskMaxSizeText.text =
             getString(
                 R.string.settings_disk_resize_resize_gb_max_format,
@@ -138,7 +144,22 @@
     }
 
     private fun resize() {
-        diskSizeMb = progressToMb(diskSizeSlider.progress)
+        val desiredDiskSizeMb = progressToMb(diskSizeSlider.progress)
+        val availableSizeMb = getAvailableSizeMb()
+        if (availableSizeMb < desiredDiskSizeMb) {
+            Snackbar.make(
+                    findViewById(android.R.id.content),
+                    R.string.settings_disk_resize_not_enough_space_message,
+                    Snackbar.LENGTH_SHORT,
+                )
+                .show()
+            diskSizeSlider.max = mbToProgress(availableSizeMb)
+            updateMaxSizeText(availableSizeMb)
+            cancel()
+            return
+        }
+
+        diskSizeMb = desiredDiskSizeMb
         buttons.isVisible = false
 
         // Note: we first stop the VM, and wait for it to fully stop. Then we (re) start the Main
@@ -186,6 +207,14 @@
             )
     }
 
+    fun updateMaxSizeText(sizeMb: Long) {
+        diskMaxSizeText.text =
+            getString(
+                R.string.settings_disk_resize_resize_gb_max_format,
+                localizedFileSize(sizeMb, /* isShort= */ true),
+            )
+    }
+
     fun localizedFileSize(sizeMb: Long, isShort: Boolean): String {
         val sizeGb = sizeMb / (1 shl 10).toFloat()
         val measure = Measure(sizeGb, MeasureUnit.GIGABYTE)
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
index 132d749..aa0c3f5 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
@@ -24,7 +24,7 @@
 import androidx.recyclerview.widget.RecyclerView
 import com.google.android.material.card.MaterialCardView
 
-class SettingsItemAdapter(private val dataSet: Array<SettingsItem>) :
+class SettingsItemAdapter(private val dataSet: List<SettingsItem>) :
     RecyclerView.Adapter<SettingsItemAdapter.ViewHolder>() {
 
     class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
index 7562779..2653ba9 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
@@ -15,16 +15,96 @@
  */
 package com.android.virtualization.terminal
 
+import android.content.ComponentName
 import android.content.Context
+import android.content.Intent
 import androidx.startup.Initializer
+import androidx.window.embedding.ActivityFilter
+import androidx.window.embedding.EmbeddingAspectRatio
 import androidx.window.embedding.RuleController
+import androidx.window.embedding.SplitAttributes
+import androidx.window.embedding.SplitPairFilter
+import androidx.window.embedding.SplitPairRule
+import androidx.window.embedding.SplitPlaceholderRule
+import androidx.window.embedding.SplitRule
+import com.android.system.virtualmachine.flags.Flags
 
 class SplitInitializer : Initializer<RuleController> {
 
     override fun create(context: Context): RuleController {
-        return RuleController.getInstance(context).apply {
-            setRules(RuleController.parseRules(context, R.xml.main_split_config))
+        val filters =
+            mutableSetOf(
+                SplitPairFilter(
+                    ComponentName(context, SettingsActivity::class.java),
+                    ComponentName(context, SettingsPortForwardingActivity::class.java),
+                    null,
+                )
+            )
+
+        if (Flags.terminalStorageBalloon()) {
+            filters.add(
+                SplitPairFilter(
+                    ComponentName(context, SettingsActivity::class.java),
+                    ComponentName(context, SettingsDiskResizeActivity::class.java),
+                    null,
+                )
+            )
         }
+
+        filters.add(
+            SplitPairFilter(
+                ComponentName(context, SettingsActivity::class.java),
+                ComponentName(context, SettingsRecoveryActivity::class.java),
+                null,
+            )
+        )
+        val splitPairRules =
+            SplitPairRule.Builder(filters)
+                .setClearTop(true)
+                .setFinishPrimaryWithSecondary(SplitRule.FinishBehavior.ADJACENT)
+                .setFinishSecondaryWithPrimary(SplitRule.FinishBehavior.ALWAYS)
+                .setDefaultSplitAttributes(
+                    SplitAttributes.Builder()
+                        .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+                        .setSplitType(
+                            SplitAttributes.SplitType.ratio(
+                                context.resources.getFloat(R.dimen.activity_split_ratio)
+                            )
+                        )
+                        .build()
+                )
+                .setMaxAspectRatioInPortrait(EmbeddingAspectRatio.ALWAYS_ALLOW)
+                .setMinWidthDp(context.resources.getInteger(R.integer.split_min_width))
+                .build()
+
+        val placeholderRule =
+            SplitPlaceholderRule.Builder(
+                    setOf(
+                        ActivityFilter(ComponentName(context, SettingsActivity::class.java), null)
+                    ),
+                    Intent(context, SettingsDiskResizeActivity::class.java),
+                )
+                .setFinishPrimaryWithPlaceholder(SplitRule.FinishBehavior.ADJACENT)
+                .setDefaultSplitAttributes(
+                    SplitAttributes.Builder()
+                        .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+                        .setSplitType(
+                            SplitAttributes.SplitType.ratio(
+                                context.resources.getFloat(R.dimen.activity_split_ratio)
+                            )
+                        )
+                        .build()
+                )
+                .setMaxAspectRatioInPortrait(EmbeddingAspectRatio.ALWAYS_ALLOW)
+                .setMinWidthDp(context.resources.getInteger(R.integer.split_min_width))
+                .setSticky(false)
+                .build()
+
+        val ruleController = RuleController.getInstance(context)
+        ruleController.addRule(splitPairRules)
+        ruleController.addRule(placeholderRule)
+
+        return ruleController
     }
 
     override fun dependencies(): List<Class<out Initializer<*>>> {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
index f426ce6..84168e5 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
@@ -41,6 +41,7 @@
 import android.widget.Toast
 import androidx.annotation.WorkerThread
 import com.android.system.virtualmachine.flags.Flags
+import com.android.virtualization.terminal.InstalledImage.Companion.roundUp
 import com.android.virtualization.terminal.MainActivity.Companion.PREFIX
 import com.android.virtualization.terminal.MainActivity.Companion.TAG
 import io.grpc.Grpc
@@ -120,7 +121,7 @@
                 // Note: this doesn't always do the resizing. If the current image size is the same
                 // as the requested size which is rounded up to the page alignment, resizing is not
                 // done.
-                val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getSize())
+                val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getApparentSize())
 
                 mainWorkerThread.submit({
                     doStart(notification, displayInfo, diskSize, resultReceiver)
@@ -140,16 +141,18 @@
         return START_NOT_STICKY
     }
 
-    private fun truncateDiskIfNecessary(image: InstalledImage) {
-        val curSize = image.getSize()
-        val physicalSize = image.getPhysicalSize()
-
-        // Change the rootfs disk's apparent size to GUEST_SPARSE_DISK_SIZE_PERCENTAGE of the total
-        // disk size.
-        // Note that the physical size is not changed.
+    private fun calculateSparseDiskSize(): Long {
+        // With storage ballooning enabled, we create a sparse file with 95% of the total size.
         val statFs = StatFs(filesDir.absolutePath)
         val hostSize = statFs.totalBytes
-        val expectedSize = hostSize * GUEST_SPARSE_DISK_SIZE_PERCENTAGE / 100
+        return roundUp(hostSize * GUEST_SPARSE_DISK_SIZE_PERCENTAGE / 100)
+    }
+
+    private fun truncateDiskIfNecessary(image: InstalledImage) {
+        val curSize = image.getApparentSize()
+        val physicalSize = image.getPhysicalSize()
+
+        val expectedSize = calculateSparseDiskSize()
         Log.d(
             TAG,
             "rootfs apparent size=$curSize, physical size=$physicalSize, expectedSize=$expectedSize",
@@ -164,6 +167,38 @@
         }
     }
 
+    // Convert the rootfs disk to a non-sparse file.
+    private fun convertToNonSparseDiskIfNecessary(image: InstalledImage) {
+        try {
+            val curApparentSize = image.getApparentSize()
+            val curPhysicalSize = image.getPhysicalSize()
+            Log.d(TAG, "Current disk size: apparent=$curApparentSize, physical=$curPhysicalSize")
+
+            // If storage ballooning was enabled via Flags.terminalStorageBalloon() before but it's
+            // now disabled, the disk is still a sparse file whose apparent size is too large.
+            // We need to shrink it to the minimum size.
+            //
+            // The disk file is considered sparse if its apparent disk size matches the expected
+            // sparse disk size.
+            // In addition, we consider it sparse if the physical size is clearly smaller than its
+            // apparent size. This additional condition is a fallback for cases
+            // where the logic of calculating the expected sparse disk size since the disk is
+            // created.
+            if (
+                curApparentSize == calculateSparseDiskSize() ||
+                    curPhysicalSize <
+                        curApparentSize * EXPECTED_PHYSICAL_SIZE_PERCENTAGE_FOR_NON_SPARSE / 100
+            ) {
+                Log.d(TAG, "A sparse disk is detected. Shrink it to the minimum size.")
+                val newSize = image.shrinkToMinimumSize()
+                Log.d(TAG, "Shrink the disk image: $curApparentSize -> $newSize")
+            }
+        } catch (e: IOException) {
+            throw RuntimeException("Failed to shrink rootfs disk", e)
+            return
+        }
+    }
+
     @WorkerThread
     private fun doStart(
         notification: Notification,
@@ -180,6 +215,10 @@
             // When storage ballooning flag is enabled, convert rootfs disk into a sparse file.
             truncateDiskIfNecessary(image)
         } else {
+            // Convert rootfs disk into a sparse file if storage ballooning flag had been enabled
+            // and then disabled.
+            convertToNonSparseDiskIfNecessary(image)
+
             // Note: this doesn't always do the resizing. If the current image size is the same as
             // the requested size which is rounded up to the page alignment, resizing is not done.
             image.resize(diskSize)
@@ -424,15 +463,32 @@
 
     @WorkerThread
     private fun doShutdown(resultReceiver: ResultReceiver?) {
-        stopForeground(STOP_FOREGROUND_REMOVE)
+        runner?.exitStatus?.thenAcceptAsync { success: Boolean ->
+            resultReceiver?.send(if (success) RESULT_STOP else RESULT_ERROR, null)
+            stopSelf()
+        }
         if (debianService != null && debianService!!.shutdownDebian()) {
             // During shutdown, change the notification content to indicate that it's closing
             val notification = createNotificationForTerminalClose()
             getSystemService<NotificationManager?>(NotificationManager::class.java)
                 .notify(this.hashCode(), notification)
-            runner?.exitStatus?.thenAcceptAsync { success: Boolean ->
-                resultReceiver?.send(if (success) RESULT_STOP else RESULT_ERROR, null)
-                stopSelf()
+
+            runner?.also { r ->
+                // For the case that shutdown from the guest agent fails.
+                // When timeout is set, the original CompletableFuture's every `thenAcceptAsync` is
+                // canceled as well. So add empty `thenAcceptAsync` to avoid interference.
+                r.exitStatus
+                    .thenAcceptAsync {}
+                    .orTimeout(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)
+                    .exceptionally {
+                        Log.e(
+                            TAG,
+                            "Stop the service directly because the VM instance isn't stopped with " +
+                                "graceful shutdown",
+                        )
+                        r.vm.stop()
+                        null
+                    }
             }
             runner = null
         } else {
@@ -459,6 +515,7 @@
         stopDebianServer()
         bgThreads.shutdownNow()
         mainWorkerThread.shutdown()
+        stopForeground(STOP_FOREGROUND_REMOVE)
         super.onDestroy()
     }
 
@@ -478,7 +535,10 @@
         private const val KEY_TERMINAL_IPADDRESS = "address"
         private const val KEY_TERMINAL_PORT = "port"
 
+        private const val SHUTDOWN_TIMEOUT_SECONDS = 3L
+
         private const val GUEST_SPARSE_DISK_SIZE_PERCENTAGE = 95
+        private const val EXPECTED_PHYSICAL_SIZE_PERCENTAGE_FOR_NON_SPARSE = 90
 
         private val VM_BOOT_TIMEOUT_SECONDS: Int =
             {
diff --git a/android/TerminalApp/res/values/config.xml b/android/TerminalApp/res/values/config.xml
index 7f0b5e6..a2c9183 100644
--- a/android/TerminalApp/res/values/config.xml
+++ b/android/TerminalApp/res/values/config.xml
@@ -16,4 +16,5 @@
 
 <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <bool name="terminal_portrait_only">true</bool>
+    <item name="activity_split_ratio" format="float" type="dimen">0.3</item>
 </resources>
diff --git a/android/TerminalApp/res/values/dimens.xml b/android/TerminalApp/res/values/dimens.xml
deleted file mode 100644
index e00ef7c..0000000
--- a/android/TerminalApp/res/values/dimens.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--  Copyright 2024 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
- -->
-
-<resources>
-    <dimen name="activity_split_ratio">0.3</dimen>
-</resources>
\ No newline at end of file
diff --git a/android/TerminalApp/res/values/strings.xml b/android/TerminalApp/res/values/strings.xml
index a6d461e..273032e 100644
--- a/android/TerminalApp/res/values/strings.xml
+++ b/android/TerminalApp/res/values/strings.xml
@@ -75,6 +75,8 @@
     <string name="settings_disk_resize_resize_gb_assigned_format"><xliff:g id="assigned_size" example="10GB">\u200E%1$s\u200E</xliff:g> assigned</string>
     <!-- Settings menu option description format of the maximum resizable disk size. [CHAR LIMIT=none] -->
     <string name="settings_disk_resize_resize_gb_max_format"><xliff:g id="max_size" example="256GB">\u200E%1$s\u200E</xliff:g> max</string>
+    <!-- Snackbar message for showing not enough space error. [CHAR LIMIT=none] -->
+    <string name="settings_disk_resize_not_enough_space_message">Not enough space on the device to resize disk</string>
     <!-- Settings menu button to cancel disk resize. [CHAR LIMIT=16] -->
     <string name="settings_disk_resize_resize_cancel">Cancel</string>
     <!-- Settings menu button to apply change Terminal app. This will launch a confirmation dialog [CHAR LIMIT=16] -->
diff --git a/android/TerminalApp/res/xml/main_split_config.xml b/android/TerminalApp/res/xml/main_split_config.xml
deleted file mode 100644
index bd0271b..0000000
--- a/android/TerminalApp/res/xml/main_split_config.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--  Copyright 2024 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
- -->
-
-<resources xmlns:window="http://schemas.android.com/apk/res-auto">
-
-    <!-- Define a split for the named activities. -->
-    <SplitPairRule
-        window:clearTop="true"
-        window:finishPrimaryWithSecondary="adjacent"
-        window:finishSecondaryWithPrimary="always"
-        window:splitLayoutDirection="locale"
-        window:splitMaxAspectRatioInPortrait="alwaysAllow"
-        window:splitMinWidthDp="@integer/split_min_width"
-        window:splitRatio="@dimen/activity_split_ratio">
-        <SplitPairFilter
-            window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
-            window:secondaryActivityName="com.android.virtualization.terminal.SettingsDiskResizeActivity" />
-        <SplitPairFilter
-            window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
-            window:secondaryActivityName="com.android.virtualization.terminal.SettingsPortForwardingActivity" />
-        <SplitPairFilter
-            window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
-            window:secondaryActivityName="com.android.virtualization.terminal.SettingsRecoveryActivity" />
-    </SplitPairRule>
-
-    <SplitPlaceholderRule
-        window:placeholderActivityName="com.android.virtualization.terminal.SettingsDiskResizeActivity"
-        window:finishPrimaryWithPlaceholder="adjacent"
-        window:splitLayoutDirection="locale"
-        window:splitMaxAspectRatioInPortrait="alwaysAllow"
-        window:splitMinWidthDp="@integer/split_min_width"
-        window:splitRatio="@dimen/activity_split_ratio"
-        window:stickyPlaceholder="false">
-        <ActivityFilter
-            window:activityName="com.android.virtualization.terminal.SettingsActivity"/>
-    </SplitPlaceholderRule>
-</resources>
\ No newline at end of file
diff --git a/android/virtmgr/src/aidl.rs b/android/virtmgr/src/aidl.rs
index d7f68b8..190acc7 100644
--- a/android/virtmgr/src/aidl.rs
+++ b/android/virtmgr/src/aidl.rs
@@ -641,6 +641,24 @@
 
         let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
 
+        let instance_id = extract_instance_id(config);
+        // Require vendor instance IDs to start with a specific prefix so that they don't conflict
+        // with system instance IDs.
+        //
+        // We should also make sure that non-vendor VMs do not use the vendor prefix, but there are
+        // already system VMs in the wild that may have randomly generated IDs with the prefix, so,
+        // for now, we only check in one direction.
+        const INSTANCE_ID_VENDOR_PREFIX: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF];
+        if matches!(calling_partition, CallingPartition::Vendor | CallingPartition::Odm)
+            && !instance_id.starts_with(INSTANCE_ID_VENDOR_PREFIX)
+        {
+            return Err(anyhow!(
+                "vendor initiated VMs must have instance IDs starting with 0xFFFFFFFF, got {}",
+                hex::encode(instance_id)
+            ))
+            .or_service_specific_exception(-1);
+        }
+
         check_config_features(config)?;
 
         if cfg!(early) {
@@ -668,7 +686,6 @@
             check_gdb_allowed(config)?;
         }
 
-        let instance_id = extract_instance_id(config);
         let mut device_tree_overlays = vec![];
         if let Some(dt_overlay) =
             maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
diff --git a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
index 5193e21..7db5135 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
@@ -23,7 +23,11 @@
     /** Name of VM */
     String name;
 
-    /** Id of the VM instance */
+    /**
+     * Id of the VM instance
+     *
+     * See AVirtualMachineRawConfig_setInstanceId for details.
+     */
     byte[64] instanceId;
 
     /** Main APK */
diff --git a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
index c5fe982..1e4fe03 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
@@ -31,7 +31,11 @@
     /** Name of VM */
     String name;
 
-    /** Id of the VM instance */
+    /**
+     * Id of the VM instance
+     *
+     * See AVirtualMachineRawConfig_setInstanceId for details.
+     */
     byte[64] instanceId;
 
     /** The kernel image, if any. */
diff --git a/android/virtualizationservice/src/aidl.rs b/android/virtualizationservice/src/aidl.rs
index 1646117..e26cd4f 100644
--- a/android/virtualizationservice/src/aidl.rs
+++ b/android/virtualizationservice/src/aidl.rs
@@ -489,6 +489,9 @@
         id.try_fill(&mut rand::thread_rng())
             .context("Failed to allocate instance_id")
             .or_service_specific_exception(-1)?;
+        // Randomly allocated IDs always start with all 7s to avoid colliding with statically
+        // assigned IDs.
+        id[..4].fill(0x77);
         let uid = get_calling_uid();
         info!("Allocated a VM's instance_id: {:?}..., for uid: {:?}", &hex::encode(id)[..8], uid);
         self.try_updating_sk_state(&id);
diff --git a/build/apex/Android.bp b/build/apex/Android.bp
index 8934de0..f0eba7f 100644
--- a/build/apex/Android.bp
+++ b/build/apex/Android.bp
@@ -56,6 +56,7 @@
         "libvirtualizationservice_jni",
         "libvirtualmachine_jni",
     ],
+    native_shared_libs: ["libavf"],
     // TODO(b/295593640) Unfortunately these are added to the apex even though they are unused.
     // Once the build system is fixed, remove this.
     unwanted_transitive_deps: [
@@ -108,7 +109,6 @@
                 "rialto_bin",
                 "android_bootloader_crosvm_aarch64",
             ],
-            native_shared_libs: ["libavf"],
         },
         x86_64: {
             binaries: [
@@ -129,7 +129,6 @@
             prebuilts: [
                 "android_bootloader_crosvm_x86_64",
             ],
-            native_shared_libs: ["libavf"],
         },
     },
     binaries: [
diff --git a/guest/pvmfw/README.md b/guest/pvmfw/README.md
index 40a6328..0288741 100644
--- a/guest/pvmfw/README.md
+++ b/guest/pvmfw/README.md
@@ -1,19 +1,30 @@
 # Protected Virtual Machine Firmware
 
+## Protected VM (_"pVM"_)
+
 In the context of the [Android Virtualization Framework][AVF], a hypervisor
 (_e.g._ [pKVM]) enforces full memory isolation between its virtual machines
-(VMs) and the host.  As a result, the host is only allowed to access memory that
-has been explicitly shared back by a VM. Such _protected VMs_ (“pVMs”) are
-therefore able to manipulate secrets without being at risk of an attacker
-stealing them by compromising the Android host.
+(VMs) and the host. As a result, such VMs are given strong guarantees regarding
+their confidentiality and integrity.
 
-As pVMs are started dynamically by a _virtual machine manager_ (“VMM”) running
-as a host process and as pVMs must not trust the host (see [_Why
-AVF?_][why-avf]), the virtual machine it configures can't be trusted either.
-Furthermore, even though the isolation mentioned above allows pVMs to protect
-their secrets from the host, it does not help with provisioning them during
-boot. In particular, the threat model would prohibit the host from ever having
-access to those secrets, preventing the VMM from passing them to the pVM.
+A _protected VMs_ (“pVMs”) is a VM running in the non-secure or realm world,
+started dynamically by a _virtual machine manager_ (“VMM”) running as a process
+of the untrusted Android host (see [_Why AVF?_][why-avf]) and which is isolated
+from the host OS so that access to its memory is restricted, even in the event
+of a compromised Android host. pVMs support rich environments, including
+Linux-based distributions.
+
+The pVM concept is not Google-exclusive. Partner-defined VMs (SoC/OEM) meeting
+isolation/memory access restrictions are also pVMs.
+
+## Protected VM Root-of-Trust: pvmfw
+
+As pVMs are managed by a VMM running on the untrusted host, the virtual machine
+it configures can't be trusted either. Furthermore, even though the isolation
+mentioned above allows pVMs to protect their secrets from the host, it does not
+help with provisioning them during boot. In particular, the threat model would
+prohibit the host from ever having access to those secrets, preventing the VMM
+from passing them to the pVM.
 
 To address these concerns the hypervisor securely loads the pVM firmware
 (“pvmfw”) in the pVM from a protected memory region (this prevents the host or
diff --git a/guest/pvmfw/avb/tests/api_test.rs b/guest/pvmfw/avb/tests/api_test.rs
index b3899d9..b8ec0bf 100644
--- a/guest/pvmfw/avb/tests/api_test.rs
+++ b/guest/pvmfw/avb/tests/api_test.rs
@@ -71,6 +71,7 @@
         expected_rollback_index,
         vec![Capability::TrustySecurityVm],
         None,
+        Some("trusty_test_vm".to_owned()),
     )
 }
 
diff --git a/guest/pvmfw/avb/tests/utils.rs b/guest/pvmfw/avb/tests/utils.rs
index 227daa2..38541c5 100644
--- a/guest/pvmfw/avb/tests/utils.rs
+++ b/guest/pvmfw/avb/tests/utils.rs
@@ -148,6 +148,7 @@
     expected_rollback_index: u64,
     capabilities: Vec<Capability>,
     page_size: Option<usize>,
+    expected_name: Option<String>,
 ) -> Result<()> {
     let public_key = load_trusted_public_key()?;
     let verified_boot_data = verify_payload(
@@ -168,7 +169,7 @@
         capabilities,
         rollback_index: expected_rollback_index,
         page_size,
-        name: None,
+        name: expected_name,
     };
     assert_eq!(expected_boot_data, verified_boot_data);
 
diff --git a/guest/pvmfw/src/arch/aarch64/exceptions.rs b/guest/pvmfw/src/arch/aarch64/exceptions.rs
index 4c867fb..c8c0156 100644
--- a/guest/pvmfw/src/arch/aarch64/exceptions.rs
+++ b/guest/pvmfw/src/arch/aarch64/exceptions.rs
@@ -18,9 +18,7 @@
     arch::aarch64::exceptions::{
         handle_permission_fault, handle_translation_fault, ArmException, Esr, HandleExceptionError,
     },
-    eprintln, logger,
-    power::reboot,
-    read_sysreg,
+    logger, read_sysreg,
 };
 
 fn handle_exception(exception: &ArmException) -> Result<(), HandleExceptionError> {
@@ -41,55 +39,44 @@
 
     let exception = ArmException::from_el1_regs();
     if let Err(e) = handle_exception(&exception) {
-        exception.print("sync_exception_current", e, elr);
-        reboot()
+        exception.print_and_reboot("sync_exception_current", e, elr);
     }
 }
 
 #[no_mangle]
 extern "C" fn irq_current(_elr: u64, _spsr: u64) {
-    eprintln!("irq_current");
-    reboot();
+    panic!("irq_current");
 }
 
 #[no_mangle]
 extern "C" fn fiq_current(_elr: u64, _spsr: u64) {
-    eprintln!("fiq_current");
-    reboot();
+    panic!("fiq_current");
 }
 
 #[no_mangle]
 extern "C" fn serr_current(_elr: u64, _spsr: u64) {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("serr_current");
-    eprintln!("esr={esr:#08x}");
-    reboot();
+    panic!("serr_current, esr={esr:#08x}");
 }
 
 #[no_mangle]
 extern "C" fn sync_lower(_elr: u64, _spsr: u64) {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("sync_lower");
-    eprintln!("esr={esr:#08x}");
-    reboot();
+    panic!("sync_lower, esr={esr:#08x}");
 }
 
 #[no_mangle]
 extern "C" fn irq_lower(_elr: u64, _spsr: u64) {
-    eprintln!("irq_lower");
-    reboot();
+    panic!("irq_lower");
 }
 
 #[no_mangle]
 extern "C" fn fiq_lower(_elr: u64, _spsr: u64) {
-    eprintln!("fiq_lower");
-    reboot();
+    panic!("fiq_lower");
 }
 
 #[no_mangle]
 extern "C" fn serr_lower(_elr: u64, _spsr: u64) {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("serr_lower");
-    eprintln!("esr={esr:#08x}");
-    reboot();
+    panic!("serr_lower, esr={esr:#08x}");
 }
diff --git a/guest/pvmfw/src/entry.rs b/guest/pvmfw/src/entry.rs
index 3714173..46b1971 100644
--- a/guest/pvmfw/src/entry.rs
+++ b/guest/pvmfw/src/entry.rs
@@ -98,7 +98,7 @@
     };
 
     const REBOOT_REASON_CONSOLE: usize = 1;
-    console_writeln!(REBOOT_REASON_CONSOLE, "{}", reboot_reason.as_avf_reboot_string());
+    console_writeln!(REBOOT_REASON_CONSOLE, "{}", reboot_reason.as_avf_reboot_string()).unwrap();
     reboot()
 
     // if we reach this point and return, vmbase::entry::rust_entry() will call power::shutdown().
diff --git a/guest/rialto/src/exceptions.rs b/guest/rialto/src/exceptions.rs
index 467a3a6..c8c0156 100644
--- a/guest/rialto/src/exceptions.rs
+++ b/guest/rialto/src/exceptions.rs
@@ -18,9 +18,7 @@
     arch::aarch64::exceptions::{
         handle_permission_fault, handle_translation_fault, ArmException, Esr, HandleExceptionError,
     },
-    eprintln, logger,
-    power::reboot,
-    read_sysreg,
+    logger, read_sysreg,
 };
 
 fn handle_exception(exception: &ArmException) -> Result<(), HandleExceptionError> {
@@ -41,58 +39,44 @@
 
     let exception = ArmException::from_el1_regs();
     if let Err(e) = handle_exception(&exception) {
-        exception.print("sync_exception_current", e, elr);
-        reboot()
+        exception.print_and_reboot("sync_exception_current", e, elr);
     }
 }
 
 #[no_mangle]
-extern "C" fn irq_current() {
-    eprintln!("irq_current");
-    reboot();
+extern "C" fn irq_current(_elr: u64, _spsr: u64) {
+    panic!("irq_current");
 }
 
 #[no_mangle]
-extern "C" fn fiq_current() {
-    eprintln!("fiq_current");
-    reboot();
+extern "C" fn fiq_current(_elr: u64, _spsr: u64) {
+    panic!("fiq_current");
 }
 
 #[no_mangle]
-extern "C" fn serr_current() {
-    eprintln!("serr_current");
-    print_esr();
-    reboot();
-}
-
-#[no_mangle]
-extern "C" fn sync_lower() {
-    eprintln!("sync_lower");
-    print_esr();
-    reboot();
-}
-
-#[no_mangle]
-extern "C" fn irq_lower() {
-    eprintln!("irq_lower");
-    reboot();
-}
-
-#[no_mangle]
-extern "C" fn fiq_lower() {
-    eprintln!("fiq_lower");
-    reboot();
-}
-
-#[no_mangle]
-extern "C" fn serr_lower() {
-    eprintln!("serr_lower");
-    print_esr();
-    reboot();
-}
-
-#[inline]
-fn print_esr() {
+extern "C" fn serr_current(_elr: u64, _spsr: u64) {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("esr={:#08x}", esr);
+    panic!("serr_current, esr={esr:#08x}");
+}
+
+#[no_mangle]
+extern "C" fn sync_lower(_elr: u64, _spsr: u64) {
+    let esr = read_sysreg!("esr_el1");
+    panic!("sync_lower, esr={esr:#08x}");
+}
+
+#[no_mangle]
+extern "C" fn irq_lower(_elr: u64, _spsr: u64) {
+    panic!("irq_lower");
+}
+
+#[no_mangle]
+extern "C" fn fiq_lower(_elr: u64, _spsr: u64) {
+    panic!("fiq_lower");
+}
+
+#[no_mangle]
+extern "C" fn serr_lower(_elr: u64, _spsr: u64) {
+    let esr = read_sysreg!("esr_el1");
+    panic!("serr_lower, esr={esr:#08x}");
 }
diff --git a/guest/trusty/security_vm/security_vm.mk b/guest/trusty/security_vm/security_vm.mk
index 89c9cdc..8717399 100644
--- a/guest/trusty/security_vm/security_vm.mk
+++ b/guest/trusty/security_vm/security_vm.mk
@@ -14,10 +14,14 @@
 
 
 ifeq ($(findstring enabled, $(TRUSTY_SYSTEM_VM)),enabled)
-PRODUCT_PACKAGES += \
-	trusty_security_vm.elf \
+
+# This is the default set of packages to load the trusty system vm.
+# It can be overridden by device-specific configuration.
+TRUSTY_SYSTEM_VM_PRODUCT_PACKAGES ?= trusty_security_vm.elf \
 	trusty_security_vm_launcher \
 	trusty_security_vm_launcher.rc \
 	early_vms.xml \
 
+PRODUCT_PACKAGES += $(TRUSTY_SYSTEM_VM_PRODUCT_PACKAGES)
+
 endif
diff --git a/guest/trusty/security_vm/vm/Android.bp b/guest/trusty/security_vm/vm/Android.bp
index 6fa0c32..9928b56 100644
--- a/guest/trusty/security_vm/vm/Android.bp
+++ b/guest/trusty/security_vm/vm/Android.bp
@@ -123,6 +123,10 @@
             name: "com.android.virt.cap",
             value: "trusty_security_vm",
         },
+        {
+            name: "com.android.virt.name",
+            value: "trusty_security_vm",
+        },
     ],
     src: select(soong_config_variable("trusty_system_vm", "enabled"), {
         true: ":trusty_security_vm_unsigned",
diff --git a/guest/trusty/test_vm/vm/Android.bp b/guest/trusty/test_vm/vm/Android.bp
index f978c92..b919599 100644
--- a/guest/trusty/test_vm/vm/Android.bp
+++ b/guest/trusty/test_vm/vm/Android.bp
@@ -101,6 +101,10 @@
             name: "com.android.virt.cap",
             value: "trusty_security_vm",
         },
+        {
+            name: "com.android.virt.name",
+            value: "trusty_test_vm",
+        },
     ],
     src: ":trusty_test_vm_unsigned",
     enabled: false,
diff --git a/guest/trusty/test_vm_os/vm/Android.bp b/guest/trusty/test_vm_os/vm/Android.bp
index 2e81828..0e4116c 100644
--- a/guest/trusty/test_vm_os/vm/Android.bp
+++ b/guest/trusty/test_vm_os/vm/Android.bp
@@ -100,6 +100,10 @@
             name: "com.android.virt.cap",
             value: "trusty_security_vm",
         },
+        {
+            name: "com.android.virt.name",
+            value: "trusty_test_vm_os",
+        },
     ],
     src: ":trusty_test_vm_os_unsigned",
     enabled: false,
diff --git a/guest/vmbase_example/src/exceptions.rs b/guest/vmbase_example/src/exceptions.rs
index 5d7768a..0eb415c 100644
--- a/guest/vmbase_example/src/exceptions.rs
+++ b/guest/vmbase_example/src/exceptions.rs
@@ -14,62 +14,51 @@
 
 //! Exception handlers.
 
-use vmbase::{eprintln, power::reboot, read_sysreg};
+use vmbase::{arch::aarch64::exceptions::ArmException, read_sysreg};
 
 #[no_mangle]
-extern "C" fn sync_exception_current(_elr: u64, _spsr: u64) {
-    eprintln!("sync_exception_current");
-    print_esr();
-    reboot();
+extern "C" fn sync_exception_current(elr: u64, _spsr: u64) {
+    ArmException::from_el1_regs().print_and_reboot(
+        "sync_exception_current",
+        "Unexpected synchronous exception",
+        elr,
+    );
 }
 
 #[no_mangle]
 extern "C" fn irq_current(_elr: u64, _spsr: u64) {
-    eprintln!("irq_current");
-    reboot();
+    panic!("irq_current");
 }
 
 #[no_mangle]
 extern "C" fn fiq_current(_elr: u64, _spsr: u64) {
-    eprintln!("fiq_current");
-    reboot();
+    panic!("fiq_current");
 }
 
 #[no_mangle]
 extern "C" fn serr_current(_elr: u64, _spsr: u64) {
-    eprintln!("serr_current");
-    print_esr();
-    reboot();
+    let esr = read_sysreg!("esr_el1");
+    panic!("serr_current, esr={:#08x}", esr);
 }
 
 #[no_mangle]
 extern "C" fn sync_lower(_elr: u64, _spsr: u64) {
-    eprintln!("sync_lower");
-    print_esr();
-    reboot();
+    let esr = read_sysreg!("esr_el1");
+    panic!("sync_lower, esr={:#08x}", esr);
 }
 
 #[no_mangle]
 extern "C" fn irq_lower(_elr: u64, _spsr: u64) {
-    eprintln!("irq_lower");
-    reboot();
+    panic!("irq_lower");
 }
 
 #[no_mangle]
 extern "C" fn fiq_lower(_elr: u64, _spsr: u64) {
-    eprintln!("fiq_lower");
-    reboot();
+    panic!("fiq_lower");
 }
 
 #[no_mangle]
 extern "C" fn serr_lower(_elr: u64, _spsr: u64) {
-    eprintln!("serr_lower");
-    print_esr();
-    reboot();
-}
-
-#[inline]
-fn print_esr() {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("esr={:#08x}", esr);
+    panic!("serr_lower, esr={:#08x}", esr);
 }
diff --git a/libs/dice/open_dice/Android.bp b/libs/dice/open_dice/Android.bp
index 739f245..9e4544d 100644
--- a/libs/dice/open_dice/Android.bp
+++ b/libs/dice/open_dice/Android.bp
@@ -61,6 +61,7 @@
         "//apex_available:platform",
         "com.android.virt",
     ],
+    min_sdk_version: "35",
 }
 
 rust_library {
@@ -88,6 +89,7 @@
         "//apex_available:platform",
         "com.android.virt",
     ],
+    min_sdk_version: "35",
 }
 
 rust_defaults {
@@ -210,6 +212,7 @@
     ],
     whole_static_libs: ["libopen_dice_cbor"],
     shared_libs: ["libcrypto"],
+    min_sdk_version: "35",
 }
 
 rust_bindgen {
@@ -224,6 +227,7 @@
     ],
     whole_static_libs: ["libopen_dice_cbor_multialg"],
     shared_libs: ["libcrypto"],
+    min_sdk_version: "35",
 }
 
 rust_bindgen {
@@ -281,6 +285,7 @@
         "libopen_dice_cbor_bindgen",
     ],
     whole_static_libs: ["libopen_dice_android"],
+    min_sdk_version: "35",
 }
 
 rust_bindgen {
@@ -293,6 +298,7 @@
         "libopen_dice_cbor_bindgen_multialg",
     ],
     whole_static_libs: ["libopen_dice_android_multialg"],
+    min_sdk_version: "35",
 }
 
 rust_bindgen {
diff --git a/libs/dice/sample_inputs/Android.bp b/libs/dice/sample_inputs/Android.bp
index c1c4566..4010741 100644
--- a/libs/dice/sample_inputs/Android.bp
+++ b/libs/dice/sample_inputs/Android.bp
@@ -80,3 +80,9 @@
     ],
     static_libs: ["libopen_dice_clear_memory"],
 }
+
+dirgroup {
+    name: "trusty_dirgroup_packages_modules_virtualization_libs_dice_sample_inputs",
+    visibility: ["//trusty/vendor/google/aosp/scripts"],
+    dirs: ["."],
+}
diff --git a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
index ad63206..4f58cd6 100644
--- a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
+++ b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
@@ -813,6 +813,10 @@
      */
     @GuardedBy("mLock")
     private void dropVm() {
+        if (mInputEventExecutor != null) {
+            mInputEventExecutor.shutdownNow();
+            mInputEventExecutor = null;
+        }
         if (mMemoryManagementCallbacks != null) {
             mContext.unregisterComponentCallbacks(mMemoryManagementCallbacks);
         }
@@ -1825,9 +1829,6 @@
             try {
                 mVirtualMachine.stop();
                 dropVm();
-                if (mInputEventExecutor != null) {
-                    mInputEventExecutor.shutdownNow();
-                }
             } catch (RemoteException e) {
                 throw e.rethrowAsRuntimeException();
             } catch (ServiceSpecificException e) {
diff --git a/libs/libavf/Android.bp b/libs/libavf/Android.bp
index aceb927..4469af5 100644
--- a/libs/libavf/Android.bp
+++ b/libs/libavf/Android.bp
@@ -40,30 +40,8 @@
     defaults: ["libavf.default"],
 }
 
-soong_config_module_type {
-    name: "virt_cc_defaults",
-    module_type: "cc_defaults",
-    config_namespace: "ANDROID",
-    bool_variables: [
-        "avf_enabled",
-    ],
-    properties: [
-        "apex_available",
-    ],
-}
-
-virt_cc_defaults {
-    name: "libavf_apex_available_defaults",
-    soong_config_variables: {
-        avf_enabled: {
-            apex_available: ["com.android.virt"],
-        },
-    },
-}
-
 cc_library {
     name: "libavf",
-    defaults: ["libavf_apex_available_defaults"],
     llndk: {
         symbol_file: "libavf.map.txt",
         moved_to_apex: true,
@@ -79,4 +57,5 @@
     stubs: {
         symbol_file: "libavf.map.txt",
     },
+    apex_available: ["com.android.virt"],
 }
diff --git a/libs/libavf/include/android/virtualization.h b/libs/libavf/include/android/virtualization.h
index 4bfe47a..e907ac4 100644
--- a/libs/libavf/include/android/virtualization.h
+++ b/libs/libavf/include/android/virtualization.h
@@ -78,6 +78,9 @@
  * The `instanceId` is expected to be re-used for the VM instance with an associated state (secret,
  * encrypted storage) - i.e., rebooting the VM must not change the instanceId.
  *
+ * `instanceId` MUST start with 0xFFFFFFFF if and only if this library is being
+ * called from code in a vendor or odm partition,
+ *
  * \param config a virtual machine config object.
  * \param instanceId a pointer to a 64-byte buffer for the instance ID.
  * \param instanceIdSize the number of bytes in `instanceId`.
diff --git a/libs/libvmbase/README.md b/libs/libvmbase/README.md
index 28d930a..3c05cc3 100644
--- a/libs/libvmbase/README.md
+++ b/libs/libvmbase/README.md
@@ -79,23 +79,16 @@
 use vmbase::power::reboot;
 
 extern "C" fn sync_exception_current() {
-    eprintln!("sync_exception_current");
-
     let mut esr: u64;
     unsafe {
         asm!("mrs {esr}, esr_el1", esr = out(reg) esr);
     }
-    eprintln!("esr={:#08x}", esr);
-
-    reboot();
+    panic!("sync_exception_current, esr={:#08x}", esr);
 }
 ```
 
 The `println!` macro shouldn't be used in exception handlers, because it relies on a global instance
 of the UART driver which might be locked when the exception happens, which would result in deadlock.
-Instead you can use `eprintln!`, which will re-initialize the UART every time to ensure that it can
-be used. This should still be used with care, as it may interfere with whatever the rest of the
-program is doing with the UART.
 
 See [example/src/exceptions.rs](examples/src/exceptions.rs) for a complete example.
 
diff --git a/libs/libvmbase/src/arch/aarch64/exceptions.rs b/libs/libvmbase/src/arch/aarch64/exceptions.rs
index 1868bf7..787ef37 100644
--- a/libs/libvmbase/src/arch/aarch64/exceptions.rs
+++ b/libs/libvmbase/src/arch/aarch64/exceptions.rs
@@ -14,12 +14,17 @@
 
 //! Helper functions and structs for exception handlers.
 
-use crate::memory::{MemoryTrackerError, MEMORY};
 use crate::{
-    arch::aarch64::layout::UART_PAGE_ADDR, arch::VirtualAddress, eprintln, memory::page_4kb_of,
+    arch::{
+        aarch64::layout::UART_PAGE_ADDR,
+        platform::{emergency_uart, DEFAULT_EMERGENCY_CONSOLE_INDEX},
+        VirtualAddress,
+    },
+    memory::{page_4kb_of, MemoryTrackerError, MEMORY},
+    power::reboot,
     read_sysreg,
 };
-use core::fmt;
+use core::fmt::{self, Write};
 use core::result;
 
 /// Represents an error that can occur while handling an exception.
@@ -122,14 +127,23 @@
         Self { esr, far: VirtualAddress(far) }
     }
 
-    /// Prints the details of an obj and the exception, excluding UART exceptions.
-    pub fn print<T: fmt::Display>(&self, exception_name: &str, obj: T, elr: u64) {
+    /// Prints the details of an obj and the exception, excluding UART exceptions, and then reboots.
+    ///
+    /// This uses the emergency console so can safely be called even for synchronous exceptions
+    /// without causing a deadlock.
+    pub fn print_and_reboot<T: fmt::Display>(&self, exception_name: &str, obj: T, elr: u64) -> ! {
         // Don't print to the UART if we are handling an exception it could raise.
         if !self.is_uart_exception() {
-            eprintln!("{exception_name}");
-            eprintln!("{obj}");
-            eprintln!("{}, elr={:#08x}", self, elr);
+            // SAFETY: We always reboot at the end of this method so there is no way for the
+            // original UART driver to be used after this.
+            if let Some(mut console) = unsafe { emergency_uart(DEFAULT_EMERGENCY_CONSOLE_INDEX) } {
+                // Ignore errors writing to emergency console, as we are about to reboot anyway.
+                _ = writeln!(console, "{exception_name}");
+                _ = writeln!(console, "{obj}");
+                _ = writeln!(console, "{}, elr={:#08x}", self, elr);
+            }
         }
+        reboot();
     }
 
     fn is_uart_exception(&self) -> bool {
diff --git a/libs/libvmbase/src/arch/aarch64/platform.rs b/libs/libvmbase/src/arch/aarch64/platform.rs
index b33df68..7e002d0 100644
--- a/libs/libvmbase/src/arch/aarch64/platform.rs
+++ b/libs/libvmbase/src/arch/aarch64/platform.rs
@@ -104,18 +104,25 @@
 
 /// Return platform uart with specific index
 ///
-/// Panics if console was not initialized by calling [`init`] first.
-pub fn uart(id: usize) -> &'static spin::mutex::SpinMutex<Uart> {
-    CONSOLES[id].get().unwrap()
+/// Returns `None` if console was not initialized by calling [`init`] first.
+pub fn uart(id: usize) -> Option<&'static SpinMutex<Uart>> {
+    CONSOLES[id].get()
 }
 
-/// Reinitializes the emergency UART driver and returns it.
+/// Reinitializes the n-th UART driver and returns it.
 ///
 /// This is intended for use in situations where the UART may be in an unknown state or the global
-/// instance may be locked, such as in an exception handler or panic handler.
-pub fn emergency_uart() -> Uart {
+/// instance may be locked, such as in the synchronous exception handler.
+///
+/// # Safety
+///
+/// This takes over the UART from wherever it is being used, the existing UART instance should not
+/// be used after this is called. This should only be used immediately before aborting the VM.
+pub unsafe fn emergency_uart(id: usize) -> Option<Uart> {
+    let addr = *ADDRESSES[id].get()?;
+
     // SAFETY: Initialization of UART using dedicated const address.
-    unsafe { Uart::new(UART_ADDRESSES[DEFAULT_EMERGENCY_CONSOLE_INDEX]) }
+    Some(unsafe { Uart::new(addr) })
 }
 
 /// Makes a `PSCI_SYSTEM_OFF` call to shutdown the VM.
diff --git a/libs/libvmbase/src/console.rs b/libs/libvmbase/src/console.rs
index 6d9a4fe..dcaf1ad 100644
--- a/libs/libvmbase/src/console.rs
+++ b/libs/libvmbase/src/console.rs
@@ -14,33 +14,26 @@
 
 //! Console driver for 8250 UART.
 
-use crate::arch::platform;
-use core::fmt::{write, Arguments, Write};
+use crate::arch::platform::{self, emergency_uart, DEFAULT_EMERGENCY_CONSOLE_INDEX};
+use crate::power::reboot;
+use core::fmt::{self, write, Arguments, Write};
+use core::panic::PanicInfo;
 
 /// Writes a formatted string followed by a newline to the n-th console.
 ///
-/// Panics if the n-th console was not initialized by calling [`init`] first.
-pub fn writeln(n: usize, format_args: Arguments) {
-    let uart = &mut *platform::uart(n).lock();
-    write(uart, format_args).unwrap();
-    let _ = uart.write_str("\n");
-}
+/// Returns an error if the n-th console was not initialized by calling [`init`] first.
+pub fn writeln(n: usize, format_args: Arguments) -> fmt::Result {
+    let uart = &mut *platform::uart(n).ok_or(fmt::Error)?.lock();
 
-/// Reinitializes the emergency UART driver and writes a formatted string followed by a newline to
-/// it.
-///
-/// This is intended for use in situations where the UART may be in an unknown state or the global
-/// instance may be locked, such as in an exception handler or panic handler.
-pub fn ewriteln(format_args: Arguments) {
-    let mut uart = platform::emergency_uart();
-    let _ = write(&mut uart, format_args);
-    let _ = uart.write_str("\n");
+    write(uart, format_args)?;
+    uart.write_str("\n")?;
+    Ok(())
 }
 
 /// Prints the given formatted string to the n-th console, followed by a newline.
 ///
-/// Panics if the console has not yet been initialized. May hang if used in an exception context;
-/// use `eprintln!` instead.
+/// Returns an error if the console has not yet been initialized. May deadlock if used in a
+/// synchronous exception handler.
 #[macro_export]
 macro_rules! console_writeln {
     ($n:expr, $($arg:tt)*) => ({
@@ -48,27 +41,24 @@
     })
 }
 
-pub(crate) use console_writeln;
-
 /// Prints the given formatted string to the console, followed by a newline.
 ///
-/// Panics if the console has not yet been initialized. May hang if used in an exception context;
-/// use `eprintln!` instead.
+/// Panics if the console has not yet been initialized. May hang if used in an exception context.
 macro_rules! println {
     ($($arg:tt)*) => ({
-        $crate::console::console_writeln!($crate::arch::platform::DEFAULT_CONSOLE_INDEX, $($arg)*)
+        $crate::console_writeln!($crate::arch::platform::DEFAULT_CONSOLE_INDEX, $($arg)*).unwrap()
     })
 }
 
 pub(crate) use println; // Make it available in this crate.
 
-/// Prints the given string followed by a newline to the console in an emergency, such as an
-/// exception handler.
-///
-/// Never panics.
-#[macro_export]
-macro_rules! eprintln {
-    ($($arg:tt)*) => ({
-        $crate::console::ewriteln(format_args!($($arg)*))
-    })
+#[panic_handler]
+fn panic(info: &PanicInfo) -> ! {
+    // SAFETY: We always reboot at the end of this method so there is no way for the
+    // original UART driver to be used after this.
+    if let Some(mut console) = unsafe { emergency_uart(DEFAULT_EMERGENCY_CONSOLE_INDEX) } {
+        // Ignore errors, to avoid a panic loop.
+        let _ = writeln!(console, "{}", info);
+    }
+    reboot()
 }
diff --git a/libs/libvmbase/src/lib.rs b/libs/libvmbase/src/lib.rs
index d254038..afb62fc 100644
--- a/libs/libvmbase/src/lib.rs
+++ b/libs/libvmbase/src/lib.rs
@@ -32,12 +32,3 @@
 pub mod uart;
 pub mod util;
 pub mod virtio;
-
-use core::panic::PanicInfo;
-use power::reboot;
-
-#[panic_handler]
-fn panic(info: &PanicInfo) -> ! {
-    eprintln!("{}", info);
-    reboot()
-}
diff --git a/libs/libvmbase/src/logger.rs b/libs/libvmbase/src/logger.rs
index 9130918..0059d11 100644
--- a/libs/libvmbase/src/logger.rs
+++ b/libs/libvmbase/src/logger.rs
@@ -16,7 +16,7 @@
 //!
 //! Internally uses the println! vmbase macro, which prints to crosvm's UART.
 //! Note: may not work if the VM is in an inconsistent state. Exception handlers
-//! should avoid using this logger and instead print with eprintln!.
+//! should avoid using this logger.
 
 use crate::console::println;
 use core::sync::atomic::{AtomicBool, Ordering};
diff --git a/tests/hostside/helper/java/com/android/microdroid/test/host/MicrodroidHostTestCaseBase.java b/tests/hostside/helper/java/com/android/microdroid/test/host/MicrodroidHostTestCaseBase.java
index fcef19a..7eb7748 100644
--- a/tests/hostside/helper/java/com/android/microdroid/test/host/MicrodroidHostTestCaseBase.java
+++ b/tests/hostside/helper/java/com/android/microdroid/test/host/MicrodroidHostTestCaseBase.java
@@ -262,6 +262,11 @@
     }
 
     public List<String> getSupportedOSList() throws Exception {
+        // The --os flag was introduced in SDK level 36. When running tests on earlier dessert
+        // releases only use "microdroid" OS.
+        if (getAndroidDevice().getApiLevel() < 36) {
+            return Arrays.asList("microdroid");
+        }
         return parseStringArrayFieldsFromVmInfo("Available OS list: ");
     }
 
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 2434ed0..379ac98 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -496,15 +496,20 @@
         final String configPath = "assets/vm_config_apex.json";
 
         // Act
-        mMicrodroidDevice =
+        MicrodroidBuilder microdroidBuilder =
                 MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
                         .debugLevel(DEBUG_LEVEL_FULL)
                         .memoryMib(minMemorySize())
                         .cpuTopology("match_host")
                         .protectedVm(true)
-                        .os(SUPPORTED_OSES.get(os))
-                        .name("protected_vm_runs_pvmfw")
-                        .build(getAndroidDevice());
+                        .name("protected_vm_runs_pvmfw");
+
+        // --os flag was introduced in SDK 36
+        if (getAndroidDevice().getApiLevel() >= 36) {
+            microdroidBuilder.os(SUPPORTED_OSES.get(os));
+        }
+
+        mMicrodroidDevice = microdroidBuilder.build(getAndroidDevice());
 
         // Assert
         mMicrodroidDevice.waitForBootComplete(BOOT_COMPLETE_TIMEOUT);
@@ -647,14 +652,18 @@
         CommandRunner android = new CommandRunner(getDevice());
         String testStartTime = android.runWithTimeout(1000, "date", "'+%Y-%m-%d %H:%M:%S.%N'");
 
-        mMicrodroidDevice =
+        MicrodroidBuilder microdroidBuilder =
                 MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
                         .debugLevel(DEBUG_LEVEL_FULL)
                         .memoryMib(minMemorySize())
                         .cpuTopology("match_host")
-                        .protectedVm(protectedVm)
-                        .os(SUPPORTED_OSES.get(os))
-                        .build(getAndroidDevice());
+                        .protectedVm(protectedVm);
+
+        if (getAndroidDevice().getApiLevel() >= 36) {
+            microdroidBuilder.os(SUPPORTED_OSES.get(os));
+        }
+
+        mMicrodroidDevice = microdroidBuilder.build(getAndroidDevice());
         mMicrodroidDevice.waitForBootComplete(BOOT_COMPLETE_TIMEOUT);
         mMicrodroidDevice.enableAdbRoot();
 
@@ -874,15 +883,20 @@
         // Create VM with microdroid
         TestDevice device = getAndroidDevice();
         final String configPath = "assets/vm_config_apex.json"; // path inside the APK
-        ITestDevice microdroid =
+        MicrodroidBuilder microdroidBuilder =
                 MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
                         .debugLevel(DEBUG_LEVEL_FULL)
                         .memoryMib(minMemorySize())
                         .cpuTopology("match_host")
                         .protectedVm(protectedVm)
-                        .os(SUPPORTED_OSES.get(os))
-                        .name("test_telemetry_pushed_atoms")
-                        .build(device);
+                        .name("test_telemetry_pushed_atoms");
+
+        if (device.getApiLevel() >= 36) {
+            microdroidBuilder.os(SUPPORTED_OSES.get(os));
+        }
+
+        ITestDevice microdroid = microdroidBuilder.build(device);
+
         microdroid.waitForBootComplete(BOOT_COMPLETE_TIMEOUT);
         device.shutdownMicrodroid(microdroid);
 
@@ -1026,14 +1040,18 @@
         assumeVmTypeSupported(os, protectedVm);
 
         final String configPath = "assets/vm_config.json"; // path inside the APK
-        testMicrodroidBootsWithBuilder(
+        MicrodroidBuilder microdroidBuilder =
                 MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
                         .debugLevel(DEBUG_LEVEL_FULL)
                         .memoryMib(minMemorySize())
                         .cpuTopology("match_host")
                         .protectedVm(protectedVm)
-                        .name("test_microdroid_boots")
-                        .os(SUPPORTED_OSES.get(os)));
+                        .name("test_microdroid_boots");
+        if (getAndroidDevice().getApiLevel() >= 36) {
+            microdroidBuilder.os(SUPPORTED_OSES.get(os));
+        }
+
+        testMicrodroidBootsWithBuilder(microdroidBuilder);
     }
 
     @Test
@@ -1064,15 +1082,18 @@
         assumeVmTypeSupported(os, protectedVm);
 
         final String configPath = "assets/vm_config.json";
-        mMicrodroidDevice =
+        MicrodroidBuilder microdroidBuilder =
                 MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
                         .debugLevel(DEBUG_LEVEL_FULL)
                         .memoryMib(minMemorySize())
                         .cpuTopology("match_host")
                         .protectedVm(protectedVm)
-                        .os(SUPPORTED_OSES.get(os))
-                        .name("test_microdroid_ram_usage")
-                        .build(getAndroidDevice());
+                        .name("test_microdroid_ram_usage");
+        if (getAndroidDevice().getApiLevel() >= 36) {
+            microdroidBuilder.os(SUPPORTED_OSES.get(os));
+        }
+
+        mMicrodroidDevice = microdroidBuilder.build(getAndroidDevice());
         mMicrodroidDevice.waitForBootComplete(BOOT_COMPLETE_TIMEOUT);
         mMicrodroidDevice.enableAdbRoot();
 
@@ -1362,16 +1383,18 @@
         Objects.requireNonNull(device);
         final String configPath = "assets/vm_config.json";
 
-        mMicrodroidDevice =
+        MicrodroidBuilder microdroidBuilder =
                 MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
                         .debugLevel(DEBUG_LEVEL_FULL)
                         .memoryMib(minMemorySize())
                         .cpuTopology("match_host")
                         .protectedVm(protectedVm)
-                        .os(SUPPORTED_OSES.get(os))
-                        .addAssignableDevice(device)
-                        .build(getAndroidDevice());
+                        .addAssignableDevice(device);
+        if (getAndroidDevice().getApiLevel() >= 36) {
+            microdroidBuilder.os(SUPPORTED_OSES.get(os));
+        }
 
+        mMicrodroidDevice = microdroidBuilder.build(getAndroidDevice());
         assertThat(mMicrodroidDevice.waitForBootComplete(BOOT_COMPLETE_TIMEOUT)).isTrue();
         assertThat(mMicrodroidDevice.enableAdbRoot()).isTrue();
     }
@@ -1408,16 +1431,19 @@
         android.run("echo advise > " + SHMEM_ENABLED_PATH);
 
         final String configPath = "assets/vm_config.json";
-        mMicrodroidDevice =
+        MicrodroidBuilder microdroidBuilder =
                 MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
                         .debugLevel(DEBUG_LEVEL_FULL)
                         .memoryMib(minMemorySize())
                         .cpuTopology("match_host")
                         .protectedVm(protectedVm)
-                        .os(SUPPORTED_OSES.get(os))
                         .hugePages(true)
-                        .name("test_huge_pages")
-                        .build(getAndroidDevice());
+                        .name("test_huge_pages");
+        if (getAndroidDevice().getApiLevel() >= 36) {
+            microdroidBuilder.os(SUPPORTED_OSES.get(os));
+        }
+
+        mMicrodroidDevice = microdroidBuilder.build(getAndroidDevice());
         mMicrodroidDevice.waitForBootComplete(BOOT_COMPLETE_TIMEOUT);
 
         android.run("echo never >" + SHMEM_ENABLED_PATH);