Merge changes from topic "custom-smcs" into main
* changes:
Start a VM in suspended state if vendor_tee_services were requested
custom smcs: check for presence of HAL
diff --git a/android/TerminalApp/AndroidManifest.xml b/android/TerminalApp/AndroidManifest.xml
index aa702a3..48b53dd 100644
--- a/android/TerminalApp/AndroidManifest.xml
+++ b/android/TerminalApp/AndroidManifest.xml
@@ -65,6 +65,8 @@
<activity android:name=".ErrorActivity"
android:label="@string/error_title"
android:process=":error" />
+ <activity android:name=".UpgradeActivity"
+ android:label="@string/upgrade_title" />
<property
android:name="android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED"
android:value="true" />
diff --git a/android/TerminalApp/assets/js/terminal_disconnect.js b/android/TerminalApp/assets/js/terminal_disconnect.js
new file mode 100644
index 0000000..1c89a13
--- /dev/null
+++ b/android/TerminalApp/assets/js/terminal_disconnect.js
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2025 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.
+ */
+
+(function() {
+ var originalLog = console.log;
+ console.log = function() {
+ console.log.history = console.log.history || [];
+ console.log.history.push(arguments);
+ originalLog.apply(console, arguments);
+ if (typeof arguments[0] === 'string' && arguments[0].startsWith("[ttyd] websocket connection closed with code: ")) {
+ TerminalApp.closeTab()
+ }
+ };
+})();
\ No newline at end of file
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/ErrorActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/ErrorActivity.kt
index 0a1090d..fe92854 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/ErrorActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/ErrorActivity.kt
@@ -18,6 +18,7 @@
import android.content.Context
import android.content.Intent
import android.os.Bundle
+import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.TextView
import java.io.IOException
@@ -34,6 +35,7 @@
val button = findViewById<View>(R.id.recovery)
button.setOnClickListener(View.OnClickListener { _ -> launchRecoveryActivity() })
+ findViewById<TextView>(R.id.cause).setMovementMethod(ScrollingMovementMethod())
}
override fun onNewIntent(intent: Intent) {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
index 086ff3d..04d6813 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
@@ -66,6 +67,16 @@
}
}
+ fun isOlderThanCurrentVersion(): Boolean {
+ val year =
+ try {
+ buildId.split(" ").last().toInt()
+ } catch (_: Exception) {
+ 0
+ }
+ return year < RELEASE_YEAR
+ }
+
@Throws(IOException::class)
fun uninstallAndBackup(): Path {
Files.delete(marker)
@@ -83,7 +94,7 @@
}
@Throws(IOException::class)
- fun getSize(): Long {
+ fun getApparentSize(): Long {
return Files.size(rootPartition)
}
@@ -118,7 +129,7 @@
@Throws(IOException::class)
fun resize(desiredSize: Long): Long {
val roundedUpDesiredSize = roundUp(desiredSize)
- val curSize = getSize()
+ val curSize = getApparentSize()
runE2fsck(rootPartition)
@@ -127,10 +138,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 +187,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)
}
}
@@ -153,6 +201,7 @@
const val MARKER_FILENAME: String = "completed"
const val RESIZE_STEP_BYTES: Long = 4 shl 20 // 4 MiB
+ const val RELEASE_YEAR: Int = 2025
/** Returns InstalledImage for a given app context */
fun getDefault(context: Context): InstalledImage {
@@ -161,19 +210,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 +249,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/Logger.kt b/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
index ba03716..088744e 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
@@ -17,9 +17,7 @@
import android.system.virtualmachine.VirtualMachine
import android.system.virtualmachine.VirtualMachineConfig
-import android.system.virtualmachine.VirtualMachineException
import android.util.Log
-import com.android.virtualization.terminal.Logger.LineBufferedOutputStream
import java.io.BufferedOutputStream
import java.io.BufferedReader
import java.io.IOException
@@ -56,19 +54,29 @@
val logPath = dir.resolve(LocalDateTime.now().toString() + ".txt")
val console = vm.getConsoleOutput()
val file = Files.newOutputStream(logPath, StandardOpenOption.CREATE)
- executor.submit<Int?> {
- console.use { console ->
- LineBufferedOutputStream(file).use { fileOutput ->
- Streams.copy(console, fileOutput)
+ executor.execute({
+ try {
+ console.use { console ->
+ LineBufferedOutputStream(file).use { fileOutput ->
+ Streams.copy(console, fileOutput)
+ }
}
+ } catch (e: Exception) {
+ Log.w(tag, "Failed to log console output. VM may be shutting down", e)
}
- }
+ })
val log = vm.getLogOutput()
- executor.submit<Unit> { log.use { writeToLogd(it, tag) } }
- } catch (e: VirtualMachineException) {
- throw RuntimeException(e)
- } catch (e: IOException) {
+ executor.execute({
+ log.use {
+ try {
+ writeToLogd(it, tag)
+ } catch (e: Exception) {
+ Log.w(tag, "Failed to log VM log output. VM may be shutting down", e)
+ }
+ }
+ })
+ } catch (e: Exception) {
throw RuntimeException(e)
}
}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
index d85242b..14855ac 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
@@ -24,6 +24,7 @@
import android.content.res.Configuration
import android.graphics.drawable.Icon
import android.graphics.fonts.FontStyle
+import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
@@ -50,6 +51,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
@@ -77,6 +79,7 @@
private lateinit var terminalTabAdapter: TerminalTabAdapter
private val terminalInfo = CompletableFuture<TerminalInfo>()
private val terminalViewModel: TerminalViewModel by viewModels()
+ private var isVmRunning = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -102,7 +105,13 @@
// if installer is launched, it will be handled in onActivityResult
if (!launchInstaller) {
- if (!Environment.isExternalStorageManager()) {
+ if (image.isOlderThanCurrentVersion()) {
+ val intent = Intent(this, UpgradeActivity::class.java)
+ intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
+ startActivity(intent)
+ // Explicitly finish to make sure that user can't go back from ErrorActivity.
+ finish()
+ } else if (!Environment.isExternalStorageManager()) {
requestStoragePermissions(this, manageExternalStorageActivityResultLauncher)
} else {
startVm()
@@ -178,20 +187,20 @@
terminalViewModel.terminalTabs[tabId] = tab
tab.customView!!
.findViewById<Button>(R.id.tab_close_button)
- .setOnClickListener(
- View.OnClickListener { _: View? ->
- if (terminalTabAdapter.tabs.size == 1) {
- finishAndRemoveTask()
- }
- viewPager.offscreenPageLimit -= 1
- terminalTabAdapter.deleteTab(tab.position)
- tabLayout.removeTab(tab)
- }
- )
+ .setOnClickListener(View.OnClickListener { _: View? -> closeTab(tab) })
// Add and select the tab
tabLayout.addTab(tab, true)
}
+ fun closeTab(tab: TabLayout.Tab) {
+ if (terminalTabAdapter.tabs.size == 1) {
+ finish()
+ }
+ viewPager.offscreenPageLimit -= 1
+ terminalTabAdapter.deleteTab(tab.position)
+ tabLayout.removeTab(tab)
+ }
+
private fun lockOrientationIfNecessary() {
val hasHwQwertyKeyboard = resources.configuration.keyboard == Configuration.KEYBOARD_QWERTY
if (hasHwQwertyKeyboard) {
@@ -227,6 +236,16 @@
activityResultLauncher.launch(intent)
}
+ override fun onPause() {
+ super.onPause()
+ MediaScannerConnection.scanFile(
+ this,
+ arrayOf("/storage/emulated/${userId}/Download"),
+ null /* mimeTypes */,
+ null, /* callback */
+ )
+ }
+
private fun getTerminalServiceUrl(ipAddress: String?, port: Int): URL? {
val config = resources.configuration
// TODO: Always enable screenReaderMode (b/395845063)
@@ -262,13 +281,16 @@
executorService.shutdown()
getSystemService<AccessibilityManager>(AccessibilityManager::class.java)
.removeAccessibilityStateChangeListener(this)
- val intent = VmLauncherService.getIntentForShutdown(this, this)
- startService(intent)
+ if (isVmRunning) {
+ val intent = VmLauncherService.getIntentForShutdown(this, this)
+ startService(intent)
+ }
super.onDestroy()
}
override fun onVmStart() {
Log.i(TAG, "onVmStart()")
+ isVmRunning = true
}
override fun onTerminalAvailable(info: TerminalInfo) {
@@ -277,11 +299,13 @@
override fun onVmStop() {
Log.i(TAG, "onVmStop()")
+ isVmRunning = false
finish()
}
override fun onVmError() {
Log.i(TAG, "onVmError()")
+ isVmRunning = false
// TODO: error cause is too simple.
ErrorActivity.start(this, Exception("onVmError"))
}
@@ -368,7 +392,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/MemBalloonController.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt
index 7647d9b..2ed7217 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt
@@ -58,7 +58,7 @@
// available memory to the virtual machine
override fun onResume(owner: LifecycleOwner) {
ongoingInflation?.cancel(false)
- executor.submit({
+ executor.execute({
Log.v(TAG, "app resumed. deflating mem balloon to the minimum")
vm.setMemoryBalloonByPercent(0)
})
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..00baeef 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
@@ -15,13 +15,15 @@
*/
package com.android.virtualization.terminal
+import android.content.Context
import android.content.Intent
import android.icu.text.MeasureFormat
import android.icu.text.NumberFormat
import android.icu.util.Measure
import android.icu.util.MeasureUnit
import android.os.Bundle
-import android.os.Environment
+import android.os.storage.StorageManager
+import android.os.storage.StorageManager.UUID_DEFAULT
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
@@ -33,12 +35,13 @@
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
class SettingsDiskResizeActivity : AppCompatActivity() {
private val numberPattern: Pattern = Pattern.compile("[\\d]*[\\٫.,]?[\\d]+")
- private val defaultMaxDiskSizeMb: Long = 16 shl 10
+ private val defaultHostReserveSizeMb: Long = 5 shl 10
private var diskSizeStepMb: Long = 0
private var diskSizeMb: Long = 0
@@ -46,6 +49,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 +60,13 @@
return bytes shl 20
}
+ private fun getAvailableSizeMb(): Long {
+ var storageManager =
+ applicationContext.getSystemService(Context.STORAGE_SERVICE) as StorageManager
+ val hostAllocatableMb = bytesToMb(storageManager.getAllocatableBytes(UUID_DEFAULT))
+ return diskSizeMb + hostAllocatableMb
+ }
+
private fun mbToProgress(bytes: Long): Int {
return (bytes / diskSizeStepMb).toInt()
}
@@ -71,15 +82,15 @@
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)
+ var maxDiskSizeMb = getAvailableSizeMb()
+ if (maxDiskSizeMb > defaultHostReserveSizeMb) {
+ maxDiskSizeMb -= defaultHostReserveSizeMb
+ }
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 +149,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 +212,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/SettingsRecoveryActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsRecoveryActivity.kt
index 319a53b..654cb57 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsRecoveryActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsRecoveryActivity.kt
@@ -21,19 +21,23 @@
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
-import androidx.lifecycle.lifecycleScope
import com.android.virtualization.terminal.MainActivity.Companion.TAG
import com.google.android.material.card.MaterialCardView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import java.io.IOException
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
class SettingsRecoveryActivity : AppCompatActivity() {
+ private lateinit var executorService: ExecutorService
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+
+ executorService =
+ Executors.newSingleThreadExecutor(TerminalThreadFactory(applicationContext))
+
setContentView(R.layout.settings_recovery)
val resetCard = findViewById<MaterialCardView>(R.id.settings_recovery_reset_card)
@@ -81,6 +85,12 @@
}
}
+ override fun onDestroy() {
+ super.onDestroy()
+
+ executorService.shutdown()
+ }
+
private fun removeBackup(): Unit {
try {
InstalledImage.getDefault(this).deleteBackup()
@@ -116,27 +126,22 @@
}
}
- private fun runInBackgroundAndRestartApp(
- backgroundWork: suspend CoroutineScope.() -> Unit
- ): Unit {
+ private fun runInBackgroundAndRestartApp(backgroundWork: Runnable) {
findViewById<View>(R.id.setting_recovery_card_container).visibility = View.INVISIBLE
findViewById<View>(R.id.recovery_boot_progress).visibility = View.VISIBLE
- lifecycleScope
- .launch(Dispatchers.IO) { backgroundWork() }
- .invokeOnCompletion {
- runOnUiThread {
- findViewById<View>(R.id.setting_recovery_card_container).visibility =
- View.VISIBLE
- findViewById<View>(R.id.recovery_boot_progress).visibility = View.INVISIBLE
- // Restart terminal
- val intent =
- baseContext.packageManager.getLaunchIntentForPackage(
- baseContext.packageName
- )
- intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
- finish()
- startActivity(intent)
- }
+ executorService.execute({
+ backgroundWork.run()
+
+ runOnUiThread {
+ findViewById<View>(R.id.setting_recovery_card_container).visibility = View.VISIBLE
+ findViewById<View>(R.id.recovery_boot_progress).visibility = View.INVISIBLE
+ // Restart terminal
+ val intent =
+ baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
+ intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
+ finish()
+ startActivity(intent)
}
+ })
}
}
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/TerminalTabFragment.kt b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
index a0c6e4e..8106f6e 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
@@ -24,6 +24,7 @@
import android.view.View
import android.view.ViewGroup
import android.webkit.ClientCertRequest
+import android.webkit.JavascriptInterface
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
@@ -92,6 +93,7 @@
terminalView.webChromeClient = TerminalWebChromeClient()
terminalView.webViewClient = TerminalWebViewClient()
+ terminalView.addJavascriptInterface(TerminalViewInterface(context!!), "TerminalApp")
(activity as MainActivity).modifierKeysController.addTerminalView(terminalView)
terminalViewModel.terminalViews.add(terminalView)
@@ -119,6 +121,18 @@
}
}
+ inner class TerminalViewInterface(private val mContext: android.content.Context) {
+ @JavascriptInterface
+ fun closeTab() {
+ if (activity != null) {
+ activity?.runOnUiThread {
+ val mainActivity = (activity as MainActivity)
+ mainActivity.closeTab(terminalViewModel.terminalTabs[id]!!)
+ }
+ }
+ }
+ }
+
private inner class TerminalWebViewClient : WebViewClient() {
private var loadFailed = false
private var requestId: Long = 0
@@ -174,6 +188,7 @@
bootProgressView.visibility = View.GONE
terminalView.visibility = View.VISIBLE
terminalView.mapTouchToMouseEvent()
+ terminalView.applyTerminalDisconnectCallback()
updateMainActivity()
updateFocus()
}
@@ -201,7 +216,7 @@
}
private fun updateMainActivity() {
- val mainActivity = (activity as MainActivity)
+ val mainActivity = activity as MainActivity ?: return
if (terminalGuiSupport()) {
mainActivity.displayMenu!!.visibility = View.VISIBLE
mainActivity.displayMenu!!.isEnabled = true
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalView.kt b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalView.kt
index 4b11c1d..9c83d8b 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalView.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalView.kt
@@ -41,6 +41,8 @@
private val ctrlKeyHandler: String = readAssetAsString(context, "js/ctrl_key_handler.js")
private val enableCtrlKey: String = readAssetAsString(context, "js/enable_ctrl_key.js")
private val disableCtrlKey: String = readAssetAsString(context, "js/disable_ctrl_key.js")
+ private val terminalDisconnectCallback: String =
+ readAssetAsString(context, "js/terminal_disconnect.js")
private val touchToMouseHandler: String =
readAssetAsString(context, "js/touch_to_mouse_handler.js")
private val a11yManager =
@@ -70,6 +72,10 @@
this.evaluateJavascript(disableCtrlKey, null)
}
+ fun applyTerminalDisconnectCallback() {
+ this.evaluateJavascript(terminalDisconnectCallback, null)
+ }
+
override fun onAccessibilityStateChanged(enabled: Boolean) {
Log.d(TAG, "accessibility $enabled")
adjustToA11yStateChange()
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/UpgradeActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/UpgradeActivity.kt
new file mode 100644
index 0000000..357de94
--- /dev/null
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/UpgradeActivity.kt
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2025 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.
+ */
+package com.android.virtualization.terminal
+
+import android.annotation.MainThread
+import android.content.Intent
+import android.os.Bundle
+import android.util.Log
+import android.view.View
+import com.google.android.material.snackbar.Snackbar
+import java.io.IOException
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+
+class UpgradeActivity : BaseActivity() {
+ private lateinit var executorService: ExecutorService
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+
+ executorService =
+ Executors.newSingleThreadExecutor(TerminalThreadFactory(applicationContext))
+
+ setContentView(R.layout.activity_upgrade)
+
+ val button = findViewById<View>(R.id.upgrade)
+ button.setOnClickListener { _ -> upgrade() }
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+
+ executorService.shutdown()
+ }
+
+ private fun upgrade() {
+ findViewById<View>(R.id.progress).visibility = View.VISIBLE
+
+ executorService.execute {
+ val image = InstalledImage.getDefault(this)
+ try {
+ image.uninstallAndBackup()
+ } catch (e: IOException) {
+ Snackbar.make(
+ findViewById<View>(android.R.id.content),
+ R.string.upgrade_error,
+ Snackbar.LENGTH_SHORT,
+ )
+ .show()
+ Log.e(MainActivity.Companion.TAG, "Failed to upgrade ", e)
+ return@execute
+ }
+
+ runOnUiThread {
+ findViewById<View>(R.id.progress).visibility = View.INVISIBLE
+ restartTerminal()
+ }
+ }
+ }
+
+ @MainThread
+ private fun restartTerminal() {
+ val intent = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
+ intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
+ finish()
+ startActivity(intent)
+ }
+}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
index f426ce6..f1ad561 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
@@ -93,7 +94,7 @@
override fun onCreate() {
super.onCreate()
- val threadFactory = TerminalThreadFactory(getApplicationContext())
+ val threadFactory = TerminalThreadFactory(applicationContext)
bgThreads = Executors.newCachedThreadPool(threadFactory)
mainWorkerThread = Executors.newSingleThreadExecutor(threadFactory)
image = InstalledImage.getDefault(this)
@@ -120,9 +121,9 @@
// 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({
+ mainWorkerThread.execute({
doStart(notification, displayInfo, diskSize, resultReceiver)
})
@@ -130,7 +131,7 @@
// ForegroundServiceDidNotStartInTimeException
startForeground(this.hashCode(), notification)
}
- ACTION_SHUTDOWN_VM -> mainWorkerThread.submit({ doShutdown(resultReceiver) })
+ ACTION_SHUTDOWN_VM -> mainWorkerThread.execute({ doShutdown(resultReceiver) })
else -> {
Log.e(TAG, "Unknown command " + intent.action)
stopSelf()
@@ -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,21 +463,36 @@
@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)
+ }
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 {
// If there is no Debian service or it fails to shutdown, just stop the service.
runner?.vm?.stop()
- stopSelf()
}
}
@@ -449,7 +503,7 @@
}
override fun onDestroy() {
- mainWorkerThread.submit({
+ mainWorkerThread.execute({
if (runner?.vm?.getStatus() == VirtualMachine.STATUS_RUNNING) {
doShutdown(null)
}
@@ -459,6 +513,7 @@
stopDebianServer()
bgThreads.shutdownNow()
mainWorkerThread.shutdown()
+ stopForeground(STOP_FOREGROUND_REMOVE)
super.onDestroy()
}
@@ -478,7 +533,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/drawable/ic_launcher_monochrome.xml b/android/TerminalApp/res/drawable/ic_launcher_monochrome.xml
new file mode 100644
index 0000000..90dc2d2
--- /dev/null
+++ b/android/TerminalApp/res/drawable/ic_launcher_monochrome.xml
@@ -0,0 +1,33 @@
+<?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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:viewportWidth="142"
+ android:viewportHeight="168.75">
+ <group android:scaleX="0.37325713"
+ android:scaleY="0.44357142"
+ android:translateX="43.332314"
+ android:translateY="39.324776">
+ <group android:translateY="133.59375">
+ <path android:pathData="M9.078125,-77.484375L69.75,-51.40625L69.75,-37.765625L9.078125,-11.609375L9.078125,-28.40625L52.53125,-44.71875L9.078125,-60.75L9.078125,-77.484375Z"
+ android:fillColor="#000000"/>
+ <path android:pathData="M139.76562,0L139.76562,13.5L75.21875,13.5L75.21875,0L139.76562,0Z"
+ android:fillColor="#000000"/>
+ </group>
+ </group>
+</vector>
\ No newline at end of file
diff --git a/android/TerminalApp/res/layout/activity_upgrade.xml b/android/TerminalApp/res/layout/activity_upgrade.xml
new file mode 100644
index 0000000..13e8404
--- /dev/null
+++ b/android/TerminalApp/res/layout/activity_upgrade.xml
@@ -0,0 +1,66 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright 2025 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.
+ -->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:fitsSystemWindows="true"
+ tools:context=".UpgradeActivity">
+
+ <TextView
+ android:id="@+id/title"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/upgrade_title"
+ android:layout_marginVertical="24dp"
+ android:layout_marginHorizontal="24dp"
+ android:layout_alignParentTop="true"
+ android:hyphenationFrequency="full"
+ android:textSize="48sp" />
+
+ <com.google.android.material.progressindicator.LinearProgressIndicator
+ android:id="@+id/progress"
+ android:indeterminate="true"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentStart="true"
+ android:layout_below="@id/title"
+ android:visibility="invisible" />
+
+ <TextView
+ android:id="@+id/desc"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/upgrade_desc"
+ android:lineSpacingExtra="5sp"
+ android:layout_marginTop="20dp"
+ android:layout_marginHorizontal="48dp"
+ android:layout_below="@id/progress"
+ android:textSize="20sp" />
+
+ <Button
+ android:id="@+id/upgrade"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentEnd="true"
+ android:layout_marginBottom="32dp"
+ android:layout_marginHorizontal="40dp"
+ android:backgroundTint="?attr/colorPrimaryDark"
+ android:text="@string/upgrade_button" />
+
+</RelativeLayout>
diff --git a/android/TerminalApp/res/mipmap-anydpi-v26/ic_launcher.xml b/android/TerminalApp/res/mipmap-anydpi-v26/ic_launcher.xml
index f96d8eb..0d9c436 100644
--- a/android/TerminalApp/res/mipmap-anydpi-v26/ic_launcher.xml
+++ b/android/TerminalApp/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -17,4 +17,5 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
+ <monochrome android:drawable="@drawable/ic_launcher_monochrome"/>
</adaptive-icon>
\ No newline at end of file
diff --git a/android/TerminalApp/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/TerminalApp/res/mipmap-anydpi-v26/ic_launcher_round.xml
index f96d8eb..0d9c436 100644
--- a/android/TerminalApp/res/mipmap-anydpi-v26/ic_launcher_round.xml
+++ b/android/TerminalApp/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -17,4 +17,5 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
+ <monochrome android:drawable="@drawable/ic_launcher_monochrome"/>
</adaptive-icon>
\ No newline at end of file
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..a0e33e5 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] -->
@@ -159,6 +161,15 @@
<!-- Error page that shows detailed error code (error reason) for bugreport. [CHAR LIMIT=none] -->
<string name="error_code">Error code: <xliff:g id="error_code" example="ACCESS_DENIED">%s</xliff:g></string>
+ <!-- Upgrade page's title. Tells users that you'll need to upgrade [CHAR LIMIT=none] -->
+ <string name="upgrade_title">Upgrade to newer terminal</string>
+ <!-- Upgrade page's description. Tell users that can't use as-is, and also explains next step. (/mnt/backup is the path which is supposed not to be translated) [CHAR LIMIT=none] -->
+ <string name="upgrade_desc">Linux terminal you were using is out of date. Please upgrade to proceed.\nData will be backed at <xliff:g id="path" example="/mnt/backup">/mnt/backup</xliff:g></string>
+ <!-- Upgrade page's button to start upgrade. [CHAR LIMIT=16] -->
+ <string name="upgrade_button">Upgrade</string>
+ <!-- Upgrade page's error toast message when upgrade failed. [CHAR LIMIT=none] -->
+ <string name="upgrade_error">Upgrade failed</string>
+
<!-- Notification action button for settings [CHAR LIMIT=20] -->
<string name="service_notification_settings">Settings</string>
<!-- Notification title for foreground service notification [CHAR LIMIT=none] -->
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 66d32ce..161a534 100644
--- a/android/virtmgr/src/aidl.rs
+++ b/android/virtmgr/src/aidl.rs
@@ -644,6 +644,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) {
@@ -671,7 +689,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/virtmgr/src/debug_config.rs b/android/virtmgr/src/debug_config.rs
index 6e2bfef..e552cf4 100644
--- a/android/virtmgr/src/debug_config.rs
+++ b/android/virtmgr/src/debug_config.rs
@@ -191,7 +191,7 @@
impl DebugConfig {
pub fn new(config: &VirtualMachineConfig) -> Self {
let debug_level = get_debug_level(config).unwrap_or(DebugLevel::NONE);
- let debug_policy = Self::get_debug_policy().unwrap_or_else(|| {
+ let debug_policy = Self::get_debug_policy(config).unwrap_or_else(|| {
info!("Debug policy is disabled");
Default::default()
});
@@ -204,7 +204,11 @@
Self { debug_level, debug_policy, dump_device_tree }
}
- fn get_debug_policy() -> Option<DebugPolicy> {
+ fn get_debug_policy(config: &VirtualMachineConfig) -> Option<DebugPolicy> {
+ if matches!(config, VirtualMachineConfig::RawConfig(_)) {
+ info!("Debug policy ignored for non-Microdroid VM");
+ return None;
+ }
let dp_sysprop = system_properties::read(CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP);
let custom_dp = dp_sysprop.unwrap_or_else(|e| {
warn!("Failed to read sysprop {CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP}: {e}");
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..7496f4d 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: [
@@ -68,10 +69,7 @@
default: [],
}),
- canned_fs_config: select(release_flag("RELEASE_AVF_ENABLE_VIRT_CPUFREQ"), {
- true: "canned_fs_config_sys_nice",
- default: "canned_fs_config",
- }),
+ canned_fs_config: "canned_fs_config",
}
vintf_fragment {
@@ -108,7 +106,6 @@
"rialto_bin",
"android_bootloader_crosvm_aarch64",
],
- native_shared_libs: ["libavf"],
},
x86_64: {
binaries: [
@@ -129,7 +126,6 @@
prebuilts: [
"android_bootloader_crosvm_x86_64",
],
- native_shared_libs: ["libavf"],
},
},
binaries: [
diff --git a/build/apex/canned_fs_config b/build/apex/canned_fs_config
index 5afd9d6..90c9747 100644
--- a/build/apex/canned_fs_config
+++ b/build/apex/canned_fs_config
@@ -1 +1,3 @@
/bin/virtualizationservice 0 2000 0755 capabilities=0x1000001 # CAP_CHOWN, CAP_SYS_RESOURCE
+/bin/crosvm 0 3013 0755 capabilities=0x800000 # CAP_SYS_NICE
+/bin/virtmgr 0 3013 0755 capabilities=0x800000 # CAP_SYS_NICE
diff --git a/build/apex/canned_fs_config_sys_nice b/build/apex/canned_fs_config_sys_nice
deleted file mode 100644
index 90c9747..0000000
--- a/build/apex/canned_fs_config_sys_nice
+++ /dev/null
@@ -1,3 +0,0 @@
-/bin/virtualizationservice 0 2000 0755 capabilities=0x1000001 # CAP_CHOWN, CAP_SYS_RESOURCE
-/bin/crosvm 0 3013 0755 capabilities=0x800000 # CAP_SYS_NICE
-/bin/virtmgr 0 3013 0755 capabilities=0x800000 # CAP_SYS_NICE
diff --git a/build/apex/manifest.json b/build/apex/manifest.json
index e596ce1..9be2aa6 100644
--- a/build/apex/manifest.json
+++ b/build/apex/manifest.json
@@ -1,6 +1,6 @@
{
"name": "com.android.virt",
- "version": 2,
+ "version": 3,
"requireNativeLibs": [
"libEGL.so",
"libGLESv2.so",
diff --git a/build/compos/manifest.json b/build/compos/manifest.json
index 7a07b1b..6d1f816 100644
--- a/build/compos/manifest.json
+++ b/build/compos/manifest.json
@@ -1,4 +1,4 @@
{
"name": "com.android.compos",
- "version": 2
+ "version": 3
}
diff --git a/build/debian/build.sh b/build/debian/build.sh
index 8c1345c..f751b30 100755
--- a/build/debian/build.sh
+++ b/build/debian/build.sh
@@ -15,6 +15,7 @@
echo "-a ARCH Architecture of the image [default is host arch: $(uname -m)]"
echo "-g Use Debian generic kernel [default is our custom kernel]"
echo "-r Release mode build"
+ echo "-u Set VM boot mode to u-boot [default is to load kernel directly]"
echo "-w Save temp work directory [for debugging]"
}
@@ -25,7 +26,7 @@
}
parse_options() {
- while getopts "a:ghrw" option; do
+ while getopts "a:ghruw" option; do
case ${option} in
h)
show_help ; exit
@@ -39,6 +40,9 @@
r)
mode=release
;;
+ u)
+ uboot=1
+ ;;
w)
save_workdir=1
;;
@@ -114,6 +118,13 @@
)
fi
+ if [[ "$uboot" != 1 ]]; then
+ packages+=(
+ libguestfs-tools
+ linux-image-generic
+ )
+ fi
+
if [[ "$use_generic_kernel" != 1 ]]; then
packages+=(
bc
@@ -312,6 +323,14 @@
}
run_fai() {
+ # NOTE: Prevent FAI from installing grub packages and running related scripts,
+ # if we are loading the kernel directly.
+ if [[ "$uboot" != 1 ]]; then
+ sed -i "/shim-signed/d ; /grub.*${debian_arch}.*/d" \
+ "${config_space}/package_config/${debian_arch^^}"
+ rm "${config_space}/scripts/SYSTEM_BOOT/20-grub"
+ fi
+
local out="${raw_disk_image}"
make -C "${debian_cloud_image}" "image_bookworm_nocloud_${debian_arch}"
mv "${debian_cloud_image}/image_bookworm_nocloud_${debian_arch}.raw" "${out}"
@@ -319,10 +338,14 @@
generate_output_package() {
fdisk -l "${raw_disk_image}"
- local vm_config="$SCRIPT_DIR/vm_config.json"
local root_partition_num=1
local efi_partition_num=15
+ local vm_config="$SCRIPT_DIR/vm_config.json"
+ if [[ "$uboot" == 1 ]]; then
+ vm_config="$SCRIPT_DIR/vm_config.u-boot.json"
+ fi
+
pushd ${workdir} > /dev/null
echo ${build_id} > build_id
@@ -341,8 +364,6 @@
sed -i "s/{root_part_guid}/$(sfdisk --part-uuid $raw_disk_image $root_partition_num)/g" vm_config.json
sed -i "s/{efi_part_guid}/$(sfdisk --part-uuid $raw_disk_image $efi_partition_num)/g" vm_config.json
- popd > /dev/null
-
contents=(
build_id
root_part
@@ -350,6 +371,19 @@
vm_config.json
)
+ if [[ "$uboot" != 1 ]]; then
+ rm -f vmlinuz* initrd.img*
+ virt-get-kernel -a "${raw_disk_image}"
+ mv vmlinuz* vmlinuz
+ mv initrd.img* initrd.img
+ contents+=(
+ vmlinuz
+ initrd.img
+ )
+ fi
+
+ popd > /dev/null
+
# --sparse option isn't supported in apache-commons-compress
tar czv -f ${output} -C ${workdir} "${contents[@]}"
}
@@ -373,6 +407,7 @@
mode=debug
save_workdir=0
use_generic_kernel=0
+uboot=0
parse_options "$@"
check_sudo
diff --git a/build/debian/build_in_container.sh b/build/debian/build_in_container.sh
index 739d2dd..82098ed 100755
--- a/build/debian/build_in_container.sh
+++ b/build/debian/build_in_container.sh
@@ -9,6 +9,7 @@
echo "-g Use Debian generic kernel [default is our custom kernel]"
echo "-r Release mode build"
echo "-s Leave a shell open [default: only if the build fails]"
+ echo "-u Set VM boot mode to u-boot [default is to load kernel directly]"
echo "-w Save temp work directory in the container [for debugging]"
}
@@ -17,8 +18,9 @@
release_flag=
save_workdir_flag=
shell_condition="||"
+uboot_flag=
-while getopts "a:ghrsw" option; do
+while getopts "a:ghrsuw" option; do
case ${option} in
a)
arch="$OPTARG"
@@ -35,6 +37,9 @@
s)
shell_condition=";"
;;
+ u)
+ uboot_flag="-u"
+ ;;
w)
save_workdir_flag="-w"
;;
@@ -58,4 +63,4 @@
-v "$ANDROID_BUILD_TOP/packages/modules/Virtualization:/root/Virtualization" \
--workdir /root/Virtualization/build/debian \
ubuntu:22.04 \
- bash -c "./build.sh -a $arch $release_flag $kernel_flag $save_workdir_flag $shell_condition bash"
+ bash -c "./build.sh -a $arch $release_flag $kernel_flag $uboot_flag $save_workdir_flag $shell_condition bash"
diff --git a/build/debian/fai_config/files/etc/systemd/zram-generator.conf/AVF b/build/debian/fai_config/files/etc/systemd/zram-generator.conf/AVF
new file mode 100644
index 0000000..43bd7e3
--- /dev/null
+++ b/build/debian/fai_config/files/etc/systemd/zram-generator.conf/AVF
@@ -0,0 +1,4 @@
+[zram0]
+zram-size = ram / 4
+
+compression-algorithm = zstd
diff --git a/build/debian/fai_config/package_config/AVF b/build/debian/fai_config/package_config/AVF
index f1ee065..c77ffcf 100644
--- a/build/debian/fai_config/package_config/AVF
+++ b/build/debian/fai_config/package_config/AVF
@@ -15,3 +15,4 @@
libvulkan1
vulkan-tools
pulseaudio
+systemd-zram-generator
diff --git a/build/debian/vm_config.json b/build/debian/vm_config.json
index 463583f..e9b3763 100644
--- a/build/debian/vm_config.json
+++ b/build/debian/vm_config.json
@@ -27,6 +27,9 @@
"sharedPath": "$APP_DATA_DIR/files"
}
],
+ "kernel": "$PAYLOAD_DIR/vmlinuz",
+ "initrd": "$PAYLOAD_DIR/initrd.img",
+ "params": "root=/dev/vda1",
"protected": false,
"cpu_topology": "match_host",
"platform_version": "~1.0",
diff --git a/build/debian/vm_config.u-boot.json b/build/debian/vm_config.u-boot.json
new file mode 100644
index 0000000..463583f
--- /dev/null
+++ b/build/debian/vm_config.u-boot.json
@@ -0,0 +1,42 @@
+{
+ "name": "debian",
+ "disks": [
+ {
+ "partitions": [
+ {
+ "label": "ROOT",
+ "path": "$PAYLOAD_DIR/root_part",
+ "writable": true,
+ "guid": "{root_part_guid}"
+ },
+ {
+ "label": "EFI",
+ "path": "$PAYLOAD_DIR/efi_part",
+ "writable": false,
+ "guid": "{efi_part_guid}"
+ }
+ ],
+ "writable": true
+ }
+ ],
+ "sharedPath": [
+ {
+ "sharedPath": "/storage/emulated"
+ },
+ {
+ "sharedPath": "$APP_DATA_DIR/files"
+ }
+ ],
+ "protected": false,
+ "cpu_topology": "match_host",
+ "platform_version": "~1.0",
+ "memory_mib": 4096,
+ "debuggable": true,
+ "console_out": true,
+ "console_input_device": "ttyS0",
+ "network": true,
+ "auto_memory_balloon": true,
+ "gpu": {
+ "backend": "2d"
+ }
+}
diff --git a/build/microdroid/Android.bp b/build/microdroid/Android.bp
index 10b492b..fac212a 100644
--- a/build/microdroid/Android.bp
+++ b/build/microdroid/Android.bp
@@ -476,19 +476,6 @@
src: ":microdroid_16k_initrd_debuggable",
}
-soong_config_module_type {
- name: "flag_aware_avb_add_hash_footer_defaults",
- module_type: "avb_add_hash_footer_defaults",
- config_namespace: "ANDROID",
- bool_variables: [
- "release_avf_enable_llpvm_changes",
- ],
- properties: [
- "rollback_index",
- "props",
- ],
-}
-
avb_add_hash_footer_defaults {
name: "microdroid_kernel_signed_defaults",
src: ":empty_file",
@@ -506,46 +493,29 @@
},
}
-MICRODROID_GKI_ROLLBACK_INDEX = 1
+MICRODROID_GKI_ROLLBACK_INDEX = 2
-flag_aware_avb_add_hash_footer_defaults {
+avb_add_hash_footer_defaults {
name: "microdroid_kernel_cap_defaults",
// Below are properties that are conditionally set depending on value of build flags.
- soong_config_variables: {
- release_avf_enable_llpvm_changes: {
- rollback_index: MICRODROID_GKI_ROLLBACK_INDEX,
- props: [
- {
- name: "com.android.virt.cap",
- value: "secretkeeper_protection",
- },
- ],
+ props: [
+ {
+ name: "com.android.virt.cap",
+ value: "secretkeeper_protection",
},
- },
+ ],
+ rollback_index: MICRODROID_GKI_ROLLBACK_INDEX,
}
-flag_aware_avb_add_hash_footer_defaults {
+avb_add_hash_footer_defaults {
name: "microdroid_kernel_cap_with_uefi_defaults",
- // Below are properties that are conditionally set depending on value of build flags.
- soong_config_variables: {
- release_avf_enable_llpvm_changes: {
- rollback_index: MICRODROID_GKI_ROLLBACK_INDEX,
- props: [
- {
- name: "com.android.virt.cap",
- value: "secretkeeper_protection|supports_uefi_boot",
- },
- ],
- conditions_default: {
- props: [
- {
- name: "com.android.virt.cap",
- value: "supports_uefi_boot",
- },
- ],
- },
+ rollback_index: MICRODROID_GKI_ROLLBACK_INDEX,
+ props: [
+ {
+ name: "com.android.virt.cap",
+ value: "secretkeeper_protection|supports_uefi_boot",
},
- },
+ ],
}
avb_add_hash_footer {
diff --git a/guest/pvmfw/Android.bp b/guest/pvmfw/Android.bp
index 6f113c8..cd32f8f 100644
--- a/guest/pvmfw/Android.bp
+++ b/guest/pvmfw/Android.bp
@@ -113,13 +113,15 @@
rust_test {
name: "libpvmfw.dice.test",
- srcs: ["src/dice.rs"],
+ srcs: ["src/dice/mod.rs"],
defaults: ["libpvmfw.test.defaults"],
rustlibs: [
"libcbor_util",
"libciborium",
+ "libcoset_nostd",
"libdiced_open_dice_nostd",
"libhwtrust",
+ "liblog_rust",
"libpvmfw_avb_nostd",
"libdiced_sample_inputs_nostd",
"libzerocopy_nostd",
diff --git a/guest/pvmfw/README.md b/guest/pvmfw/README.md
index c7f3dd6..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
@@ -510,12 +521,12 @@
and its configuration data.
As a quick prototyping solution, a valid DICE chain (such as this [test
-file][bcc.dat]) can be appended to the `pvmfw.bin` image with `pvmfw-tool`.
+file][dice.dat]) can be appended to the `pvmfw.bin` image with `pvmfw-tool`.
```shell
m pvmfw-tool pvmfw_bin
PVMFW_BIN=${ANDROID_PRODUCT_OUT}/system/etc/pvmfw.bin
-DICE=${ANDROID_BUILD_TOP}/packages/modules/Virtualization/tests/pvmfw/assets/bcc.dat
+DICE=${ANDROID_BUILD_TOP}/packages/modules/Virtualization/tests/pvmfw/assets/dice.dat
pvmfw-tool custom_pvmfw ${PVMFW_BIN} ${DICE}
```
@@ -537,7 +548,7 @@
Note: `adb root` is required to set the system property.
-[bcc.dat]: https://cs.android.com/android/platform/superproject/main/+/main:packages/modules/Virtualization/tests/pvmfw/assets/bcc.dat
+[dice.dat]: https://cs.android.com/android/platform/superproject/main/+/main:packages/modules/Virtualization/tests/pvmfw/assets/dice.dat
### Running pVM without pvmfw
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..843cca9 100644
--- a/guest/pvmfw/avb/tests/utils.rs
+++ b/guest/pvmfw/avb/tests/utils.rs
@@ -133,7 +133,9 @@
initrd_digest,
public_key: &public_key,
capabilities,
- rollback_index: 1,
+ // TODO(b/392081737): Capture expected rollback_index from build variables as we
+ // intend on auto-syncing rollback_index with security patch timestamps
+ rollback_index: 2,
page_size,
name: None,
};
@@ -148,6 +150,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 +171,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/arch/aarch64/payload.rs b/guest/pvmfw/src/arch/aarch64/payload.rs
index 0da8297..77e9a31 100644
--- a/guest/pvmfw/src/arch/aarch64/payload.rs
+++ b/guest/pvmfw/src/arch/aarch64/payload.rs
@@ -23,13 +23,10 @@
/// Function boot payload after cleaning all secret from pvmfw memory
pub fn jump_to_payload(entrypoint: usize, slices: &MemorySlices) -> ! {
let fdt_address = slices.fdt.as_ptr() as usize;
- let bcc = slices
- .dice_chain
- .map(|slice| {
- let r = slice.as_ptr_range();
- (r.start as usize)..(r.end as usize)
- })
- .expect("Missing DICE chain");
+ let dice_handover = slices.dice_handover.map(|slice| {
+ let r = slice.as_ptr_range();
+ (r.start as usize)..(r.end as usize)
+ });
deactivate_dynamic_page_tables();
@@ -50,9 +47,14 @@
assert_eq!(scratch.start.0 % ASM_STP_ALIGN, 0, "scratch memory is misaligned.");
assert_eq!(scratch.end.0 % ASM_STP_ALIGN, 0, "scratch memory is misaligned.");
- assert!(bcc.is_within(&(scratch.start.0..scratch.end.0)));
- assert_eq!(bcc.start % ASM_STP_ALIGN, 0, "Misaligned guest BCC.");
- assert_eq!(bcc.end % ASM_STP_ALIGN, 0, "Misaligned guest BCC.");
+ // A sub-region of the scratch memory might contain data for the next stage so skip zeroing it.
+ // Alternatively, an empty region at the start of the scratch region is compatible with the ASM
+ // implementation and results in the whole scratch region being zeroed.
+ let skipped = dice_handover.unwrap_or(scratch.start.0..scratch.start.0);
+
+ assert!(skipped.is_within(&(scratch.start.0..scratch.end.0)));
+ assert_eq!(skipped.start % ASM_STP_ALIGN, 0, "Misaligned skipped region.");
+ assert_eq!(skipped.end % ASM_STP_ALIGN, 0, "Misaligned skipped region.");
let stack = layout::stack_range();
@@ -73,27 +75,22 @@
// SAFETY: We're exiting pvmfw by passing the register values we need to a noreturn asm!().
unsafe {
asm!(
- "cmp {scratch}, {bcc}",
- "b.hs 1f",
-
- // Zero .data & .bss until BCC.
+ // Zero .data & .bss until the start of the skipped region.
+ "b 1f",
"0: stp xzr, xzr, [{scratch}], 16",
- "cmp {scratch}, {bcc}",
+ "1: cmp {scratch}, {skipped}",
"b.lo 0b",
- "1:",
- // Skip BCC.
- "mov {scratch}, {bcc_end}",
- "cmp {scratch}, {scratch_end}",
- "b.hs 1f",
+ // Skip the skipped region.
+ "mov {scratch}, {skipped_end}",
// Keep zeroing .data & .bss.
+ "b 1f",
"0: stp xzr, xzr, [{scratch}], 16",
- "cmp {scratch}, {scratch_end}",
+ "1: cmp {scratch}, {scratch_end}",
"b.lo 0b",
- "1:",
- // Flush d-cache over .data & .bss (including BCC).
+ // Flush d-cache over .data & .bss (including skipped region).
"0: dc cvau, {cache_line}",
"add {cache_line}, {cache_line}, {dcache_line_size}",
"cmp {cache_line}, {scratch_end}",
@@ -159,8 +156,8 @@
"dsb nsh",
"br x30",
sctlr_el1_val = in(reg) SCTLR_EL1_VAL,
- bcc = in(reg) u64::try_from(bcc.start).unwrap(),
- bcc_end = in(reg) u64::try_from(bcc.end).unwrap(),
+ skipped = in(reg) u64::try_from(skipped.start).unwrap(),
+ skipped_end = in(reg) u64::try_from(skipped.end).unwrap(),
cache_line = in(reg) u64::try_from(scratch.start.0).unwrap(),
scratch = in(reg) u64::try_from(scratch.start.0).unwrap(),
scratch_end = in(reg) u64::try_from(scratch.end.0).unwrap(),
diff --git a/guest/pvmfw/src/config.rs b/guest/pvmfw/src/config.rs
index dbfde15..a16da35 100644
--- a/guest/pvmfw/src/config.rs
+++ b/guest/pvmfw/src/config.rs
@@ -124,7 +124,7 @@
#[derive(Clone, Copy, Debug)]
pub enum Entry {
- Bcc,
+ DiceHandover,
DebugPolicy,
VmDtbo,
VmBaseDtbo,
@@ -136,12 +136,12 @@
const COUNT: usize = Self::_VARIANT_COUNT as usize;
const ALL_ENTRIES: [Entry; Self::COUNT] =
- [Self::Bcc, Self::DebugPolicy, Self::VmDtbo, Self::VmBaseDtbo];
+ [Self::DiceHandover, Self::DebugPolicy, Self::VmDtbo, Self::VmBaseDtbo];
}
#[derive(Default)]
pub struct Entries<'a> {
- pub bcc: &'a mut [u8],
+ pub dice_handover: Option<&'a mut [u8]>,
pub debug_policy: Option<&'a [u8]>,
pub vm_dtbo: Option<&'a mut [u8]>,
pub vm_ref_dt: Option<&'a [u8]>,
@@ -269,8 +269,8 @@
entry_size,
);
}
- // Ensures that BCC exists.
- ranges[Entry::Bcc as usize].ok_or(Error::MissingEntry(Entry::Bcc))?;
+ // Ensures that the DICE handover is present.
+ ranges[Entry::DiceHandover as usize].ok_or(Error::MissingEntry(Entry::DiceHandover))?;
Ok(Self { body, ranges })
}
@@ -293,15 +293,12 @@
entries[i] = Some(chunk);
}
}
- let [bcc, debug_policy, vm_dtbo, vm_ref_dt] = entries;
-
- // The platform BCC has always been required.
- let bcc = bcc.unwrap();
+ let [dice_handover, debug_policy, vm_dtbo, vm_ref_dt] = entries;
// We have no reason to mutate so drop the `mut`.
let debug_policy = debug_policy.map(|x| &*x);
let vm_ref_dt = vm_ref_dt.map(|x| &*x);
- Entries { bcc, debug_policy, vm_dtbo, vm_ref_dt }
+ Entries { dice_handover, debug_policy, vm_dtbo, vm_ref_dt }
}
}
diff --git a/guest/pvmfw/src/device_assignment.rs b/guest/pvmfw/src/device_assignment.rs
index fb485fe..ba13fa3 100644
--- a/guest/pvmfw/src/device_assignment.rs
+++ b/guest/pvmfw/src/device_assignment.rs
@@ -373,10 +373,12 @@
// see: DeviceAssignmentInfo::validate_all_regs().
let mut all_iommus = BTreeSet::new();
for physical_device in physical_devices.values() {
- for iommu in &physical_device.iommus {
- if !all_iommus.insert(iommu) {
- error!("Unsupported phys IOMMU duplication found, <iommus> = {iommu:?}");
- return Err(DeviceAssignmentError::UnsupportedIommusDuplication);
+ if let Some(iommus) = &physical_device.iommus {
+ for iommu in iommus {
+ if !all_iommus.insert(iommu) {
+ error!("Unsupported phys IOMMU duplication found, <iommus> = {iommu:?}");
+ return Err(DeviceAssignmentError::UnsupportedIommusDuplication);
+ }
}
}
}
@@ -692,17 +694,17 @@
struct PhysicalDeviceInfo {
target: Phandle,
reg: Vec<DeviceReg>,
- iommus: Vec<(PhysIommu, Sid)>,
+ iommus: Option<Vec<(PhysIommu, Sid)>>,
}
impl PhysicalDeviceInfo {
fn parse_iommus(
node: &FdtNode,
phys_iommus: &BTreeMap<Phandle, PhysIommu>,
- ) -> Result<Vec<(PhysIommu, Sid)>> {
+ ) -> Result<Option<Vec<(PhysIommu, Sid)>>> {
let mut iommus = vec![];
let Some(mut cells) = node.getprop_cells(c"iommus")? else {
- return Ok(iommus);
+ return Ok(None);
};
while let Some(cell) = cells.next() {
// Parse pIOMMU ID
@@ -717,7 +719,7 @@
iommus.push((*iommu, Sid::from(cell)));
}
- Ok(iommus)
+ Ok(Some(iommus))
}
fn parse(node: &FdtNode, phys_iommus: &BTreeMap<Phandle, PhysIommu>) -> Result<Option<Self>> {
@@ -740,9 +742,9 @@
// <reg> property from the crosvm DT
reg: Vec<DeviceReg>,
// <interrupts> property from the crosvm DT
- interrupts: Vec<u8>,
+ interrupts: Option<Vec<u8>>,
// Parsed <iommus> property from the crosvm DT. Tuple of PvIommu and vSID.
- iommus: Vec<(PvIommu, Vsid)>,
+ iommus: Option<Vec<(PvIommu, Vsid)>>,
}
impl AssignedDeviceInfo {
@@ -794,19 +796,18 @@
Ok(())
}
- fn parse_interrupts(node: &FdtNode) -> Result<Vec<u8>> {
+ fn parse_interrupts(node: &FdtNode) -> Result<Option<Vec<u8>>> {
+ let Some(cells) = node.getprop_cells(c"interrupts")? else {
+ return Ok(None);
+ };
// Validation: Validate if interrupts cell numbers are multiple of #interrupt-cells.
// We can't know how many interrupts would exist.
- let interrupts_cells = node
- .getprop_cells(c"interrupts")?
- .ok_or(DeviceAssignmentError::InvalidInterrupts)?
- .count();
- if interrupts_cells % CELLS_PER_INTERRUPT != 0 {
+ if cells.count() % CELLS_PER_INTERRUPT != 0 {
return Err(DeviceAssignmentError::InvalidInterrupts);
}
// Once validated, keep the raw bytes so patch can be done with setprop()
- Ok(node.getprop(c"interrupts").unwrap().unwrap().into())
+ Ok(Some(node.getprop(c"interrupts").unwrap().unwrap().into()))
}
// TODO(b/277993056): Also validate /__local_fixups__ to ensure that <iommus> has phandle.
@@ -895,8 +896,16 @@
let interrupts = Self::parse_interrupts(&node)?;
- let iommus = Self::parse_iommus(&node, pviommus)?;
- Self::validate_iommus(&iommus, &physical_device.iommus, hypervisor)?;
+ // Ignore <iommus> if no pvIOMMUs are expected based on the VM DTBO, possibly
+ // because physical IOMMUs are being assigned directly.
+ let iommus = if let Some(iommus) = &physical_device.iommus {
+ let parsed_iommus = Self::parse_iommus(&node, pviommus)?;
+ Self::validate_iommus(&parsed_iommus, iommus, hypervisor)?;
+ Some(parsed_iommus)
+ } else {
+ // TODO: Detect misconfigured iommus in input DT.
+ None
+ };
Ok(Some(Self { node_path, reg, interrupts, iommus }))
}
@@ -904,14 +913,21 @@
fn patch(&self, fdt: &mut Fdt, pviommu_phandles: &BTreeMap<PvIommu, Phandle>) -> Result<()> {
let mut dst = fdt.node_mut(&self.node_path)?.unwrap();
dst.setprop(c"reg", &to_be_bytes(&self.reg))?;
- dst.setprop(c"interrupts", &self.interrupts)?;
- let mut iommus = Vec::with_capacity(8 * self.iommus.len());
- for (pviommu, vsid) in &self.iommus {
- let phandle = pviommu_phandles.get(pviommu).unwrap();
- iommus.extend_from_slice(&u32::from(*phandle).to_be_bytes());
- iommus.extend_from_slice(&vsid.0.to_be_bytes());
+ if let Some(interrupts) = &self.interrupts {
+ dst.setprop(c"interrupts", interrupts)?;
+ } else {
+ dst.nop_property(c"interrupts")?;
}
- dst.setprop(c"iommus", &iommus)?;
+
+ if let Some(iommus) = &self.iommus {
+ let mut iommus_vec = Vec::with_capacity(8 * iommus.len());
+ for (pviommu, vsid) in iommus {
+ let phandle = pviommu_phandles.get(pviommu).unwrap();
+ iommus_vec.extend_from_slice(&u32::from(*phandle).to_be_bytes());
+ iommus_vec.extend_from_slice(&vsid.0.to_be_bytes());
+ }
+ dst.setprop(c"iommus", &iommus_vec)?;
+ }
Ok(())
}
@@ -946,10 +962,12 @@
fn validate_pviommu_topology(assigned_devices: &[AssignedDeviceInfo]) -> Result<()> {
let mut all_iommus = BTreeSet::new();
for assigned_device in assigned_devices {
- for iommu in &assigned_device.iommus {
- if !all_iommus.insert(iommu) {
- error!("Unsupported pvIOMMU duplication found, <iommus> = {iommu:?}");
- return Err(DeviceAssignmentError::UnsupportedPvIommusDuplication);
+ if let Some(iommus) = &assigned_device.iommus {
+ for iommu in iommus {
+ if !all_iommus.insert(iommu) {
+ error!("Unsupported pvIOMMU duplication found, <iommus> = {iommu:?}");
+ return Err(DeviceAssignmentError::UnsupportedPvIommusDuplication);
+ }
}
}
}
@@ -1282,6 +1300,8 @@
// TODO(ptosi): Add tests with varying HYP_GRANULE values.
+ // TODO(ptosi): Add tests with iommus.is_none()
+
#[test]
fn device_info_new_without_symbols() {
let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
@@ -1328,8 +1348,8 @@
let expected = [AssignedDeviceInfo {
node_path: CString::new("/bus0/backlight").unwrap(),
reg: vec![[0x9, 0xFF].into()],
- interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
- iommus: vec![],
+ interrupts: Some(into_fdt_prop(vec![0x0, 0xF, 0x4])),
+ iommus: None,
}];
assert_eq!(device_info.assigned_devices, expected);
@@ -1353,8 +1373,8 @@
let expected = [AssignedDeviceInfo {
node_path: CString::new("/rng").unwrap(),
reg: vec![[0x9, 0xFF].into()],
- interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
- iommus: vec![(PvIommu { id: 0x4 }, Vsid(0xFF0))],
+ interrupts: Some(into_fdt_prop(vec![0x0, 0xF, 0x4])),
+ iommus: Some(vec![(PvIommu { id: 0x4 }, Vsid(0xFF0))]),
}];
assert_eq!(device_info.assigned_devices, expected);
@@ -1435,7 +1455,6 @@
(Ok(c"android,backlight,ignore-gctrl-reset"), Ok(Vec::new())),
(Ok(c"compatible"), Ok(Vec::from(*b"android,backlight\0"))),
(Ok(c"interrupts"), Ok(into_fdt_prop(vec![0x0, 0xF, 0x4]))),
- (Ok(c"iommus"), Ok(Vec::new())),
(Ok(c"phandle"), Ok(into_fdt_prop(vec![phandle.unwrap()]))),
(Ok(c"reg"), Ok(into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]))),
];
diff --git a/guest/pvmfw/src/bcc.rs b/guest/pvmfw/src/dice/chain.rs
similarity index 71%
rename from guest/pvmfw/src/bcc.rs
rename to guest/pvmfw/src/dice/chain.rs
index 9260d7f..c8353fa 100644
--- a/guest/pvmfw/src/bcc.rs
+++ b/guest/pvmfw/src/dice/chain.rs
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! Code to inspect/manipulate the BCC (DICE Chain) we receive from our loader (the hypervisor).
+//! Code to inspect/manipulate the DICE Chain we receive from our loader.
// TODO(b/279910232): Unify this, somehow, with the similar but different code in hwtrust.
@@ -25,56 +25,58 @@
use diced_open_dice::{BccHandover, Cdi, DiceArtifacts, DiceMode};
use log::trace;
-type Result<T> = core::result::Result<T, BccError>;
+type Result<T> = core::result::Result<T, DiceChainError>;
-pub enum BccError {
+pub enum DiceChainError {
CborDecodeError,
CborEncodeError,
CosetError(coset::CoseError),
DiceError(diced_open_dice::DiceError),
- MalformedBcc(&'static str),
- MissingBcc,
+ Malformed(&'static str),
+ Missing,
}
-impl From<coset::CoseError> for BccError {
+impl From<coset::CoseError> for DiceChainError {
fn from(e: coset::CoseError) -> Self {
Self::CosetError(e)
}
}
-impl fmt::Display for BccError {
+impl fmt::Display for DiceChainError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
- Self::CborDecodeError => write!(f, "Error parsing BCC CBOR"),
- Self::CborEncodeError => write!(f, "Error encoding BCC CBOR"),
+ Self::CborDecodeError => write!(f, "Error parsing DICE chain CBOR"),
+ Self::CborEncodeError => write!(f, "Error encoding DICE chain CBOR"),
Self::CosetError(e) => write!(f, "Encountered an error with coset: {e}"),
Self::DiceError(e) => write!(f, "Dice error: {e:?}"),
- Self::MalformedBcc(s) => {
- write!(f, "BCC does not have the expected CBOR structure: {s}")
+ Self::Malformed(s) => {
+ write!(f, "DICE chain does not have the expected CBOR structure: {s}")
}
- Self::MissingBcc => write!(f, "Missing BCC"),
+ Self::Missing => write!(f, "Missing DICE chain"),
}
}
}
/// Return a new CBOR encoded BccHandover that is based on the incoming CDIs but does not chain
-/// from the received BCC.
-pub fn truncate(bcc_handover: BccHandover) -> Result<Vec<u8>> {
+/// from the received DICE chain.
+#[cfg_attr(test, allow(dead_code))]
+pub fn truncate(handover: BccHandover) -> Result<Vec<u8>> {
// Note: The strings here are deliberately different from those used in a normal DICE handover
// because we want this to not be equivalent to any valid DICE derivation.
- let cdi_seal = taint_cdi(bcc_handover.cdi_seal(), "TaintCdiSeal")?;
- let cdi_attest = taint_cdi(bcc_handover.cdi_attest(), "TaintCdiAttest")?;
+ let cdi_seal = taint_cdi(handover.cdi_seal(), "TaintCdiSeal")?;
+ let cdi_attest = taint_cdi(handover.cdi_attest(), "TaintCdiAttest")?;
// BccHandover = {
// 1 : bstr .size 32, ; CDI_Attest
// 2 : bstr .size 32, ; CDI_Seal
// ? 3 : Bcc, ; Certificate chain
// }
- let bcc_handover: Vec<(Value, Value)> =
+ let handover: Vec<(Value, Value)> =
vec![(1.into(), cdi_attest.as_slice().into()), (2.into(), cdi_seal.as_slice().into())];
- cbor_util::serialize(&bcc_handover).map_err(|_| BccError::CborEncodeError)
+ cbor_util::serialize(&handover).map_err(|_| DiceChainError::CborEncodeError)
}
+#[cfg_attr(test, allow(dead_code))]
fn taint_cdi(cdi: &Cdi, info: &str) -> Result<Cdi> {
// An arbitrary value generated randomly.
const SALT: [u8; 64] = [
@@ -86,44 +88,39 @@
];
let mut result = [0u8; size_of::<Cdi>()];
diced_open_dice::kdf(cdi.as_slice(), &SALT, info.as_bytes(), result.as_mut_slice())
- .map_err(BccError::DiceError)?;
+ .map_err(DiceChainError::DiceError)?;
Ok(result)
}
-/// Represents a (partially) decoded BCC DICE chain.
-pub struct Bcc {
+/// Represents a (partially) decoded DICE chain.
+pub struct DiceChainInfo {
is_debug_mode: bool,
leaf_subject_pubkey: PublicKey,
}
-impl Bcc {
- /// Returns whether any node in the received DICE chain is marked as debug (and hence is not
- /// secure).
- pub fn new(received_bcc: Option<&[u8]>) -> Result<Bcc> {
- let received_bcc = received_bcc.unwrap_or(&[]);
- if received_bcc.is_empty() {
- return Err(BccError::MissingBcc);
- }
+impl DiceChainInfo {
+ pub fn new(handover: Option<&[u8]>) -> Result<Self> {
+ let handover = handover.filter(|h| !h.is_empty()).ok_or(DiceChainError::Missing)?;
- // We don't attempt to fully validate the BCC (e.g. we don't check the signatures) - we
- // have to trust our loader. But if it's invalid CBOR or otherwise clearly ill-formed,
+ // We don't attempt to fully validate the DICE chain (e.g. we don't check the signatures) -
+ // we have to trust our loader. But if it's invalid CBOR or otherwise clearly ill-formed,
// something is very wrong, so we fail.
- let bcc_cbor =
- cbor_util::deserialize(received_bcc).map_err(|_| BccError::CborDecodeError)?;
+ let handover_cbor =
+ cbor_util::deserialize(handover).map_err(|_| DiceChainError::CborDecodeError)?;
// Bcc = [
// PubKeyEd25519 / PubKeyECDSA256, // DK_pub
// + BccEntry, // Root -> leaf (KM_pub)
// ]
- let bcc = match bcc_cbor {
+ let dice_chain = match handover_cbor {
Value::Array(v) if v.len() >= 2 => v,
- _ => return Err(BccError::MalformedBcc("Invalid top level value")),
+ _ => return Err(DiceChainError::Malformed("Invalid top level value")),
};
// Decode all the DICE payloads to make sure they are well-formed.
- let payloads = bcc
+ let payloads = dice_chain
.into_iter()
.skip(1)
- .map(|v| BccEntry::new(v).payload())
+ .map(|v| DiceChainEntry::new(v).payload())
.collect::<Result<Vec<_>>>()?;
let is_debug_mode = is_any_payload_debug_mode(&payloads)?;
@@ -132,6 +129,8 @@
Ok(Self { is_debug_mode, leaf_subject_pubkey })
}
+ /// Returns whether any node in the received DICE chain is marked as debug (and hence is not
+ /// secure).
pub fn is_debug_mode(&self) -> bool {
self.is_debug_mode
}
@@ -141,7 +140,7 @@
}
}
-fn is_any_payload_debug_mode(payloads: &[BccPayload]) -> Result<bool> {
+fn is_any_payload_debug_mode(payloads: &[DiceChainEntryPayload]) -> Result<bool> {
// Check if any payload in the chain is marked as Debug mode, which means the device is not
// secure. (Normal means it is a secure boot, for that stage at least; we ignore recovery
// & not configured /invalid values, since it's not clear what they would mean in this
@@ -155,10 +154,7 @@
}
#[repr(transparent)]
-struct BccEntry(Value);
-
-#[repr(transparent)]
-struct BccPayload(Value);
+struct DiceChainEntry(Value);
#[derive(Debug, Clone)]
pub struct PublicKey {
@@ -167,12 +163,12 @@
pub cose_alg: iana::Algorithm,
}
-impl BccEntry {
+impl DiceChainEntry {
pub fn new(entry: Value) -> Self {
Self(entry)
}
- pub fn payload(&self) -> Result<BccPayload> {
+ pub fn payload(&self) -> Result<DiceChainEntryPayload> {
// BccEntry = [ // COSE_Sign1 (untagged)
// protected : bstr .cbor {
// 1 : AlgorithmEdDSA / AlgorithmES256, // Algorithm
@@ -183,11 +179,13 @@
// // ECDSA(SigningKey, bstr .cbor BccEntryInput)
// // See RFC 8032 for details of how to encode the signature value for Ed25519.
// ]
+ let payload = self
+ .payload_bytes()
+ .ok_or(DiceChainError::Malformed("Invalid DiceChainEntryPayload"))?;
let payload =
- self.payload_bytes().ok_or(BccError::MalformedBcc("Invalid payload in BccEntry"))?;
- let payload = cbor_util::deserialize(payload).map_err(|_| BccError::CborDecodeError)?;
- trace!("Bcc payload: {payload:?}");
- Ok(BccPayload(payload))
+ cbor_util::deserialize(payload).map_err(|_| DiceChainError::CborDecodeError)?;
+ trace!("DiceChainEntryPayload: {payload:?}");
+ Ok(DiceChainEntryPayload(payload))
}
fn payload_bytes(&self) -> Option<&Vec<u8>> {
@@ -203,7 +201,10 @@
const MODE_DEBUG: u8 = DiceMode::kDiceModeDebug as u8;
const SUBJECT_PUBLIC_KEY: i32 = -4670552;
-impl BccPayload {
+#[repr(transparent)]
+struct DiceChainEntryPayload(Value);
+
+impl DiceChainEntryPayload {
pub fn is_debug_mode(&self) -> Result<bool> {
// BccPayload = { // CWT
// ...
@@ -219,11 +220,11 @@
// Profile for DICE spec.
let mode = if let Some(bytes) = value.as_bytes() {
if bytes.len() != 1 {
- return Err(BccError::MalformedBcc("Invalid mode bstr"));
+ return Err(DiceChainError::Malformed("Invalid mode bstr"));
}
bytes[0].into()
} else {
- value.as_integer().ok_or(BccError::MalformedBcc("Invalid type for mode"))?
+ value.as_integer().ok_or(DiceChainError::Malformed("Invalid type for mode"))?
};
Ok(mode == MODE_DEBUG.into())
}
@@ -237,9 +238,9 @@
// ...
// }
self.value_from_key(SUBJECT_PUBLIC_KEY)
- .ok_or(BccError::MalformedBcc("Subject public key missing"))?
+ .ok_or(DiceChainError::Malformed("Subject public key missing"))?
.as_bytes()
- .ok_or(BccError::MalformedBcc("Subject public key is not a byte string"))
+ .ok_or(DiceChainError::Malformed("Subject public key is not a byte string"))
.and_then(|v| PublicKey::from_slice(v))
}
@@ -262,7 +263,7 @@
fn from_slice(slice: &[u8]) -> Result<Self> {
let key = CoseKey::from_slice(slice)?;
let Some(Algorithm::Assigned(cose_alg)) = key.alg else {
- return Err(BccError::MalformedBcc("Invalid algorithm in public key"));
+ return Err(DiceChainError::Malformed("Invalid algorithm in public key"));
};
Ok(Self { cose_alg })
}
diff --git a/guest/pvmfw/src/dice.rs b/guest/pvmfw/src/dice/mod.rs
similarity index 78%
rename from guest/pvmfw/src/dice.rs
rename to guest/pvmfw/src/dice/mod.rs
index 49a3807..dc7b64e 100644
--- a/guest/pvmfw/src/dice.rs
+++ b/guest/pvmfw/src/dice/mod.rs
@@ -12,12 +12,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! Support for DICE derivation and BCC generation.
+//! Support for DICE derivation and DICE chain generation.
extern crate alloc;
+pub(crate) mod chain;
+
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
+pub use chain::DiceChainInfo;
use ciborium::cbor;
use ciborium::Value;
use core::mem::size_of;
@@ -84,11 +87,12 @@
pub mode: DiceMode,
pub security_version: u64,
pub rkp_vm_marker: bool,
+ pub instance_hash: Option<Hash>,
component_name: String,
}
impl PartialInputs {
- pub fn new(data: &VerifiedBootData) -> Result<Self> {
+ pub fn new(data: &VerifiedBootData, instance_hash: Option<Hash>) -> Result<Self> {
let code_hash = to_dice_hash(data)?;
let auth_hash = hash(data.public_key)?;
let mode = to_dice_mode(data.debug_level);
@@ -98,20 +102,27 @@
let rkp_vm_marker = data.has_capability(Capability::RemoteAttest)
|| data.has_capability(Capability::TrustySecurityVm);
- Ok(Self { code_hash, auth_hash, mode, security_version, rkp_vm_marker, component_name })
+ Ok(Self {
+ code_hash,
+ auth_hash,
+ mode,
+ security_version,
+ rkp_vm_marker,
+ instance_hash,
+ component_name,
+ })
}
- pub fn write_next_bcc(
+ pub fn write_next_handover(
self,
- current_bcc_handover: &[u8],
+ current_handover: &[u8],
salt: &[u8; HIDDEN_SIZE],
- instance_hash: Option<Hash>,
deferred_rollback_protection: bool,
- next_bcc: &mut [u8],
+ next_handover: &mut [u8],
context: DiceContext,
) -> Result<()> {
let config = self
- .generate_config_descriptor(instance_hash)
+ .generate_config_descriptor()
.map_err(|_| diced_open_dice::DiceError::InvalidInput)?;
let dice_inputs = InputValues::new(
@@ -121,7 +132,7 @@
self.mode,
self.make_hidden(salt, deferred_rollback_protection)?,
);
- let _ = bcc_handover_main_flow(current_bcc_handover, &dice_inputs, next_bcc, context)?;
+ let _ = bcc_handover_main_flow(current_handover, &dice_inputs, next_handover, context)?;
Ok(())
}
@@ -157,14 +168,14 @@
)
}
- fn generate_config_descriptor(&self, instance_hash: Option<Hash>) -> Result<Vec<u8>> {
+ fn generate_config_descriptor(&self) -> Result<Vec<u8>> {
let mut config = Vec::with_capacity(4);
config.push((cbor!(COMPONENT_NAME_KEY)?, cbor!(self.component_name.as_str())?));
config.push((cbor!(SECURITY_VERSION_KEY)?, cbor!(self.security_version)?));
if self.rkp_vm_marker {
config.push((cbor!(RKP_VM_MARKER_KEY)?, Value::Null))
}
- if let Some(instance_hash) = instance_hash {
+ if let Some(instance_hash) = self.instance_hash {
config.push((cbor!(INSTANCE_HASH_KEY)?, Value::from(instance_hash.as_slice())));
}
let config = Value::Map(config);
@@ -181,6 +192,7 @@
SECURITY_VERSION_KEY,
};
use ciborium::Value;
+ use diced_open_dice::bcc_handover_parse;
use diced_open_dice::DiceArtifacts;
use diced_open_dice::DiceContext;
use diced_open_dice::DiceMode;
@@ -213,7 +225,7 @@
#[test]
fn base_data_conversion() {
let vb_data = BASE_VB_DATA;
- let inputs = PartialInputs::new(&vb_data).unwrap();
+ let inputs = PartialInputs::new(&vb_data, None).unwrap();
assert_eq!(inputs.mode, DiceMode::kDiceModeNormal);
assert_eq!(inputs.security_version, 42);
@@ -225,7 +237,7 @@
#[test]
fn debuggable_conversion() {
let vb_data = VerifiedBootData { debug_level: DebugLevel::Full, ..BASE_VB_DATA };
- let inputs = PartialInputs::new(&vb_data).unwrap();
+ let inputs = PartialInputs::new(&vb_data, None).unwrap();
assert_eq!(inputs.mode, DiceMode::kDiceModeDebug);
}
@@ -234,7 +246,7 @@
fn rkp_vm_conversion() {
let vb_data =
VerifiedBootData { capabilities: vec![Capability::RemoteAttest], ..BASE_VB_DATA };
- let inputs = PartialInputs::new(&vb_data).unwrap();
+ let inputs = PartialInputs::new(&vb_data, None).unwrap();
assert!(inputs.rkp_vm_marker);
}
@@ -242,22 +254,23 @@
#[test]
fn base_config_descriptor() {
let vb_data = BASE_VB_DATA;
- let inputs = PartialInputs::new(&vb_data).unwrap();
- let config_map = decode_config_descriptor(&inputs, None);
+ let inputs = PartialInputs::new(&vb_data, None).unwrap();
+ let config_map = decode_config_descriptor(&inputs);
assert_eq!(config_map.get(&COMPONENT_NAME_KEY).unwrap().as_text().unwrap(), "vm_entry");
assert_eq!(config_map.get(&COMPONENT_VERSION_KEY), None);
assert_eq!(config_map.get(&RESETTABLE_KEY), None);
assert_eq!(config_map.get(&SECURITY_VERSION_KEY).unwrap().as_integer().unwrap(), 42.into());
assert_eq!(config_map.get(&RKP_VM_MARKER_KEY), None);
+ assert_eq!(config_map.get(&INSTANCE_HASH_KEY), None);
}
#[test]
fn rkp_vm_config_descriptor_has_rkp_vm_marker_and_component_name() {
let vb_data =
VerifiedBootData { capabilities: vec![Capability::RemoteAttest], ..BASE_VB_DATA };
- let inputs = PartialInputs::new(&vb_data).unwrap();
- let config_map = decode_config_descriptor(&inputs, Some(HASH));
+ let inputs = PartialInputs::new(&vb_data, Some(HASH)).unwrap();
+ let config_map = decode_config_descriptor(&inputs);
assert_eq!(config_map.get(&COMPONENT_NAME_KEY).unwrap().as_text().unwrap(), "vm_entry");
assert!(config_map.get(&RKP_VM_MARKER_KEY).unwrap().is_null());
@@ -267,8 +280,8 @@
fn security_vm_config_descriptor_has_rkp_vm_marker() {
let vb_data =
VerifiedBootData { capabilities: vec![Capability::TrustySecurityVm], ..BASE_VB_DATA };
- let inputs = PartialInputs::new(&vb_data).unwrap();
- let config_map = decode_config_descriptor(&inputs, Some(HASH));
+ let inputs = PartialInputs::new(&vb_data, Some(HASH)).unwrap();
+ let config_map = decode_config_descriptor(&inputs);
assert!(config_map.get(&RKP_VM_MARKER_KEY).unwrap().is_null());
}
@@ -277,8 +290,8 @@
fn config_descriptor_with_instance_hash() {
let vb_data =
VerifiedBootData { capabilities: vec![Capability::RemoteAttest], ..BASE_VB_DATA };
- let inputs = PartialInputs::new(&vb_data).unwrap();
- let config_map = decode_config_descriptor(&inputs, Some(HASH));
+ let inputs = PartialInputs::new(&vb_data, Some(HASH)).unwrap();
+ let config_map = decode_config_descriptor(&inputs);
assert_eq!(*config_map.get(&INSTANCE_HASH_KEY).unwrap(), Value::from(HASH.as_slice()));
}
@@ -286,16 +299,13 @@
fn config_descriptor_without_instance_hash() {
let vb_data =
VerifiedBootData { capabilities: vec![Capability::RemoteAttest], ..BASE_VB_DATA };
- let inputs = PartialInputs::new(&vb_data).unwrap();
- let config_map = decode_config_descriptor(&inputs, None);
+ let inputs = PartialInputs::new(&vb_data, None).unwrap();
+ let config_map = decode_config_descriptor(&inputs);
assert!(!config_map.contains_key(&INSTANCE_HASH_KEY));
}
- fn decode_config_descriptor(
- inputs: &PartialInputs,
- instance_hash: Option<Hash>,
- ) -> HashMap<i64, Value> {
- let config_descriptor = inputs.generate_config_descriptor(instance_hash).unwrap();
+ fn decode_config_descriptor(inputs: &PartialInputs) -> HashMap<i64, Value> {
+ let config_descriptor = inputs.generate_config_descriptor().unwrap();
let cbor_map =
cbor_util::deserialize::<Value>(&config_descriptor).unwrap().into_map().unwrap();
@@ -309,7 +319,7 @@
#[test]
fn changing_deferred_rpb_changes_secrets() {
let vb_data = VerifiedBootData { debug_level: DebugLevel::Full, ..BASE_VB_DATA };
- let inputs = PartialInputs::new(&vb_data).unwrap();
+ let inputs = PartialInputs::new(&vb_data, Some([0u8; 64])).unwrap();
let mut buffer_without_defer = [0; 4096];
let mut buffer_with_defer = [0; 4096];
let mut buffer_without_defer_retry = [0; 4096];
@@ -334,62 +344,57 @@
inputs
.clone()
- .write_next_bcc(
+ .write_next_handover(
sample_dice_input,
&[0u8; HIDDEN_SIZE],
- Some([0u8; 64]),
false,
&mut buffer_without_defer,
context.clone(),
)
.unwrap();
- let bcc_handover1 = diced_open_dice::bcc_handover_parse(&buffer_without_defer).unwrap();
+ let handover1 = from_serialized_handover(&buffer_without_defer);
inputs
.clone()
- .write_next_bcc(
+ .write_next_handover(
sample_dice_input,
&[0u8; HIDDEN_SIZE],
- Some([0u8; 64]),
true,
&mut buffer_with_defer,
context.clone(),
)
.unwrap();
- let bcc_handover2 = diced_open_dice::bcc_handover_parse(&buffer_with_defer).unwrap();
+ let handover2 = from_serialized_handover(&buffer_with_defer);
inputs
.clone()
- .write_next_bcc(
+ .write_next_handover(
sample_dice_input,
&[0u8; HIDDEN_SIZE],
- Some([0u8; 64]),
false,
&mut buffer_without_defer_retry,
context.clone(),
)
.unwrap();
- let bcc_handover3 =
- diced_open_dice::bcc_handover_parse(&buffer_without_defer_retry).unwrap();
+ let handover3 = from_serialized_handover(&buffer_without_defer_retry);
- assert_ne!(bcc_handover1.cdi_seal(), bcc_handover2.cdi_seal());
- assert_eq!(bcc_handover1.cdi_seal(), bcc_handover3.cdi_seal());
+ assert_ne!(handover1.cdi_seal(), handover2.cdi_seal());
+ assert_eq!(handover1.cdi_seal(), handover3.cdi_seal());
}
#[test]
fn dice_derivation_with_different_algorithms_is_valid() {
let dice_artifacts = make_sample_bcc_and_cdis().unwrap();
- let bcc_handover0_bytes = to_bcc_handover(&dice_artifacts);
+ let handover0_bytes = to_serialized_handover(&dice_artifacts);
let vb_data = VerifiedBootData { debug_level: DebugLevel::Full, ..BASE_VB_DATA };
- let inputs = PartialInputs::new(&vb_data).unwrap();
+ let inputs = PartialInputs::new(&vb_data, Some([0u8; 64])).unwrap();
let mut buffer = [0; 4096];
inputs
.clone()
- .write_next_bcc(
- &bcc_handover0_bytes,
+ .write_next_handover(
+ &handover0_bytes,
&[0u8; HIDDEN_SIZE],
- Some([0u8; 64]),
true,
&mut buffer,
DiceContext {
@@ -397,17 +402,16 @@
subject_algorithm: KeyAlgorithm::EcdsaP256,
},
)
- .expect("Failed to derive Ed25519 -> EcdsaP256 BCC");
- let bcc_handover1 = diced_open_dice::bcc_handover_parse(&buffer).unwrap();
- let bcc_handover1_bytes = to_bcc_handover(&bcc_handover1);
+ .expect("Failed to derive Ed25519 -> EcdsaP256 DICE chain");
+ let handover1 = from_serialized_handover(&buffer);
+ let handover1_bytes = to_serialized_handover(&handover1);
buffer.fill(0);
inputs
.clone()
- .write_next_bcc(
- &bcc_handover1_bytes,
+ .write_next_handover(
+ &handover1_bytes,
&[0u8; HIDDEN_SIZE],
- Some([0u8; 64]),
true,
&mut buffer,
DiceContext {
@@ -415,17 +419,16 @@
subject_algorithm: KeyAlgorithm::EcdsaP384,
},
)
- .expect("Failed to derive EcdsaP256 -> EcdsaP384 BCC");
- let bcc_handover2 = diced_open_dice::bcc_handover_parse(&buffer).unwrap();
- let bcc_handover2_bytes = to_bcc_handover(&bcc_handover2);
+ .expect("Failed to derive EcdsaP256 -> EcdsaP384 DICE chain");
+ let handover2 = from_serialized_handover(&buffer);
+ let handover2_bytes = to_serialized_handover(&handover2);
buffer.fill(0);
inputs
.clone()
- .write_next_bcc(
- &bcc_handover2_bytes,
+ .write_next_handover(
+ &handover2_bytes,
&[0u8; HIDDEN_SIZE],
- Some([0u8; 64]),
true,
&mut buffer,
DiceContext {
@@ -433,21 +436,25 @@
subject_algorithm: KeyAlgorithm::Ed25519,
},
)
- .expect("Failed to derive EcdsaP384 -> Ed25519 BCC");
- let bcc_handover3 = diced_open_dice::bcc_handover_parse(&buffer).unwrap();
+ .expect("Failed to derive EcdsaP384 -> Ed25519 DICE chain");
+ let handover3 = from_serialized_handover(&buffer);
let mut session = Session::default();
session.set_allow_any_mode(true);
- let _chain = dice::Chain::from_cbor(&session, bcc_handover3.bcc().unwrap()).unwrap();
+ let _chain = dice::Chain::from_cbor(&session, handover3.bcc().unwrap()).unwrap();
}
- fn to_bcc_handover(dice_artifacts: &dyn DiceArtifacts) -> Vec<u8> {
+ fn to_serialized_handover(dice_artifacts: &dyn DiceArtifacts) -> Vec<u8> {
let dice_chain = cbor_util::deserialize::<Value>(dice_artifacts.bcc().unwrap()).unwrap();
- let bcc_handover = Value::Map(vec![
+ let handover = Value::Map(vec![
(Value::Integer(1.into()), Value::Bytes(dice_artifacts.cdi_attest().to_vec())),
(Value::Integer(2.into()), Value::Bytes(dice_artifacts.cdi_seal().to_vec())),
(Value::Integer(3.into()), dice_chain),
]);
- cbor_util::serialize(&bcc_handover).unwrap()
+ cbor_util::serialize(&handover).unwrap()
+ }
+
+ fn from_serialized_handover(bytes: &[u8]) -> diced_open_dice::BccHandover {
+ bcc_handover_parse(bytes).unwrap()
}
}
diff --git a/guest/pvmfw/src/entry.rs b/guest/pvmfw/src/entry.rs
index 8ada6a1..cb6c64e 100644
--- a/guest/pvmfw/src/entry.rs
+++ b/guest/pvmfw/src/entry.rs
@@ -33,8 +33,8 @@
#[derive(Debug, Clone)]
pub enum RebootReason {
- /// A malformed BCC was received.
- InvalidBcc,
+ /// A malformed DICE handover was received.
+ InvalidDiceHandover,
/// An invalid configuration was appended to pvmfw.
InvalidConfig,
/// An unexpected internal error happened.
@@ -54,7 +54,7 @@
impl RebootReason {
pub fn as_avf_reboot_string(&self) -> &'static str {
match self {
- Self::InvalidBcc => "PVM_FIRMWARE_INVALID_BCC",
+ Self::InvalidDiceHandover => "PVM_FIRMWARE_INVALID_DICE_HANDOVER",
Self::InvalidConfig => "PVM_FIRMWARE_INVALID_CONFIG_DATA",
Self::InternalError => "PVM_FIRMWARE_INTERNAL_ERROR",
Self::InvalidFdt => "PVM_FIRMWARE_INVALID_FDT",
@@ -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().
@@ -135,21 +135,26 @@
let mut slices = MemorySlices::new(fdt, payload, payload_size)?;
// This wrapper allows main() to be blissfully ignorant of platform details.
- let (next_bcc, debuggable_payload) = crate::main(
+ let (next_dice_handover, debuggable_payload) = crate::main(
slices.fdt,
slices.kernel,
slices.ramdisk,
- config_entries.bcc,
+ config_entries.dice_handover.as_deref(),
config_entries.debug_policy,
config_entries.vm_dtbo,
config_entries.vm_ref_dt,
)?;
- slices.add_dice_chain(next_bcc);
+ if let Some(r) = next_dice_handover {
+ slices.add_dice_handover(r);
+ }
+
// Keep UART MMIO_GUARD-ed for debuggable payloads, to enable earlycon.
let keep_uart = cfg!(debuggable_vms_improvements) && debuggable_payload;
// Writable-dirty regions will be flushed when MemoryTracker is dropped.
- config_entries.bcc.zeroize();
+ if let Some(r) = config_entries.dice_handover {
+ r.zeroize();
+ }
unshare_all_mmio_except_uart().map_err(|e| {
error!("Failed to unshare MMIO ranges: {e}");
@@ -180,8 +185,8 @@
enum AppendedPayload<'a> {
/// Configuration data.
Config(config::Config<'a>),
- /// Deprecated raw BCC, as used in Android T.
- LegacyBcc(&'a mut [u8]),
+ /// Deprecated raw DICE handover, as used in Android T.
+ LegacyDiceHandover(&'a mut [u8]),
}
impl<'a> AppendedPayload<'a> {
@@ -201,9 +206,12 @@
// SAFETY: Pointer to a valid mut (not accessed elsewhere), 'a lifetime re-used.
let data: &'a mut _ = unsafe { &mut *data_ptr };
- const BCC_SIZE: usize = SIZE_4KB;
- warn!("Assuming the appended data at {:?} to be a raw BCC", data.as_ptr());
- Some(Self::LegacyBcc(&mut data[..BCC_SIZE]))
+ const DICE_CHAIN_SIZE: usize = SIZE_4KB;
+ warn!(
+ "Assuming the appended data at {:?} to be a raw DICE handover",
+ data.as_ptr()
+ );
+ Some(Self::LegacyDiceHandover(&mut data[..DICE_CHAIN_SIZE]))
}
Err(e) => {
error!("Invalid configuration data at {data_ptr:?}: {e}");
@@ -215,7 +223,9 @@
fn get_entries(self) -> config::Entries<'a> {
match self {
Self::Config(cfg) => cfg.get_entries(),
- Self::LegacyBcc(bcc) => config::Entries { bcc, ..Default::default() },
+ Self::LegacyDiceHandover(d) => {
+ config::Entries { dice_handover: Some(d), ..Default::default() }
+ }
}
}
}
diff --git a/guest/pvmfw/src/fdt.rs b/guest/pvmfw/src/fdt.rs
index 59399b3..b5d3b28 100644
--- a/guest/pvmfw/src/fdt.rs
+++ b/guest/pvmfw/src/fdt.rs
@@ -874,9 +874,13 @@
}
}
-fn read_wdt_info_from(fdt: &Fdt) -> libfdt::Result<WdtInfo> {
+fn read_wdt_info_from(fdt: &Fdt) -> libfdt::Result<Option<WdtInfo>> {
let mut node_iter = fdt.compatible_nodes(c"qemu,vcpu-stall-detector")?;
- let node = node_iter.next().ok_or(FdtError::NotFound)?;
+ let Some(node) = node_iter.next() else {
+ // Some VMs may not have qemu,vcpu-stall-detector compatible watchdogs.
+ // Do not treat it as error.
+ return Ok(None);
+ };
let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
let reg = ranges.next().ok_or(FdtError::NotFound)?;
@@ -893,7 +897,7 @@
warn!("Discarding extra vmwdt <interrupts> entries.");
}
- Ok(WdtInfo { addr: reg.addr, size, irq })
+ Ok(Some(WdtInfo { addr: reg.addr, size, irq }))
}
fn validate_wdt_info(wdt: &WdtInfo, num_cpus: usize) -> Result<(), RebootReason> {
@@ -905,18 +909,25 @@
Ok(())
}
-fn patch_wdt_info(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
- let mut interrupts = WdtInfo::get_expected(num_cpus).irq;
- for v in interrupts.iter_mut() {
- *v = v.to_be();
- }
-
+fn patch_wdt_info(
+ fdt: &mut Fdt,
+ wdt_info: &Option<WdtInfo>,
+ num_cpus: usize,
+) -> libfdt::Result<()> {
let mut node = fdt
.root_mut()
.next_compatible(c"qemu,vcpu-stall-detector")?
.ok_or(libfdt::FdtError::NotFound)?;
- node.setprop_inplace(c"interrupts", interrupts.as_bytes())?;
- Ok(())
+
+ if wdt_info.is_some() {
+ let mut interrupts = WdtInfo::get_expected(num_cpus).irq;
+ for v in interrupts.iter_mut() {
+ *v = v.to_be();
+ }
+ node.setprop_inplace(c"interrupts", interrupts.as_bytes())
+ } else {
+ node.nop()
+ }
}
/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
@@ -1088,6 +1099,7 @@
untrusted_props: BTreeMap<CString, Vec<u8>>,
vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
vcpufreq_info: Option<VcpufreqInfo>,
+ wdt_info: Option<WdtInfo>,
}
impl DeviceTreeInfo {
@@ -1218,7 +1230,9 @@
error!("Failed to read vCPU stall detector info from DT: {e}");
RebootReason::InvalidFdt
})?;
- validate_wdt_info(&wdt_info, cpus.len())?;
+ if let Some(ref info) = wdt_info {
+ validate_wdt_info(info, cpus.len())?;
+ }
let serial_info = read_serial_info_from(fdt).map_err(|e| {
error!("Failed to read serial info from DT: {e}");
@@ -1284,6 +1298,7 @@
untrusted_props,
vm_ref_dt_props_info,
vcpufreq_info,
+ wdt_info,
})
}
@@ -1316,7 +1331,7 @@
error!("Failed to patch pci info to DT: {e}");
RebootReason::InvalidFdt
})?;
- patch_wdt_info(fdt, info.cpus.len()).map_err(|e| {
+ patch_wdt_info(fdt, &info.wdt_info, info.cpus.len()).map_err(|e| {
error!("Failed to patch wdt info to DT: {e}");
RebootReason::InvalidFdt
})?;
@@ -1360,7 +1375,7 @@
/// Modifies the input DT according to the fields of the configuration.
pub fn modify_for_next_stage(
fdt: &mut Fdt,
- bcc: &[u8],
+ dice_handover: Option<&[u8]>,
new_instance: bool,
strict_boot: bool,
debug_policy: Option<&[u8]>,
@@ -1382,7 +1397,7 @@
fdt.unpack()?;
}
- patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
+ patch_dice_node(fdt, dice_handover)?;
if let Some(mut chosen) = fdt.chosen_mut()? {
empty_or_delete_prop(&mut chosen, c"avf,strict-boot", strict_boot)?;
@@ -1400,17 +1415,19 @@
Ok(())
}
-/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
-fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
- // We reject DTs with missing reserved-memory node as validation should have checked that the
- // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
- let node = fdt.node_mut(c"/reserved-memory")?.ok_or(libfdt::FdtError::NotFound)?;
-
+/// Patch the "google,open-dice"-compatible reserved-memory node to point to the DICE handover.
+fn patch_dice_node(fdt: &mut Fdt, handover: Option<&[u8]>) -> libfdt::Result<()> {
+ // The node is assumed to be present in the template DT.
+ let node = fdt.node_mut(c"/reserved-memory")?.ok_or(FdtError::NotFound)?;
let mut node = node.next_compatible(c"google,open-dice")?.ok_or(FdtError::NotFound)?;
- let addr: u64 = addr.try_into().unwrap();
- let size: u64 = size.try_into().unwrap();
- node.setprop_inplace(c"reg", [addr.to_be_bytes(), size.to_be_bytes()].as_flattened())
+ if let Some(r) = handover {
+ let addr = (r.as_ptr() as usize).try_into().unwrap();
+ let size = r.len().try_into().unwrap();
+ node.setprop_addrrange_inplace(c"reg", addr, size)
+ } else {
+ node.nop()
+ }
}
fn empty_or_delete_prop(
diff --git a/guest/pvmfw/src/main.rs b/guest/pvmfw/src/main.rs
index 30624cd..db60849 100644
--- a/guest/pvmfw/src/main.rs
+++ b/guest/pvmfw/src/main.rs
@@ -20,7 +20,6 @@
extern crate alloc;
mod arch;
-mod bcc;
mod bootargs;
mod config;
mod device_assignment;
@@ -32,19 +31,22 @@
mod memory;
mod rollback;
-use crate::bcc::Bcc;
-use crate::dice::PartialInputs;
+use crate::dice::{DiceChainInfo, PartialInputs};
use crate::entry::RebootReason;
use crate::fdt::{modify_for_next_stage, read_instance_id, sanitize_device_tree};
use crate::rollback::perform_rollback_protection;
use alloc::borrow::Cow;
use alloc::boxed::Box;
+use alloc::vec::Vec;
use bssl_avf::Digester;
-use diced_open_dice::{bcc_handover_parse, DiceArtifacts, DiceContext, Hidden, VM_KEY_ALGORITHM};
+use diced_open_dice::{
+ bcc_handover_parse, DiceArtifacts, DiceContext, Hidden, HIDDEN_SIZE, VM_KEY_ALGORITHM,
+};
use libfdt::Fdt;
use log::{debug, error, info, trace, warn};
use pvmfw_avb::verify_payload;
use pvmfw_avb::DebugLevel;
+use pvmfw_avb::VerifiedBootData;
use pvmfw_embedded_key::PUBLIC_KEY;
use vmbase::heap;
use vmbase::memory::{flush, SIZE_4KB};
@@ -54,11 +56,11 @@
untrusted_fdt: &mut Fdt,
signed_kernel: &[u8],
ramdisk: Option<&[u8]>,
- current_bcc_handover: &[u8],
+ current_dice_handover: Option<&[u8]>,
mut debug_policy: Option<&[u8]>,
vm_dtbo: Option<&mut [u8]>,
vm_ref_dt: Option<&[u8]>,
-) -> Result<(&'a [u8], bool), RebootReason> {
+) -> Result<(Option<&'a [u8]>, bool), RebootReason> {
info!("pVM firmware");
debug!("FDT: {:?}", untrusted_fdt.as_ptr());
debug!("Signed kernel: {:?} ({:#x} bytes)", signed_kernel.as_ptr(), signed_kernel.len());
@@ -69,101 +71,57 @@
debug!("Ramdisk: None");
}
- let bcc_handover = bcc_handover_parse(current_bcc_handover).map_err(|e| {
- error!("Invalid BCC Handover: {e:?}");
- RebootReason::InvalidBcc
- })?;
- trace!("BCC: {bcc_handover:x?}");
-
- let bcc = Bcc::new(bcc_handover.bcc()).map_err(|e| {
- error!("{e}");
- RebootReason::InvalidBcc
- })?;
+ let (parsed_dice, dice_debug_mode) = parse_dice_handover(current_dice_handover)?;
// The bootloader should never pass us a debug policy when the boot is secure (the bootloader
// is locked). If it gets it wrong, disregard it & log it, to avoid it causing problems.
- if debug_policy.is_some() && !bcc.is_debug_mode() {
- warn!("Ignoring debug policy, BCC does not indicate Debug mode");
+ if debug_policy.is_some() && !dice_debug_mode {
+ warn!("Ignoring debug policy, DICE handover does not indicate Debug mode");
debug_policy = None;
}
- let verified_boot_data = verify_payload(signed_kernel, ramdisk, PUBLIC_KEY).map_err(|e| {
- error!("Failed to verify the payload: {e}");
- RebootReason::PayloadVerificationError
- })?;
- let debuggable = verified_boot_data.debug_level != DebugLevel::None;
- if debuggable {
- info!("Successfully verified a debuggable payload.");
- info!("Please disregard any previous libavb ERROR about initrd_normal.");
- }
+ // Policy/Hidden ABI: If the pvmfw loader (typically ABL) didn't pass a DICE handover (which is
+ // technically still mandatory, as per the config data specification), skip DICE, AVB, and RBP.
+ // This is to support Qualcomm QTVMs, which perform guest image verification in TrustZone.
+ let (verified_boot_data, debuggable, guest_page_size) = if current_dice_handover.is_none() {
+ warn!("Verified boot is disabled!");
+ (None, false, SIZE_4KB)
+ } else {
+ let (dat, debug, sz) = perform_verified_boot(signed_kernel, ramdisk)?;
+ (Some(dat), debug, sz)
+ };
- let guest_page_size = verified_boot_data.page_size.unwrap_or(SIZE_4KB);
let hyp_page_size = hypervisor_backends::get_granule_size();
let _ =
sanitize_device_tree(untrusted_fdt, vm_dtbo, vm_ref_dt, guest_page_size, hyp_page_size)?;
let fdt = untrusted_fdt; // DT has now been sanitized.
- let next_bcc_size = guest_page_size;
- let next_bcc = heap::aligned_boxed_slice(next_bcc_size, guest_page_size).ok_or_else(|| {
- error!("Failed to allocate the next-stage BCC");
- RebootReason::InternalError
- })?;
- // By leaking the slice, its content will be left behind for the next stage.
- let next_bcc = Box::leak(next_bcc);
-
- let dice_inputs = PartialInputs::new(&verified_boot_data).map_err(|e| {
- error!("Failed to compute partial DICE inputs: {e:?}");
- RebootReason::InternalError
- })?;
-
- let instance_hash = salt_from_instance_id(fdt)?;
- let (new_instance, salt, defer_rollback_protection) = perform_rollback_protection(
- fdt,
- &verified_boot_data,
- &dice_inputs,
- bcc_handover.cdi_seal(),
- instance_hash,
- )?;
- trace!("Got salt for instance: {salt:x?}");
-
- let new_bcc_handover = if cfg!(dice_changes) {
- Cow::Borrowed(current_bcc_handover)
- } else {
- // It is possible that the DICE chain we were given is rooted in the UDS. We do not want to
- // give such a chain to the payload, or even the associated CDIs. So remove the
- // entire chain we were given and taint the CDIs. Note that the resulting CDIs are
- // still deterministically derived from those we received, so will vary iff they do.
- // TODO(b/280405545): Remove this post Android 14.
- let truncated_bcc_handover = bcc::truncate(bcc_handover).map_err(|e| {
- error!("{e}");
+ let (next_dice_handover, new_instance) = if let Some(ref data) = verified_boot_data {
+ let instance_hash = salt_from_instance_id(fdt)?;
+ let dice_inputs = PartialInputs::new(data, instance_hash).map_err(|e| {
+ error!("Failed to compute partial DICE inputs: {e:?}");
RebootReason::InternalError
})?;
- Cow::Owned(truncated_bcc_handover)
- };
+ let (dice_handover_bytes, dice_cdi_seal, dice_context) =
+ parsed_dice.expect("Missing DICE values with VB data");
+ let (new_instance, salt, defer_rollback_protection) =
+ perform_rollback_protection(fdt, data, &dice_inputs, &dice_cdi_seal)?;
+ trace!("Got salt for instance: {salt:x?}");
- trace!("BCC leaf subject public key algorithm: {:?}", bcc.leaf_subject_pubkey().cose_alg);
-
- let dice_context = DiceContext {
- authority_algorithm: bcc.leaf_subject_pubkey().cose_alg.try_into().map_err(|e| {
- error!("{e}");
- RebootReason::InternalError
- })?,
- subject_algorithm: VM_KEY_ALGORITHM,
- };
- dice_inputs
- .write_next_bcc(
- new_bcc_handover.as_ref(),
- &salt,
- instance_hash,
- defer_rollback_protection,
- next_bcc,
+ let next_dice_handover = perform_dice_derivation(
+ dice_handover_bytes.as_ref(),
dice_context,
- )
- .map_err(|e| {
- error!("Failed to derive next-stage DICE secrets: {e:?}");
- RebootReason::SecretDerivationError
- })?;
- flush(next_bcc);
+ dice_inputs,
+ &salt,
+ defer_rollback_protection,
+ guest_page_size,
+ guest_page_size,
+ )?;
+
+ (Some(next_dice_handover), new_instance)
+ } else {
+ (None, true)
+ };
let kaslr_seed = u64::from_ne_bytes(rand::random_array().map_err(|e| {
error!("Failed to generated guest KASLR seed: {e}");
@@ -172,7 +130,7 @@
let strict_boot = true;
modify_for_next_stage(
fdt,
- next_bcc,
+ next_dice_handover,
new_instance,
strict_boot,
debug_policy,
@@ -185,7 +143,106 @@
})?;
info!("Starting payload...");
- Ok((next_bcc, debuggable))
+ Ok((next_dice_handover, debuggable))
+}
+
+fn parse_dice_handover(
+ bytes: Option<&[u8]>,
+) -> Result<(Option<(Cow<'_, [u8]>, Vec<u8>, DiceContext)>, bool), RebootReason> {
+ let Some(bytes) = bytes else {
+ return Ok((None, false));
+ };
+ let dice_handover = bcc_handover_parse(bytes).map_err(|e| {
+ error!("Invalid DICE Handover: {e:?}");
+ RebootReason::InvalidDiceHandover
+ })?;
+ trace!("DICE handover: {dice_handover:x?}");
+
+ let dice_chain_info = DiceChainInfo::new(dice_handover.bcc()).map_err(|e| {
+ error!("{e}");
+ RebootReason::InvalidDiceHandover
+ })?;
+ let is_debug_mode = dice_chain_info.is_debug_mode();
+ let cose_alg = dice_chain_info.leaf_subject_pubkey().cose_alg;
+ trace!("DICE chain leaf subject public key algorithm: {:?}", cose_alg);
+
+ let dice_context = DiceContext {
+ authority_algorithm: cose_alg.try_into().map_err(|e| {
+ error!("{e}");
+ RebootReason::InternalError
+ })?,
+ subject_algorithm: VM_KEY_ALGORITHM,
+ };
+
+ let cdi_seal = dice_handover.cdi_seal().to_vec();
+
+ let bytes_for_next = if cfg!(dice_changes) {
+ Cow::Borrowed(bytes)
+ } else {
+ // It is possible that the DICE chain we were given is rooted in the UDS. We do not want to
+ // give such a chain to the payload, or even the associated CDIs. So remove the
+ // entire chain we were given and taint the CDIs. Note that the resulting CDIs are
+ // still deterministically derived from those we received, so will vary iff they do.
+ // TODO(b/280405545): Remove this post Android 14.
+ let truncated_bytes = dice::chain::truncate(dice_handover).map_err(|e| {
+ error!("{e}");
+ RebootReason::InternalError
+ })?;
+ Cow::Owned(truncated_bytes)
+ };
+
+ Ok((Some((bytes_for_next, cdi_seal, dice_context)), is_debug_mode))
+}
+
+fn perform_dice_derivation<'a>(
+ dice_handover_bytes: &[u8],
+ dice_context: DiceContext,
+ dice_inputs: PartialInputs,
+ salt: &[u8; HIDDEN_SIZE],
+ defer_rollback_protection: bool,
+ next_handover_size: usize,
+ next_handover_align: usize,
+) -> Result<&'a [u8], RebootReason> {
+ let next_dice_handover = heap::aligned_boxed_slice(next_handover_size, next_handover_align)
+ .ok_or_else(|| {
+ error!("Failed to allocate the next-stage DICE handover");
+ RebootReason::InternalError
+ })?;
+ // By leaking the slice, its content will be left behind for the next stage.
+ let next_dice_handover = Box::leak(next_dice_handover);
+
+ dice_inputs
+ .write_next_handover(
+ dice_handover_bytes.as_ref(),
+ salt,
+ defer_rollback_protection,
+ next_dice_handover,
+ dice_context,
+ )
+ .map_err(|e| {
+ error!("Failed to derive next-stage DICE secrets: {e:?}");
+ RebootReason::SecretDerivationError
+ })?;
+ flush(next_dice_handover);
+ Ok(next_dice_handover)
+}
+
+fn perform_verified_boot<'a>(
+ signed_kernel: &[u8],
+ ramdisk: Option<&[u8]>,
+) -> Result<(VerifiedBootData<'a>, bool, usize), RebootReason> {
+ let verified_boot_data = verify_payload(signed_kernel, ramdisk, PUBLIC_KEY).map_err(|e| {
+ error!("Failed to verify the payload: {e}");
+ RebootReason::PayloadVerificationError
+ })?;
+ let debuggable = verified_boot_data.debug_level != DebugLevel::None;
+ if debuggable {
+ info!("Successfully verified a debuggable payload.");
+ info!("Please disregard any previous libavb ERROR about initrd_normal.");
+ }
+ let guest_page_size = verified_boot_data.page_size.unwrap_or(SIZE_4KB);
+
+ Ok((verified_boot_data, debuggable, guest_page_size))
}
// Get the "salt" which is one of the input for DICE derivation.
diff --git a/guest/pvmfw/src/memory.rs b/guest/pvmfw/src/memory.rs
index a663008..8af5aae 100644
--- a/guest/pvmfw/src/memory.rs
+++ b/guest/pvmfw/src/memory.rs
@@ -31,7 +31,7 @@
pub fdt: &'a mut libfdt::Fdt,
pub kernel: &'a [u8],
pub ramdisk: Option<&'a [u8]>,
- pub dice_chain: Option<&'a [u8]>,
+ pub dice_handover: Option<&'a [u8]>,
}
impl<'a> MemorySlices<'a> {
@@ -112,12 +112,12 @@
None
};
- let dice_chain = None;
+ let dice_handover = None;
- Ok(Self { fdt: untrusted_fdt, kernel, ramdisk, dice_chain })
+ Ok(Self { fdt: untrusted_fdt, kernel, ramdisk, dice_handover })
}
- pub fn add_dice_chain(&mut self, dice_chain: &'a [u8]) {
- self.dice_chain = Some(dice_chain)
+ pub fn add_dice_handover(&mut self, slice: &'a [u8]) {
+ self.dice_handover = Some(slice)
}
}
diff --git a/guest/pvmfw/src/rollback.rs b/guest/pvmfw/src/rollback.rs
index e51b6d5..c2848a2 100644
--- a/guest/pvmfw/src/rollback.rs
+++ b/guest/pvmfw/src/rollback.rs
@@ -42,8 +42,8 @@
verified_boot_data: &VerifiedBootData,
dice_inputs: &PartialInputs,
cdi_seal: &[u8],
- instance_hash: Option<Hidden>,
) -> Result<(bool, Hidden, bool), RebootReason> {
+ let instance_hash = dice_inputs.instance_hash;
if let Some(fixed) = get_fixed_rollback_protection(verified_boot_data) {
// Prevent attackers from impersonating well-known images.
perform_fixed_index_rollback_protection(verified_boot_data, fixed)?;
diff --git a/guest/pvmfw/testdata/expected_dt_with_dependency.dts b/guest/pvmfw/testdata/expected_dt_with_dependency.dts
index 7e0ad20..2823e1a 100644
--- a/guest/pvmfw/testdata/expected_dt_with_dependency.dts
+++ b/guest/pvmfw/testdata/expected_dt_with_dependency.dts
@@ -11,7 +11,6 @@
dep = <&node_a_dep &common>;
reg = <0x0 0xFF000 0x0 0x1>;
interrupts = <0x0 0xF 0x4>;
- iommus;
};
node_a_dep: node_a_dep {
diff --git a/guest/pvmfw/testdata/expected_dt_with_dependency_loop.dts b/guest/pvmfw/testdata/expected_dt_with_dependency_loop.dts
index 61031ab..b1ce262 100644
--- a/guest/pvmfw/testdata/expected_dt_with_dependency_loop.dts
+++ b/guest/pvmfw/testdata/expected_dt_with_dependency_loop.dts
@@ -8,7 +8,6 @@
loop_dep = <&node_c_loop>;
reg = <0x0 0xFF200 0x0 0x1>;
interrupts = <0x0 0xF 0x4>;
- iommus;
};
node_c_loop: node_c_loop {
diff --git a/guest/pvmfw/testdata/expected_dt_with_multiple_dependencies.dts b/guest/pvmfw/testdata/expected_dt_with_multiple_dependencies.dts
index dc8c357..d31c8cd 100644
--- a/guest/pvmfw/testdata/expected_dt_with_multiple_dependencies.dts
+++ b/guest/pvmfw/testdata/expected_dt_with_multiple_dependencies.dts
@@ -13,7 +13,6 @@
dep = <&node_a_dep &common>;
reg = <0x0 0xFF000 0x0 0x1>;
interrupts = <0x0 0xF 0x4>;
- iommus;
};
node_a_dep: node_a_dep {
@@ -38,7 +37,6 @@
dep = <&node_b_dep1 &node_b_dep2>;
reg = <0x00 0xFF100 0x00 0x01>;
interrupts = <0x00 0x0F 0x04>;
- iommus;
};
node_b_dep1: node_b_dep1 {
diff --git a/guest/rialto/Android.bp b/guest/rialto/Android.bp
index 35ede7a..a49f11f 100644
--- a/guest/rialto/Android.bp
+++ b/guest/rialto/Android.bp
@@ -63,8 +63,8 @@
// Both SERVICE_VM_VERSION and SERVICE_VM_VERSION_STRING should represent the
// same version number for the service VM.
-SERVICE_VM_VERSION = 1
-SERVICE_VM_VERSION_STRING = "1"
+SERVICE_VM_VERSION = 2
+SERVICE_VM_VERSION_STRING = "2"
genrule {
name: "service_vm_version_rs",
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/apexutil/src/lib.rs b/libs/apexutil/src/lib.rs
index 639135f..9ae5f2b 100644
--- a/libs/apexutil/src/lib.rs
+++ b/libs/apexutil/src/lib.rs
@@ -179,7 +179,7 @@
// The expected hex values were generated when we ran the method the first time.
assert_eq!(
hex::encode(res.root_digest),
- "54265da77ae1fd619e39809ad99fedc576bb20c0c7a8002190fa64438436299f"
+ "0cdeee606f2c9b468900e07d306384605684e6ca0b8bc6c51592808de9fd1c44"
);
assert_eq!(
hex::encode(res.public_key),
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..0d13695 100644
--- a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
+++ b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
@@ -758,7 +758,7 @@
try {
status = stateToStatus(virtualMachine.getState());
} catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
+ status = STATUS_STOPPED;
}
}
if (status == STATUS_STOPPED && !mVmRootPath.exists()) {
@@ -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) {
@@ -1889,9 +1890,7 @@
mVirtualMachine.stop();
dropVm();
}
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- } catch (ServiceSpecificException e) {
+ } catch (RemoteException | ServiceSpecificException e) {
// Deliberately ignored; this almost certainly means the VM exited just as
// we tried to stop it.
Log.i(TAG, "Ignoring error on close()", 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/libhypervisor_backends/src/error.rs b/libs/libhypervisor_backends/src/error.rs
index 3046b0c..ffc6c57 100644
--- a/libs/libhypervisor_backends/src/error.rs
+++ b/libs/libhypervisor_backends/src/error.rs
@@ -18,6 +18,8 @@
#[cfg(target_arch = "aarch64")]
use super::hypervisor::GeniezoneError;
+#[cfg(target_arch = "aarch64")]
+use super::hypervisor::GunyahError;
use super::hypervisor::KvmError;
#[cfg(target_arch = "aarch64")]
use uuid::Uuid;
@@ -41,6 +43,9 @@
#[cfg(target_arch = "x86_64")]
/// Unsupported x86_64 Hypervisor
UnsupportedHypervisor(u128),
+ #[cfg(target_arch = "aarch64")]
+ /// Failed to invoke Gunyah HVC.
+ GunyahError(GunyahError),
}
impl fmt::Display for Error {
@@ -58,6 +63,10 @@
)
}
#[cfg(target_arch = "aarch64")]
+ Self::GunyahError(e) => {
+ write!(f, "Failed to invoke Gunyah HVC: {e}")
+ }
+ #[cfg(target_arch = "aarch64")]
Self::UnsupportedHypervisorUuid(u) => {
write!(f, "Unsupported Hypervisor UUID {u}")
}
diff --git a/libs/libhypervisor_backends/src/hypervisor.rs b/libs/libhypervisor_backends/src/hypervisor.rs
index 7c274f5..81008f1 100644
--- a/libs/libhypervisor_backends/src/hypervisor.rs
+++ b/libs/libhypervisor_backends/src/hypervisor.rs
@@ -39,6 +39,9 @@
#[cfg(target_arch = "aarch64")]
pub use geniezone::GeniezoneError;
+#[cfg(target_arch = "aarch64")]
+pub use gunyah::GunyahError;
+
use alloc::boxed::Box;
use common::Hypervisor;
pub use common::{DeviceAssigningHypervisor, MemSharingHypervisor, MmioGuardedHypervisor};
diff --git a/libs/libhypervisor_backends/src/hypervisor/gunyah.rs b/libs/libhypervisor_backends/src/hypervisor/gunyah.rs
index 45c01bf..f25d15a 100644
--- a/libs/libhypervisor_backends/src/hypervisor/gunyah.rs
+++ b/libs/libhypervisor_backends/src/hypervisor/gunyah.rs
@@ -1,10 +1,42 @@
use super::common::Hypervisor;
+use super::DeviceAssigningHypervisor;
+use crate::{Error, Result};
+use thiserror::Error;
use uuid::{uuid, Uuid};
+const SIZE_4KB: usize = 4 << 10;
+
pub(super) struct GunyahHypervisor;
+/// Error from a Gunyah HVC call.
+#[derive(Copy, Clone, Debug, Eq, Error, PartialEq)]
+pub enum GunyahError {
+ /// The call is not supported by the implementation.
+ #[error("Gunyah call not supported")]
+ NotSupported,
+}
+
impl GunyahHypervisor {
pub const UUID: Uuid = uuid!("c1d58fcd-a453-5fdb-9265-ce36673d5f14");
}
-impl Hypervisor for GunyahHypervisor {}
+impl Hypervisor for GunyahHypervisor {
+ fn as_device_assigner(&self) -> Option<&dyn DeviceAssigningHypervisor> {
+ Some(self)
+ }
+
+ fn get_granule_size(&self) -> Option<usize> {
+ Some(SIZE_4KB)
+ }
+}
+
+impl DeviceAssigningHypervisor for GunyahHypervisor {
+ fn get_phys_mmio_token(&self, base_ipa: u64) -> Result<u64> {
+ // PA = IPA for now.
+ Ok(base_ipa)
+ }
+
+ fn get_phys_iommu_token(&self, _pviommu_id: u64, _vsid: u64) -> Result<(u64, u64)> {
+ Err(Error::GunyahError(GunyahError::NotSupported))
+ }
+}
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);
diff --git a/tests/old_images_avf_test/src/main.rs b/tests/old_images_avf_test/src/main.rs
index 018a80e..b72c706 100644
--- a/tests/old_images_avf_test/src/main.rs
+++ b/tests/old_images_avf_test/src/main.rs
@@ -173,20 +173,6 @@
}
#[test]
-fn test_run_rialto_protected() -> Result<()> {
- if hypervisor_props::is_protected_vm_supported()? {
- run_vm(
- "/data/local/tmp/rialto.bin", /* image_path */
- c"test_rialto", /* test_name */
- true, /* protected_vm */
- )
- } else {
- info!("pVMs are not supported on device. skipping test");
- Ok(())
- }
-}
-
-#[test]
fn test_run_rialto_non_protected() -> Result<()> {
if hypervisor_props::is_vm_supported()? {
run_vm(
@@ -201,20 +187,6 @@
}
#[test]
-fn test_run_android16_rialto_protected() -> Result<()> {
- if hypervisor_props::is_protected_vm_supported()? {
- run_vm(
- "/data/local/tmp/android16_rialto.bin", /* image_path */
- c"android16_test_rialto", /* test_name */
- true, /* protected_vm */
- )
- } else {
- info!("pVMs are not supported on device. skipping test");
- Ok(())
- }
-}
-
-#[test]
fn test_run_android16_rialto_non_protected() -> Result<()> {
if hypervisor_props::is_vm_supported()? {
run_vm(
diff --git a/tests/pvmfw/Android.bp b/tests/pvmfw/Android.bp
index 7f5f2af..f7a8aed 100644
--- a/tests/pvmfw/Android.bp
+++ b/tests/pvmfw/Android.bp
@@ -63,6 +63,6 @@
filegroup {
name: "test_avf_bcc_dat",
srcs: [
- "assets/bcc.dat",
+ "assets/dice.dat",
],
}
diff --git a/tests/pvmfw/assets/bcc.dat b/tests/pvmfw/assets/bcc.dat
new file mode 120000
index 0000000..0bf1fec
--- /dev/null
+++ b/tests/pvmfw/assets/bcc.dat
@@ -0,0 +1 @@
+dice.dat
\ No newline at end of file
diff --git a/tests/pvmfw/assets/bcc.dat b/tests/pvmfw/assets/dice.dat
similarity index 100%
rename from tests/pvmfw/assets/bcc.dat
rename to tests/pvmfw/assets/dice.dat
Binary files differ
diff --git a/tests/pvmfw/java/com/android/pvmfw/test/CustomPvmfwHostTestCaseBase.java b/tests/pvmfw/java/com/android/pvmfw/test/CustomPvmfwHostTestCaseBase.java
index 296604b..1e9efae 100644
--- a/tests/pvmfw/java/com/android/pvmfw/test/CustomPvmfwHostTestCaseBase.java
+++ b/tests/pvmfw/java/com/android/pvmfw/test/CustomPvmfwHostTestCaseBase.java
@@ -40,7 +40,7 @@
/** Base class for testing custom pvmfw */
public class CustomPvmfwHostTestCaseBase extends MicrodroidHostTestCaseBase {
@NonNull public static final String PVMFW_FILE_NAME = "pvmfw_test.bin";
- @NonNull public static final String BCC_FILE_NAME = "bcc.dat";
+ @NonNull public static final String BCC_FILE_NAME = "dice.dat";
@NonNull public static final String PACKAGE_FILE_NAME = "MicrodroidTestApp.apk";
@NonNull public static final String PACKAGE_NAME = "com.android.microdroid.test";
@NonNull public static final String MICRODROID_DEBUG_FULL = "full";
diff --git a/tests/pvmfw/tools/PvmfwTool.java b/tests/pvmfw/tools/PvmfwTool.java
index 9f0cb42..5df0b48 100644
--- a/tests/pvmfw/tools/PvmfwTool.java
+++ b/tests/pvmfw/tools/PvmfwTool.java
@@ -28,7 +28,7 @@
System.out.println(" Requires BCC. VM Reference DT, VM DTBO, and Debug policy");
System.out.println(" can optionally be specified");
System.out.println(
- "Usage: pvmfw-tool <out> <pvmfw.bin> <bcc.dat> [VM reference DT] [VM DTBO] [debug"
+ "Usage: pvmfw-tool <out> <pvmfw.bin> <dice.dat> [VM reference DT] [VM DTBO] [debug"
+ " policy]");
}