Merge "build/debian: Allow booting the kernel directly" into main
diff --git a/android/TerminalApp/Android.bp b/android/TerminalApp/Android.bp
index 2bac412..c18ada4 100644
--- a/android/TerminalApp/Android.bp
+++ b/android/TerminalApp/Android.bp
@@ -14,7 +14,9 @@
// TODO(b/330257000): will be removed when binder RPC is used
"android.system.virtualizationservice_internal-java",
"androidx-constraintlayout_constraintlayout",
+ "androidx.navigation_navigation-fragment-ktx",
"androidx.window_window",
+ "androidx.work_work-runtime",
"apache-commons-compress",
"avf_aconfig_flags_java",
"com.google.android.material_material",
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/Application.kt b/android/TerminalApp/java/com/android/virtualization/terminal/Application.kt
index c427337..efe651e 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/Application.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/Application.kt
@@ -18,21 +18,12 @@
import android.app.Application as AndroidApplication
import android.app.NotificationChannel
import android.app.NotificationManager
-import android.content.ComponentName
import android.content.Context
-import android.content.Intent
-import android.content.ServiceConnection
-import android.os.IBinder
-import androidx.lifecycle.DefaultLifecycleObserver
-import androidx.lifecycle.LifecycleOwner
-import androidx.lifecycle.ProcessLifecycleOwner
public class Application : AndroidApplication() {
override fun onCreate() {
super.onCreate()
setupNotificationChannels()
- val lifecycleObserver = ApplicationLifecycleObserver()
- ProcessLifecycleOwner.get().lifecycle.addObserver(lifecycleObserver)
}
private fun setupNotificationChannels() {
@@ -61,45 +52,4 @@
fun getInstance(c: Context): Application = c.getApplicationContext() as Application
}
-
- /**
- * Observes application lifecycle events and interacts with the VmLauncherService to manage
- * virtual machine state based on application lifecycle transitions. This class binds to the
- * VmLauncherService and notifies it of application lifecycle events (onStart, onStop), allowing
- * the service to manage the VM accordingly.
- */
- inner class ApplicationLifecycleObserver() : DefaultLifecycleObserver {
- private var vmLauncherService: VmLauncherService? = null
- private val connection =
- object : ServiceConnection {
- override fun onServiceConnected(className: ComponentName, service: IBinder) {
- val binder = service as VmLauncherService.VmLauncherServiceBinder
- vmLauncherService = binder.getService()
- }
-
- override fun onServiceDisconnected(arg0: ComponentName) {
- vmLauncherService = null
- }
- }
-
- override fun onCreate(owner: LifecycleOwner) {
- super.onCreate(owner)
- bindToVmLauncherService()
- }
-
- override fun onStart(owner: LifecycleOwner) {
- super.onStart(owner)
- vmLauncherService?.processAppLifeCycleEvent(ApplicationLifeCycleEvent.APP_ON_START)
- }
-
- override fun onStop(owner: LifecycleOwner) {
- vmLauncherService?.processAppLifeCycleEvent(ApplicationLifeCycleEvent.APP_ON_STOP)
- super.onStop(owner)
- }
-
- fun bindToVmLauncherService() {
- val intent = Intent(this@Application, VmLauncherService::class.java)
- this@Application.bindService(intent, connection, 0) // No BIND_AUTO_CREATE
- }
- }
}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/ApplicationLifeCycleEvent.kt b/android/TerminalApp/java/com/android/virtualization/terminal/ApplicationLifeCycleEvent.kt
deleted file mode 100644
index 4e26c3c..0000000
--- a/android/TerminalApp/java/com/android/virtualization/terminal/ApplicationLifeCycleEvent.kt
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * 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
-
-enum class ApplicationLifeCycleEvent {
- APP_ON_START,
- APP_ON_STOP,
-}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/ConfigJson.kt b/android/TerminalApp/java/com/android/virtualization/terminal/ConfigJson.kt
index 1fd58cd..5d22790 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/ConfigJson.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/ConfigJson.kt
@@ -29,7 +29,6 @@
import com.android.virtualization.terminal.ConfigJson.InputJson
import com.android.virtualization.terminal.ConfigJson.PartitionJson
import com.android.virtualization.terminal.ConfigJson.SharedPathJson
-import com.android.virtualization.terminal.InstalledImage.Companion.getDefault
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import java.io.BufferedReader
@@ -313,7 +312,7 @@
private fun replaceKeywords(r: Reader, context: Context): String {
val rules: Map<String, String> =
mapOf(
- "\\\$PAYLOAD_DIR" to getDefault(context).installDir.toString(),
+ "\\\$PAYLOAD_DIR" to InstalledImage.getDefault(context).installDir.toString(),
"\\\$USER_ID" to context.userId.toString(),
"\\\$PACKAGE_NAME" to context.getPackageName(),
"\\\$APP_DATA_DIR" to context.getDataDir().toString(),
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/DebianServiceImpl.kt b/android/TerminalApp/java/com/android/virtualization/terminal/DebianServiceImpl.kt
index 887ae02..2c52283 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/DebianServiceImpl.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/DebianServiceImpl.kt
@@ -18,9 +18,9 @@
import android.content.Context
import android.util.Log
import androidx.annotation.Keep
-import com.android.virtualization.terminal.DebianServiceImpl.ForwarderHostCallback
+import com.android.internal.annotations.GuardedBy
+import com.android.system.virtualmachine.flags.Flags
import com.android.virtualization.terminal.MainActivity.Companion.TAG
-import com.android.virtualization.terminal.PortsStateManager.Companion.getInstance
import com.android.virtualization.terminal.proto.DebianServiceGrpc.DebianServiceImplBase
import com.android.virtualization.terminal.proto.ForwardingRequestItem
import com.android.virtualization.terminal.proto.QueueOpeningRequest
@@ -28,12 +28,17 @@
import com.android.virtualization.terminal.proto.ReportVmActivePortsResponse
import com.android.virtualization.terminal.proto.ShutdownQueueOpeningRequest
import com.android.virtualization.terminal.proto.ShutdownRequestItem
+import com.android.virtualization.terminal.proto.StorageBalloonQueueOpeningRequest
+import com.android.virtualization.terminal.proto.StorageBalloonRequestItem
+import io.grpc.stub.ServerCallStreamObserver
import io.grpc.stub.StreamObserver
internal class DebianServiceImpl(context: Context) : DebianServiceImplBase() {
- private val portsStateManager: PortsStateManager = getInstance(context)
+ private val portsStateManager = PortsStateManager.getInstance(context)
private var portsStateListener: PortsStateManager.Listener? = null
private var shutdownRunnable: Runnable? = null
+ private val mLock = Object()
+ @GuardedBy("mLock") private var storageBalloonCallback: StorageBalloonCallback? = null
override fun reportVmActivePorts(
request: ReportVmActivePortsRequest,
@@ -79,14 +84,74 @@
request: ShutdownQueueOpeningRequest?,
responseObserver: StreamObserver<ShutdownRequestItem?>,
) {
+ val serverCallStreamObserver =
+ responseObserver as ServerCallStreamObserver<ShutdownRequestItem?>
+ serverCallStreamObserver.setOnCancelHandler { shutdownRunnable = null }
Log.d(TAG, "openShutdownRequestQueue")
shutdownRunnable = Runnable {
+ if (serverCallStreamObserver.isCancelled()) {
+ return@Runnable
+ }
responseObserver.onNext(ShutdownRequestItem.newBuilder().build())
responseObserver.onCompleted()
shutdownRunnable = null
}
}
+ private class StorageBalloonCallback(
+ private val responseObserver: StreamObserver<StorageBalloonRequestItem?>
+ ) {
+ fun setAvailableStorageBytes(availableBytes: Long) {
+ Log.d(TAG, "send setStorageBalloon: $availableBytes")
+ val item =
+ StorageBalloonRequestItem.newBuilder().setAvailableBytes(availableBytes).build()
+ responseObserver.onNext(item)
+ }
+
+ fun closeConnection() {
+ Log.d(TAG, "close StorageBalloonQueue")
+ responseObserver.onCompleted()
+ }
+ }
+
+ fun setAvailableStorageBytes(availableBytes: Long): Boolean {
+ synchronized(mLock) {
+ if (storageBalloonCallback == null) {
+ Log.d(TAG, "storageBalloonCallback is not ready.")
+ return false
+ }
+ storageBalloonCallback!!.setAvailableStorageBytes(availableBytes)
+ }
+ return true
+ }
+
+ override fun openStorageBalloonRequestQueue(
+ request: StorageBalloonQueueOpeningRequest?,
+ responseObserver: StreamObserver<StorageBalloonRequestItem?>,
+ ) {
+ if (!Flags.terminalStorageBalloon()) {
+ return
+ }
+ Log.d(TAG, "openStorageRequestQueue")
+ synchronized(mLock) {
+ if (storageBalloonCallback != null) {
+ Log.d(TAG, "RequestQueue already exists. Closing connection.")
+ storageBalloonCallback!!.closeConnection()
+ }
+ storageBalloonCallback = StorageBalloonCallback(responseObserver)
+ }
+ }
+
+ fun closeStorageBalloonRequestQueue() {
+ Log.d(TAG, "Stopping storage balloon queue")
+ synchronized(mLock) {
+ if (storageBalloonCallback != null) {
+ storageBalloonCallback!!.closeConnection()
+ storageBalloonCallback = null
+ }
+ }
+ }
+
@Keep
private class ForwarderHostCallback(
private val responseObserver: StreamObserver<ForwardingRequestItem?>
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/ImageArchive.kt b/android/TerminalApp/java/com/android/virtualization/terminal/ImageArchive.kt
index be1f922..54754ff 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/ImageArchive.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/ImageArchive.kt
@@ -146,8 +146,8 @@
companion object {
private const val DIR_IN_SDCARD = "linux"
private const val ARCHIVE_NAME = "images.tar.gz"
- private const val BUILD_TAG = "latest" // TODO: use actual tag name
- private const val HOST_URL = "https://dl.google.com/android/ferrochrome/$BUILD_TAG"
+ private val BUILD_TAG = Integer.toString(Build.VERSION.SDK_INT_FULL)
+ private val HOST_URL = "https://dl.google.com/android/ferrochrome/$BUILD_TAG"
fun getSdcardPathForTesting(): Path {
return Environment.getExternalStoragePublicDirectory(DIR_IN_SDCARD).toPath()
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
index 7acc5f3..50aaa33 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
@@ -19,15 +19,13 @@
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
import java.io.FileReader
import java.io.IOException
import java.io.RandomAccessFile
-import java.lang.IllegalArgumentException
-import java.lang.NumberFormatException
-import java.lang.RuntimeException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
@@ -86,11 +84,18 @@
}
@Throws(IOException::class)
- fun getSize(): Long {
+ fun getApparentSize(): Long {
return Files.size(rootPartition)
}
@Throws(IOException::class)
+ fun getPhysicalSize(): Long {
+ val stat = RandomAccessFile(rootPartition.toFile(), "rw").use { raf -> Os.fstat(raf.fd) }
+ // The unit of st_blocks is 512 byte in Android.
+ return 512L * stat.st_blocks
+ }
+
+ @Throws(IOException::class)
fun getSmallestSizePossible(): Long {
runE2fsck(rootPartition)
val p: String = rootPartition.toAbsolutePath().toString()
@@ -114,18 +119,67 @@
@Throws(IOException::class)
fun resize(desiredSize: Long): Long {
val roundedUpDesiredSize = roundUp(desiredSize)
- val curSize = getSize()
+ val curSize = getApparentSize()
+
+ runE2fsck(rootPartition)
if (roundedUpDesiredSize == curSize) {
return roundedUpDesiredSize
}
- runE2fsck(rootPartition)
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)
+ fun truncate(size: Long) {
+ try {
+ 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 truncate space", e)
+ throw IOException("Failed to truncate space", e)
+ }
}
companion object {
@@ -145,20 +199,6 @@
}
@Throws(IOException::class)
- private fun allocateSpace(path: Path, sizeInBytes: Long) {
- try {
- val raf = RandomAccessFile(path.toFile(), "rw")
- val fd = raf.fd
- Os.posix_fallocate(fd, 0, sizeInBytes)
- raf.close()
- 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)
@@ -198,7 +238,7 @@
}
}
- private fun roundUp(bytes: Long): Long {
+ internal fun roundUp(bytes: Long): Long {
// Round up every diskSizeStep MB
return ceil((bytes.toDouble()) / RESIZE_STEP_BYTES).toLong() * RESIZE_STEP_BYTES
}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt b/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
index 4162247..ba03716 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
@@ -47,6 +47,10 @@
}
try {
+ if (Files.isRegularFile(dir)) {
+ Log.i(tag, "Removed legacy log file: $dir")
+ Files.delete(dir)
+ }
Files.createDirectories(dir)
deleteOldLogs(dir, 10)
val logPath = dir.resolve(LocalDateTime.now().toString() + ".txt")
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
index 662fef5..52afef4 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
@@ -15,6 +15,7 @@
*/
package com.android.virtualization.terminal
+import android.app.ForegroundServiceStartNotAllowedException
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
@@ -29,7 +30,6 @@
import android.os.ConditionVariable
import android.os.Environment
import android.os.SystemProperties
-import android.os.Trace
import android.provider.Settings
import android.util.DisplayMetrics
import android.util.Log
@@ -45,19 +45,15 @@
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
-import androidx.lifecycle.ViewModelProvider
+import androidx.activity.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.android.internal.annotations.VisibleForTesting
import com.android.microdroid.test.common.DeviceProperties
-import com.android.system.virtualmachine.flags.Flags.terminalGuiSupport
+import com.android.system.virtualmachine.flags.Flags
import com.android.virtualization.terminal.ErrorActivity.Companion.start
-import com.android.virtualization.terminal.InstalledImage.Companion.getDefault
-import com.android.virtualization.terminal.VmLauncherService.Companion.run
-import com.android.virtualization.terminal.VmLauncherService.Companion.stop
import com.android.virtualization.terminal.VmLauncherService.VmLauncherServiceCallback
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
-import java.io.IOException
import java.net.MalformedURLException
import java.net.URL
import java.util.concurrent.CompletableFuture
@@ -77,17 +73,17 @@
private lateinit var image: InstalledImage
private lateinit var accessibilityManager: AccessibilityManager
private lateinit var manageExternalStorageActivityResultLauncher: ActivityResultLauncher<Intent>
- private lateinit var terminalViewModel: TerminalViewModel
private lateinit var viewPager: ViewPager2
private lateinit var tabLayout: TabLayout
private lateinit var terminalTabAdapter: TerminalTabAdapter
private val terminalInfo = CompletableFuture<TerminalInfo>()
+ private val terminalViewModel: TerminalViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lockOrientationIfNecessary()
- image = getDefault(this)
+ image = InstalledImage.getDefault(this)
val launchInstaller = installIfNecessary()
@@ -116,7 +112,6 @@
}
private fun initializeUi() {
- terminalViewModel = ViewModelProvider(this)[TerminalViewModel::class.java]
setContentView(R.layout.activity_headless)
tabLayout = findViewById<TabLayout>(R.id.tab_layout)
displayMenu = findViewById<Button>(R.id.display_button)
@@ -131,9 +126,9 @@
}
displayMenu?.also {
- it.visibility = if (terminalGuiSupport()) View.VISIBLE else View.GONE
+ it.visibility = if (Flags.terminalGuiSupport()) View.VISIBLE else View.GONE
it.setEnabled(false)
- if (terminalGuiSupport()) {
+ if (Flags.terminalGuiSupport()) {
it.setOnClickListener {
val intent = Intent(this, DisplayActivity::class.java)
intent.flags =
@@ -156,6 +151,20 @@
TabLayoutMediator(tabLayout, viewPager, false, false) { _: TabLayout.Tab?, _: Int -> }
.attach()
+ tabLayout.addOnTabSelectedListener(
+ object : TabLayout.OnTabSelectedListener {
+ override fun onTabSelected(tab: TabLayout.Tab?) {
+ tab?.position?.let {
+ terminalViewModel.selectedTabViewId = terminalTabAdapter.tabs[it].id
+ }
+ }
+
+ override fun onTabUnselected(tab: TabLayout.Tab?) {}
+
+ override fun onTabReselected(tab: TabLayout.Tab?) {}
+ }
+ )
+
addTerminalTab()
tabAddButton?.setOnClickListener { addTerminalTab() }
@@ -165,7 +174,9 @@
val tab = tabLayout.newTab()
tab.setCustomView(R.layout.tabitem_terminal)
viewPager.offscreenPageLimit += 1
- terminalTabAdapter.addTab()
+ val tabId = terminalTabAdapter.addTab()
+ terminalViewModel.selectedTabViewId = tabId
+ terminalViewModel.terminalTabs[tabId] = tab
tab.customView!!
.findViewById<Button>(R.id.tab_close_button)
.setOnClickListener(
@@ -200,7 +211,7 @@
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (Build.isDebuggable() && event.keyCode == KeyEvent.KEYCODE_UNKNOWN) {
if (event.action == KeyEvent.ACTION_UP) {
- start(this, Exception("Debug: KeyEvent.KEYCODE_UNKNOWN"))
+ ErrorActivity.start(this, Exception("Debug: KeyEvent.KEYCODE_UNKNOWN"))
}
return true
}
@@ -228,9 +239,7 @@
"&fontWeightBold=" +
(FontStyle.FONT_WEIGHT_BOLD + config.fontWeightAdjustment) +
"&screenReaderMode=" +
- accessibilityManager.isEnabled +
- "&titleFixed=" +
- getString(R.string.app_name))
+ accessibilityManager.isEnabled)
try {
return URL("https", ipAddress, port, "/$query")
@@ -254,7 +263,8 @@
executorService.shutdown()
getSystemService<AccessibilityManager>(AccessibilityManager::class.java)
.removeAccessibilityStateChangeListener(this)
- stop(this)
+ val intent = VmLauncherService.getIntentForShutdown(this, this)
+ startService(intent)
super.onDestroy()
}
@@ -274,7 +284,7 @@
override fun onVmError() {
Log.i(TAG, "onVmError()")
// TODO: error cause is too simple.
- start(this, Exception("onVmError"))
+ ErrorActivity.start(this, Exception("onVmError"))
}
override fun onAccessibilityStateChanged(enabled: Boolean) {
@@ -309,13 +319,11 @@
}
private fun startVm() {
- val image = getDefault(this)
+ val image = InstalledImage.getDefault(this)
if (!image.isInstalled()) {
return
}
- resizeDiskIfNecessary(image)
-
val tapIntent = Intent(this, MainActivity::class.java)
tapIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
val tapPendingIntent =
@@ -326,9 +334,7 @@
val settingsPendingIntent =
PendingIntent.getActivity(this, 0, settingsIntent, PendingIntent.FLAG_IMMUTABLE)
- val stopIntent = Intent()
- stopIntent.setClass(this, VmLauncherService::class.java)
- stopIntent.setAction(VmLauncherService.ACTION_STOP_VM_LAUNCHER_SERVICE)
+ val stopIntent = VmLauncherService.getIntentForShutdown(this, this)
val stopPendingIntent =
PendingIntent.getService(
this,
@@ -363,8 +369,22 @@
)
.build()
- Trace.beginAsyncSection("executeTerminal", 0)
- run(this, this, notification, getDisplayInfo())
+ val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getApparentSize())
+
+ val intent =
+ VmLauncherService.getIntentForStart(
+ this,
+ this,
+ notification,
+ getDisplayInfo(),
+ diskSize,
+ )
+ try {
+ startForegroundService(intent)
+ } catch (e: ForegroundServiceStartNotAllowedException) {
+ Log.e(TAG, "Failed to start VM", e)
+ finish()
+ }
}
@VisibleForTesting
@@ -372,19 +392,10 @@
return bootCompleted.block(timeoutMillis)
}
- private fun resizeDiskIfNecessary(image: InstalledImage) {
- try {
- // TODO(b/382190982): Show snackbar message instead when it's recoverable.
- image.resize(intent.getLongExtra(KEY_DISK_SIZE, image.getSize()))
- } catch (e: IOException) {
- start(this, Exception("Failed to resize disk", e))
- return
- }
- }
-
companion object {
const val TAG: String = "VmTerminalApp"
- const val KEY_DISK_SIZE: String = "disk_size"
+ const val PREFIX: String = "com.android.virtualization.terminal."
+ const val EXTRA_DISK_SIZE: String = PREFIX + "EXTRA_DISK_SIZE"
private val TERMINAL_CONNECTION_TIMEOUT_MS: Int
private const val REQUEST_CODE_INSTALLER = 0x33
private const val FONT_SIZE_DEFAULT = 13
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt
new file mode 100644
index 0000000..7647d9b
--- /dev/null
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+package com.android.virtualization.terminal
+
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
+import android.system.virtualmachine.VirtualMachine
+import android.util.Log
+import androidx.lifecycle.DefaultLifecycleObserver
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.ProcessLifecycleOwner
+import com.android.virtualization.terminal.MainActivity.Companion.TAG
+import java.util.concurrent.Executors
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
+
+/**
+ * MemBalloonController is responsible for adjusting the memory ballon size of a VM depending on
+ * whether the app is visible or running in the background
+ */
+class MemBalloonController(val context: Context, val vm: VirtualMachine) {
+ companion object {
+ private const val INITIAL_PERCENT = 10
+ private const val MAX_PERCENT = 50
+ private const val INFLATION_STEP_PERCENT = 5
+ private const val INFLATION_PERIOD_SEC = 60L
+
+ private val mainHandler = Handler(Looper.getMainLooper())
+
+ private fun runOnMainThread(runnable: Runnable) {
+ mainHandler.post(runnable)
+ }
+ }
+
+ private val executor =
+ Executors.newSingleThreadScheduledExecutor(
+ TerminalThreadFactory(context.getApplicationContext())
+ )
+
+ private val observer =
+ object : DefaultLifecycleObserver {
+
+ // If the app is started or resumed, give deflate the balloon to 0 to give maximum
+ // available memory to the virtual machine
+ override fun onResume(owner: LifecycleOwner) {
+ ongoingInflation?.cancel(false)
+ executor.submit({
+ Log.v(TAG, "app resumed. deflating mem balloon to the minimum")
+ vm.setMemoryBalloonByPercent(0)
+ })
+ }
+
+ // If the app goes into background, progressively inflate the balloon from
+ // INITIAL_PERCENT until it reaches MAX_PERCENT
+ override fun onStop(owner: LifecycleOwner) {
+ ongoingInflation?.cancel(false)
+ balloonPercent = INITIAL_PERCENT
+ ongoingInflation =
+ executor.scheduleAtFixedRate(
+ {
+ if (balloonPercent <= MAX_PERCENT) {
+ Log.v(TAG, "inflating mem balloon to ${balloonPercent} %")
+ vm.setMemoryBalloonByPercent(balloonPercent)
+ balloonPercent += INFLATION_STEP_PERCENT
+ } else {
+ Log.v(TAG, "mem balloon is inflated to its max (${MAX_PERCENT} %)")
+ ongoingInflation!!.cancel(false)
+ }
+ },
+ 0 /* initialDelay */,
+ INFLATION_PERIOD_SEC,
+ TimeUnit.SECONDS,
+ )
+ }
+ }
+
+ private var balloonPercent = 0
+ private var ongoingInflation: ScheduledFuture<*>? = null
+
+ fun start() {
+ // addObserver is @MainThread
+ runOnMainThread({ ProcessLifecycleOwner.get().lifecycle.addObserver(observer) })
+ }
+
+ fun stop() {
+ // removeObserver is @MainThread
+ runOnMainThread({
+ ProcessLifecycleOwner.get().lifecycle.removeObserver(observer)
+ executor.shutdown()
+ })
+ }
+}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/ModifierKeysController.kt b/android/TerminalApp/java/com/android/virtualization/terminal/ModifierKeysController.kt
index ed340d2..7c3eb69 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/ModifierKeysController.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/ModifierKeysController.kt
@@ -115,10 +115,12 @@
activeTerminalView!!.hasFocus() &&
!(activity.resources.configuration.keyboard == Configuration.KEYBOARD_QWERTY)
- // If terminal's height is less than 30% of the screen height, we need to show modifier keys in
- // a single line to save the vertical space
- private fun needsKeysInSingleLine(): Boolean =
- activeTerminalView!!.height.div(activity.window.decorView.height.toFloat()) < 0.3f
+ // If terminal's height including height of modifier keys is less than 40% of the screen
+ // height, we need to show modifier keys in a single line to save the vertical space
+ private fun needsKeysInSingleLine(): Boolean {
+ val keys = if (keysInSingleLine) keysSingleLine else keysDoubleLine
+ return activeTerminalView!!.height + keys.height < 0.4f * activity.window.decorView.height
+ }
companion object {
private val BTN_KEY_CODE_MAP =
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/Runner.kt b/android/TerminalApp/java/com/android/virtualization/terminal/Runner.kt
index 6454cbd..642cb26 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/Runner.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/Runner.kt
@@ -27,7 +27,7 @@
import java.util.concurrent.ForkJoinPool
/** Utility class for creating a VM and waiting for it to finish. */
-internal class Runner private constructor(val vm: VirtualMachine?, callback: Callback) {
+internal class Runner private constructor(val vm: VirtualMachine, callback: Callback) {
/** Get future about VM's exit status. */
val exitStatus = callback.finishedSuccessfully
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 8ea4b25..da07b19 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
@@ -31,7 +31,9 @@
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
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
@@ -45,6 +47,7 @@
private lateinit var cancelButton: View
private lateinit var resizeButton: View
private lateinit var diskSizeText: TextView
+ private lateinit var diskMaxSizeText: TextView
private lateinit var diskSizeSlider: SeekBar
private fun bytesToMb(bytes: Long): Long {
@@ -55,6 +58,13 @@
return bytes shl 20
}
+ private fun getAvailableSizeMb(): Long {
+ val usableSpaceMb =
+ bytesToMb(Environment.getDataDirectory().getUsableSpace()) and
+ (diskSizeStepMb - 1).inv()
+ return diskSizeMb + usableSpaceMb
+ }
+
private fun mbToProgress(bytes: Long): Int {
return (bytes / diskSizeStepMb).toInt()
}
@@ -70,15 +80,12 @@
diskSizeStepMb = 1L shl resources.getInteger(R.integer.disk_size_round_up_step_size_in_mb)
val image = InstalledImage.getDefault(this)
- diskSizeMb = bytesToMb(image.getSize())
+ diskSizeMb = bytesToMb(image.getApparentSize())
val minDiskSizeMb = bytesToMb(image.getSmallestSizePossible()).coerceAtMost(diskSizeMb)
- val usableSpaceMb =
- bytesToMb(Environment.getDataDirectory().getUsableSpace()) and
- (diskSizeStepMb - 1).inv()
- val maxDiskSizeMb = defaultMaxDiskSizeMb.coerceAtMost(diskSizeMb + usableSpaceMb)
+ val maxDiskSizeMb = defaultMaxDiskSizeMb.coerceAtMost(getAvailableSizeMb())
diskSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_assigned)!!
- val diskMaxSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_max)
+ diskMaxSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_max)
diskMaxSizeText.text =
getString(
R.string.settings_disk_resize_resize_gb_max_format,
@@ -137,15 +144,52 @@
}
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
- // Restart terminal
- val intent = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
- intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
- intent?.putExtra(MainActivity.KEY_DISK_SIZE, mbToBytes(diskSizeMb))
- finish()
- startActivity(intent)
+ // Note: we first stop the VM, and wait for it to fully stop. Then we (re) start the Main
+ // Activity with an extra argument specifying the new size. The actual resizing will be done
+ // there.
+ // TODO: show progress until the stop is confirmed
+ val intent =
+ VmLauncherService.getIntentForShutdown(
+ this,
+ object : VmLauncherServiceCallback {
+ override fun onVmStart() {}
+
+ override fun onTerminalAvailable(info: TerminalInfo) {}
+
+ override fun onVmStop() {
+ finish()
+
+ val intent =
+ baseContext.packageManager.getLaunchIntentForPackage(
+ baseContext.packageName
+ )!!
+ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
+ intent.putExtra(MainActivity.EXTRA_DISK_SIZE, mbToBytes(diskSizeMb))
+ startActivity(intent)
+ }
+
+ override fun onVmError() {}
+ },
+ )
+ startService(intent)
}
fun updateSliderText(sizeMb: Long) {
@@ -163,6 +207,14 @@
)
}
+ fun updateMaxSizeText(sizeMb: Long) {
+ diskMaxSizeText.text =
+ getString(
+ R.string.settings_disk_resize_resize_gb_max_format,
+ localizedFileSize(sizeMb, /* isShort= */ true),
+ )
+ }
+
fun localizedFileSize(sizeMb: Long, isShort: Boolean): String {
val sizeGb = sizeMb / (1 shl 10).toFloat()
val measure = Measure(sizeGb, MeasureUnit.GIGABYTE)
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
index 132d749..aa0c3f5 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
@@ -24,7 +24,7 @@
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
-class SettingsItemAdapter(private val dataSet: Array<SettingsItem>) :
+class SettingsItemAdapter(private val dataSet: List<SettingsItem>) :
RecyclerView.Adapter<SettingsItemAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
index 7562779..2653ba9 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
@@ -15,16 +15,96 @@
*/
package com.android.virtualization.terminal
+import android.content.ComponentName
import android.content.Context
+import android.content.Intent
import androidx.startup.Initializer
+import androidx.window.embedding.ActivityFilter
+import androidx.window.embedding.EmbeddingAspectRatio
import androidx.window.embedding.RuleController
+import androidx.window.embedding.SplitAttributes
+import androidx.window.embedding.SplitPairFilter
+import androidx.window.embedding.SplitPairRule
+import androidx.window.embedding.SplitPlaceholderRule
+import androidx.window.embedding.SplitRule
+import com.android.system.virtualmachine.flags.Flags
class SplitInitializer : Initializer<RuleController> {
override fun create(context: Context): RuleController {
- return RuleController.getInstance(context).apply {
- setRules(RuleController.parseRules(context, R.xml.main_split_config))
+ val filters =
+ mutableSetOf(
+ SplitPairFilter(
+ ComponentName(context, SettingsActivity::class.java),
+ ComponentName(context, SettingsPortForwardingActivity::class.java),
+ null,
+ )
+ )
+
+ if (Flags.terminalStorageBalloon()) {
+ filters.add(
+ SplitPairFilter(
+ ComponentName(context, SettingsActivity::class.java),
+ ComponentName(context, SettingsDiskResizeActivity::class.java),
+ null,
+ )
+ )
}
+
+ filters.add(
+ SplitPairFilter(
+ ComponentName(context, SettingsActivity::class.java),
+ ComponentName(context, SettingsRecoveryActivity::class.java),
+ null,
+ )
+ )
+ val splitPairRules =
+ SplitPairRule.Builder(filters)
+ .setClearTop(true)
+ .setFinishPrimaryWithSecondary(SplitRule.FinishBehavior.ADJACENT)
+ .setFinishSecondaryWithPrimary(SplitRule.FinishBehavior.ALWAYS)
+ .setDefaultSplitAttributes(
+ SplitAttributes.Builder()
+ .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+ .setSplitType(
+ SplitAttributes.SplitType.ratio(
+ context.resources.getFloat(R.dimen.activity_split_ratio)
+ )
+ )
+ .build()
+ )
+ .setMaxAspectRatioInPortrait(EmbeddingAspectRatio.ALWAYS_ALLOW)
+ .setMinWidthDp(context.resources.getInteger(R.integer.split_min_width))
+ .build()
+
+ val placeholderRule =
+ SplitPlaceholderRule.Builder(
+ setOf(
+ ActivityFilter(ComponentName(context, SettingsActivity::class.java), null)
+ ),
+ Intent(context, SettingsDiskResizeActivity::class.java),
+ )
+ .setFinishPrimaryWithPlaceholder(SplitRule.FinishBehavior.ADJACENT)
+ .setDefaultSplitAttributes(
+ SplitAttributes.Builder()
+ .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+ .setSplitType(
+ SplitAttributes.SplitType.ratio(
+ context.resources.getFloat(R.dimen.activity_split_ratio)
+ )
+ )
+ .build()
+ )
+ .setMaxAspectRatioInPortrait(EmbeddingAspectRatio.ALWAYS_ALLOW)
+ .setMinWidthDp(context.resources.getInteger(R.integer.split_min_width))
+ .setSticky(false)
+ .build()
+
+ val ruleController = RuleController.getInstance(context)
+ ruleController.addRule(splitPairRules)
+ ruleController.addRule(placeholderRule)
+
+ return ruleController
}
override fun dependencies(): List<Class<out Initializer<*>>> {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/StorageBalloonWorker.kt b/android/TerminalApp/java/com/android/virtualization/terminal/StorageBalloonWorker.kt
new file mode 100644
index 0000000..345bf75
--- /dev/null
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/StorageBalloonWorker.kt
@@ -0,0 +1,111 @@
+/*
+ * 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.
+ */
+package com.android.virtualization.terminal
+
+import android.content.Context
+import android.os.storage.StorageManager
+import android.os.storage.StorageManager.UUID_DEFAULT
+import android.util.Log
+import androidx.work.WorkManager
+import androidx.work.Worker
+import androidx.work.WorkerParameters
+import com.android.virtualization.terminal.MainActivity.Companion.TAG
+import java.util.concurrent.TimeUnit
+
+class StorageBalloonWorker(appContext: Context, workerParams: WorkerParameters) :
+ Worker(appContext, workerParams) {
+
+ override fun doWork(): Result {
+ Log.d(TAG, "StorageBalloonWorker.doWork() called")
+
+ var storageManager =
+ applicationContext.getSystemService(Context.STORAGE_SERVICE) as StorageManager
+ val hostAllocatableBytes = storageManager.getAllocatableBytes(UUID_DEFAULT)
+
+ val guestAvailableBytes = calculateGuestAvailableStorageSize(hostAllocatableBytes)
+ // debianService must be set when this function is called.
+ debianService!!.setAvailableStorageBytes(guestAvailableBytes)
+
+ val delaySeconds = calculateDelaySeconds(hostAllocatableBytes)
+ scheduleNextTask(delaySeconds)
+
+ return Result.success()
+ }
+
+ private fun calculateGuestAvailableStorageSize(hostAllocatableBytes: Long): Long {
+ return hostAllocatableBytes - HOST_RESERVED_BYTES
+ }
+
+ private fun calculateDelaySeconds(hostAvailableBytes: Long): Long {
+ return when {
+ hostAvailableBytes < CRITICAL_STORAGE_THRESHOLD_BYTES -> CRITICAL_DELAY_SECONDS
+ hostAvailableBytes < LOW_STORAGE_THRESHOLD_BYTES -> LOW_STORAGE_DELAY_SECONDS
+ hostAvailableBytes < MODERATE_STORAGE_THRESHOLD_BYTES -> MODERATE_STORAGE_DELAY_SECONDS
+ else -> NORMAL_DELAY_SECONDS
+ }
+ }
+
+ private fun scheduleNextTask(delaySeconds: Long) {
+ val storageBalloonTaskRequest =
+ androidx.work.OneTimeWorkRequest.Builder(StorageBalloonWorker::class.java)
+ .setInitialDelay(delaySeconds, TimeUnit.SECONDS)
+ .build()
+ androidx.work.WorkManager.getInstance(applicationContext)
+ .enqueueUniqueWork(
+ "storageBalloonTask",
+ androidx.work.ExistingWorkPolicy.REPLACE,
+ storageBalloonTaskRequest,
+ )
+ Log.d(TAG, "next storage balloon task is scheduled in $delaySeconds seconds")
+ }
+
+ companion object {
+ private var debianService: DebianServiceImpl? = null
+
+ // Reserve 1GB as host-only region.
+ private const val HOST_RESERVED_BYTES = 1024L * 1024 * 1024
+
+ // Thresholds for deciding time period to report storage information to the guest.
+ // Less storage is available on the host, more frequently the host will report storage
+ // information to the guest.
+ //
+ // Critical: (host storage < 1GB) => report every 5 seconds
+ private const val CRITICAL_STORAGE_THRESHOLD_BYTES = 1L * 1024 * 1024 * 1024
+ private const val CRITICAL_DELAY_SECONDS = 5L
+ // Low: (1GB <= storage < 5GB) => report every 60 seconds
+ private const val LOW_STORAGE_THRESHOLD_BYTES = 5L * 1024 * 1024 * 1024
+ private const val LOW_STORAGE_DELAY_SECONDS = 60L
+ // Moderate: (5GB <= storage < 10GB) => report every 15 minutes
+ private const val MODERATE_STORAGE_THRESHOLD_BYTES = 10L * 1024 * 1024 * 1024
+ private const val MODERATE_STORAGE_DELAY_SECONDS = 15L * 60
+ // Normal: report every 60 minutes
+ private const val NORMAL_DELAY_SECONDS = 60L * 60
+
+ internal fun start(ctx: Context, ds: DebianServiceImpl) {
+ debianService = ds
+ val storageBalloonTaskRequest =
+ androidx.work.OneTimeWorkRequest.Builder(StorageBalloonWorker::class.java)
+ .setInitialDelay(1, TimeUnit.SECONDS)
+ .build()
+ androidx.work.WorkManager.getInstance(ctx)
+ .enqueueUniqueWork(
+ "storageBalloonTask",
+ androidx.work.ExistingWorkPolicy.REPLACE,
+ storageBalloonTaskRequest,
+ )
+ }
+ }
+}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
index 5c01ead..a0c6e4e 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
@@ -19,7 +19,6 @@
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Bundle
-import android.os.Trace
import android.util.Log
import android.view.LayoutInflater
import android.view.View
@@ -32,8 +31,9 @@
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
+import android.widget.TextView
import androidx.fragment.app.Fragment
-import androidx.lifecycle.ViewModelProvider
+import androidx.fragment.app.activityViewModels
import com.android.system.virtualmachine.flags.Flags.terminalGuiSupport
import com.android.virtualization.terminal.CertificateUtils.createOrGetKey
import com.android.virtualization.terminal.CertificateUtils.writeCertificateToFile
@@ -46,7 +46,7 @@
private lateinit var id: String
private var certificates: Array<X509Certificate>? = null
private var privateKey: PrivateKey? = null
- private lateinit var terminalViewModel: TerminalViewModel
+ private val terminalViewModel: TerminalViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
@@ -60,7 +60,6 @@
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
- terminalViewModel = ViewModelProvider(this)[TerminalViewModel::class.java]
terminalView = view.findViewById(R.id.webview)
bootProgressView = view.findViewById(R.id.boot_progress)
initializeWebView()
@@ -80,19 +79,46 @@
terminalView.saveState(outState)
}
+ override fun onResume() {
+ super.onResume()
+ updateFocus()
+ }
+
private fun initializeWebView() {
terminalView.settings.databaseEnabled = true
terminalView.settings.domStorageEnabled = true
terminalView.settings.javaScriptEnabled = true
terminalView.settings.cacheMode = WebSettings.LOAD_DEFAULT
- terminalView.webChromeClient = WebChromeClient()
+ terminalView.webChromeClient = TerminalWebChromeClient()
terminalView.webViewClient = TerminalWebViewClient()
(activity as MainActivity).modifierKeysController.addTerminalView(terminalView)
terminalViewModel.terminalViews.add(terminalView)
}
+ private inner class TerminalWebChromeClient : WebChromeClient() {
+ override fun onReceivedTitle(view: WebView?, title: String?) {
+ super.onReceivedTitle(view, title)
+ title?.let { originalTitle ->
+ val ttydSuffix = " | login -f droid (localhost)"
+ val displayedTitle =
+ if (originalTitle.endsWith(ttydSuffix)) {
+ // When the session is created. The format of the title will be
+ // 'droid@localhost: ~ | login -f droid (localhost)'.
+ originalTitle.dropLast(ttydSuffix.length)
+ } else {
+ originalTitle
+ }
+
+ terminalViewModel.terminalTabs[id]
+ ?.customView
+ ?.findViewById<TextView>(R.id.tab_title)
+ ?.text = displayedTitle
+ }
+ }
+ }
+
private inner class TerminalWebViewClient : WebViewClient() {
private var loadFailed = false
private var requestId: Long = 0
@@ -145,11 +171,11 @@
object : WebView.VisualStateCallback() {
override fun onComplete(completedRequestId: Long) {
if (completedRequestId == requestId) {
- Trace.endAsyncSection("executeTerminal", 0)
bootProgressView.visibility = View.GONE
terminalView.visibility = View.VISIBLE
terminalView.mapTouchToMouseEvent()
updateMainActivity()
+ updateFocus()
}
}
},
@@ -191,6 +217,12 @@
certificates = arrayOf<X509Certificate>(pke.certificate as X509Certificate)
}
+ private fun updateFocus() {
+ if (terminalViewModel.selectedTabViewId == id) {
+ terminalView.requestFocus()
+ }
+ }
+
companion object {
const val TAG: String = "VmTerminalApp"
}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalViewModel.kt b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalViewModel.kt
index 4a69f75..dd40143 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalViewModel.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalViewModel.kt
@@ -16,7 +16,10 @@
package com.android.virtualization.terminal
import androidx.lifecycle.ViewModel
+import com.google.android.material.tabs.TabLayout.Tab
class TerminalViewModel : ViewModel() {
val terminalViews: MutableSet<TerminalView> = mutableSetOf()
+ var selectedTabViewId: String? = null
+ val terminalTabs: MutableMap<String, Tab> = mutableMapOf()
}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
index 345e8dd..84168e5 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
@@ -31,18 +31,19 @@
import android.os.Parcel
import android.os.Parcelable
import android.os.ResultReceiver
-import android.os.Trace
+import android.os.StatFs
+import android.os.SystemProperties
import android.system.virtualmachine.VirtualMachine
import android.system.virtualmachine.VirtualMachineCustomImageConfig
import android.system.virtualmachine.VirtualMachineCustomImageConfig.AudioConfig
import android.system.virtualmachine.VirtualMachineException
import android.util.Log
import android.widget.Toast
-import com.android.internal.annotations.GuardedBy
-import com.android.system.virtualmachine.flags.Flags.terminalGuiSupport
+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 com.android.virtualization.terminal.Runner.Companion.create
-import com.android.virtualization.terminal.VmLauncherService.VmLauncherServiceCallback
import io.grpc.Grpc
import io.grpc.InsecureServerCredentials
import io.grpc.Metadata
@@ -55,65 +56,27 @@
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
-import java.lang.Math.min
-import java.lang.RuntimeException
import java.net.InetSocketAddress
import java.net.SocketAddress
import java.nio.file.Files
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
class VmLauncherService : Service() {
- inner class VmLauncherServiceBinder : android.os.Binder() {
- fun getService(): VmLauncherService = this@VmLauncherService
- }
-
- private val binder = VmLauncherServiceBinder()
+ // Thread pool
+ private lateinit var bgThreads: ExecutorService
+ // Single thread
+ private lateinit var mainWorkerThread: ExecutorService
+ private lateinit var image: InstalledImage
// TODO: using lateinit for some fields to avoid null
- private var executorService: ExecutorService? = null
private var virtualMachine: VirtualMachine? = null
- private var resultReceiver: ResultReceiver? = null
private var server: Server? = null
private var debianService: DebianServiceImpl? = null
private var portNotifier: PortNotifier? = null
- private var mLock = Object()
- @GuardedBy("mLock") private var currentMemBalloonPercent = 0
-
- @GuardedBy("mLock") private val inflateMemBalloonHandler = Handler(Looper.getMainLooper())
- private val inflateMemBalloonTask: Runnable =
- object : Runnable {
- override fun run() {
- synchronized(mLock) {
- if (
- currentMemBalloonPercent < INITIAL_MEM_BALLOON_PERCENT ||
- currentMemBalloonPercent > MAX_MEM_BALLOON_PERCENT
- ) {
- Log.e(
- TAG,
- "currentBalloonPercent=$currentMemBalloonPercent is invalid," +
- " should be in range: " +
- "$INITIAL_MEM_BALLOON_PERCENT~$MAX_MEM_BALLOON_PERCENT",
- )
- return
- }
- // Increases the balloon size by MEM_BALLOON_PERCENT_STEP% every time
- if (currentMemBalloonPercent < MAX_MEM_BALLOON_PERCENT) {
- currentMemBalloonPercent =
- min(
- MAX_MEM_BALLOON_PERCENT,
- currentMemBalloonPercent + MEM_BALLOON_PERCENT_STEP,
- )
- virtualMachine?.setMemoryBalloonByPercent(currentMemBalloonPercent)
- inflateMemBalloonHandler.postDelayed(
- this,
- MEM_BALLOON_INFLATE_INTERVAL_MILLIS,
- )
- }
- }
- }
- }
+ private var runner: Runner? = null
interface VmLauncherServiceCallback {
fun onVmStart()
@@ -126,110 +89,169 @@
}
override fun onBind(intent: Intent?): IBinder? {
- return binder
+ return null
}
- /**
- * Processes application lifecycle events and adjusts the virtual machine's memory balloon
- * accordingly.
- *
- * @param event The application lifecycle event.
- */
- fun processAppLifeCycleEvent(event: ApplicationLifeCycleEvent) {
- when (event) {
- // When the app starts, reset the memory balloon to 0%.
- // This gives the app maximum available memory.
- ApplicationLifeCycleEvent.APP_ON_START -> {
- synchronized(mLock) {
- inflateMemBalloonHandler.removeCallbacks(inflateMemBalloonTask)
- currentMemBalloonPercent = 0
- virtualMachine?.setMemoryBalloonByPercent(currentMemBalloonPercent)
- }
- }
- ApplicationLifeCycleEvent.APP_ON_STOP -> {
- // When the app stops, inflate the memory balloon to INITIAL_MEM_BALLOON_PERCENT.
- // Inflate the balloon by MEM_BALLOON_PERCENT_STEP every
- // MEM_BALLOON_INFLATE_INTERVAL_MILLIS milliseconds until reaching
- // MAX_MEM_BALLOON_PERCENT of total memory. This allows the system to reclaim
- // memory while the app is in the background.
- synchronized(mLock) {
- currentMemBalloonPercent = INITIAL_MEM_BALLOON_PERCENT
- virtualMachine?.setMemoryBalloonByPercent(currentMemBalloonPercent)
- inflateMemBalloonHandler.postDelayed(
- inflateMemBalloonTask,
- MEM_BALLOON_INFLATE_INTERVAL_MILLIS,
- )
- }
- }
- else -> {
- Log.e(TAG, "unrecognized lifecycle event: $event")
- }
- }
+ override fun onCreate() {
+ super.onCreate()
+ val threadFactory = TerminalThreadFactory(getApplicationContext())
+ bgThreads = Executors.newCachedThreadPool(threadFactory)
+ mainWorkerThread = Executors.newSingleThreadExecutor(threadFactory)
+ image = InstalledImage.getDefault(this)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
- if (intent.action == ACTION_STOP_VM_LAUNCHER_SERVICE) {
- 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)
- } else {
- // If there is no Debian service or it fails to shutdown, just stop the service.
+ val resultReceiver =
+ intent.getParcelableExtra<ResultReceiver>(
+ Intent.EXTRA_RESULT_RECEIVER,
+ ResultReceiver::class.java,
+ )!!
+
+ when (intent.action) {
+ ACTION_START_VM -> {
+ val notification =
+ intent.getParcelableExtra<Notification>(
+ EXTRA_NOTIFICATION,
+ Notification::class.java,
+ )!!
+
+ val displayInfo =
+ intent.getParcelableExtra(EXTRA_DISPLAY_INFO, DisplayInfo::class.java)!!
+
+ // 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.getApparentSize())
+
+ mainWorkerThread.submit({
+ doStart(notification, displayInfo, diskSize, resultReceiver)
+ })
+
+ // Do this outside of the main worker thread, so that we don't cause
+ // ForegroundServiceDidNotStartInTimeException
+ startForeground(this.hashCode(), notification)
+ }
+ ACTION_SHUTDOWN_VM -> mainWorkerThread.submit({ doShutdown(resultReceiver) })
+ else -> {
+ Log.e(TAG, "Unknown command " + intent.action)
stopSelf()
}
- return START_NOT_STICKY
}
- if (virtualMachine != null) {
- Log.d(TAG, "VM instance is already started")
- return START_NOT_STICKY
- }
- executorService = Executors.newCachedThreadPool(TerminalThreadFactory(applicationContext))
+ return START_NOT_STICKY
+ }
+
+ 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
+ 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",
+ )
+
+ if (curSize != expectedSize) {
+ try {
+ image.truncate(expectedSize)
+ } catch (e: IOException) {
+ throw RuntimeException("Failed to truncate a disk", e)
+ }
+ }
+ }
+
+ // 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,
+ displayInfo: DisplayInfo,
+ diskSize: Long,
+ resultReceiver: ResultReceiver,
+ ) {
val image = InstalledImage.getDefault(this)
val json = ConfigJson.from(this, image.configPath)
val configBuilder = json.toConfigBuilder(this)
val customImageConfigBuilder = json.toCustomImageConfigBuilder(this)
- val displaySize = intent.getParcelableExtra(EXTRA_DISPLAY_INFO, DisplayInfo::class.java)
+
+ if (Flags.terminalStorageBalloon()) {
+ // 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)
+ }
customImageConfigBuilder.setAudioConfig(
AudioConfig.Builder().setUseSpeaker(true).setUseMicrophone(true).build()
)
- if (overrideConfigIfNecessary(customImageConfigBuilder, displaySize)) {
+ if (overrideConfigIfNecessary(customImageConfigBuilder, displayInfo)) {
configBuilder.setCustomImageConfig(customImageConfigBuilder.build())
}
val config = configBuilder.build()
- Trace.beginSection("vmCreate")
- val runner: Runner =
+ runner =
try {
- create(this, config)
+ Runner.create(this, config)
} catch (e: VirtualMachineException) {
throw RuntimeException("cannot create runner", e)
}
- Trace.endSection()
- Trace.beginAsyncSection("debianBoot", 0)
- virtualMachine = runner.vm
- resultReceiver =
- intent.getParcelableExtra<ResultReceiver?>(
- Intent.EXTRA_RESULT_RECEIVER,
- ResultReceiver::class.java,
- )
+ val virtualMachine = runner!!.vm
+ val mbc = MemBalloonController(this, virtualMachine)
+ mbc.start()
- runner.exitStatus.thenAcceptAsync { success: Boolean ->
- resultReceiver?.send(if (success) RESULT_STOP else RESULT_ERROR, null)
+ runner!!.exitStatus.thenAcceptAsync { success: Boolean ->
+ mbc.stop()
+ resultReceiver.send(if (success) RESULT_STOP else RESULT_ERROR, null)
stopSelf()
}
- val logDir = getFileStreamPath(virtualMachine!!.name + ".log").toPath()
- Logger.setup(virtualMachine!!, logDir, executorService!!)
+ val logDir = getFileStreamPath(virtualMachine.name + ".log").toPath()
+ Logger.setup(virtualMachine, logDir, bgThreads)
- val notification =
- intent.getParcelableExtra<Notification?>(EXTRA_NOTIFICATION, Notification::class.java)
-
- startForeground(this.hashCode(), notification)
-
- resultReceiver!!.send(RESULT_START, null)
+ resultReceiver.send(RESULT_START, null)
portNotifier = PortNotifier(this)
@@ -241,13 +263,20 @@
val bundle = Bundle()
bundle.putString(KEY_TERMINAL_IPADDRESS, ipAddress)
bundle.putInt(KEY_TERMINAL_PORT, port)
- resultReceiver!!.send(RESULT_TERMINAL_AVAIL, bundle)
+ resultReceiver.send(RESULT_TERMINAL_AVAIL, bundle)
startDebianServer(ipAddress)
},
- executorService,
+ bgThreads,
)
-
- return START_NOT_STICKY
+ .exceptionallyAsync(
+ { e ->
+ Log.e(TAG, "Failed to start VM", e)
+ resultReceiver.send(RESULT_ERROR, null)
+ stopSelf()
+ null
+ },
+ bgThreads,
+ )
}
private fun getTerminalServiceInfo(): CompletableFuture<NsdServiceInfo> {
@@ -282,13 +311,15 @@
}
},
)
+
+ resolvedInfo.orTimeout(VM_BOOT_TIMEOUT_SECONDS.toLong(), TimeUnit.SECONDS)
return resolvedInfo
}
private fun createNotificationForTerminalClose(): Notification {
val stopIntent = Intent()
stopIntent.setClass(this, VmLauncherService::class.java)
- stopIntent.setAction(ACTION_STOP_VM_LAUNCHER_SERVICE)
+ stopIntent.setAction(ACTION_SHUTDOWN_VM)
val stopPendingIntent =
PendingIntent.getService(
this,
@@ -349,7 +380,7 @@
// Set the initial display size
// TODO(jeongik): set up the display size on demand
- if (terminalGuiSupport() && displayInfo != null) {
+ if (Flags.terminalGuiSupport() && displayInfo != null) {
builder
.setDisplayConfig(
VirtualMachineCustomImageConfig.DisplayConfig.Builder()
@@ -411,7 +442,7 @@
return
}
- executorService!!.execute(
+ bgThreads.execute(
Runnable {
// TODO(b/373533555): we can use mDNS for that.
val debianServicePortFile = File(filesDir, "debian_service_port")
@@ -424,40 +455,77 @@
}
}
)
+
+ if (Flags.terminalStorageBalloon()) {
+ StorageBalloonWorker.start(this, debianService!!)
+ }
}
- override fun onDestroy() {
- portNotifier?.stop()
- getSystemService<NotificationManager?>(NotificationManager::class.java).cancelAll()
- stopDebianServer()
- if (virtualMachine != null) {
- if (virtualMachine!!.getStatus() == VirtualMachine.STATUS_RUNNING) {
- try {
- virtualMachine!!.stop()
- stopForeground(STOP_FOREGROUND_REMOVE)
- } catch (e: VirtualMachineException) {
- Log.e(TAG, "failed to stop a VM instance", e)
- }
- }
- executorService?.shutdownNow()
- executorService = null
- virtualMachine = null
+ @WorkerThread
+ private fun doShutdown(resultReceiver: ResultReceiver?) {
+ runner?.exitStatus?.thenAcceptAsync { success: Boolean ->
+ resultReceiver?.send(if (success) RESULT_STOP else RESULT_ERROR, null)
+ stopSelf()
}
- super.onDestroy()
+ 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?.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()
+ }
}
private fun stopDebianServer() {
debianService?.killForwarderHost()
+ debianService?.closeStorageBalloonRequestQueue()
server?.shutdown()
}
+ override fun onDestroy() {
+ mainWorkerThread.submit({
+ if (runner?.vm?.getStatus() == VirtualMachine.STATUS_RUNNING) {
+ doShutdown(null)
+ }
+ })
+ portNotifier?.stop()
+ getSystemService<NotificationManager?>(NotificationManager::class.java).cancelAll()
+ stopDebianServer()
+ bgThreads.shutdownNow()
+ mainWorkerThread.shutdown()
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ super.onDestroy()
+ }
+
companion object {
- private const val EXTRA_NOTIFICATION = "EXTRA_NOTIFICATION"
- private const val ACTION_START_VM_LAUNCHER_SERVICE =
- "android.virtualization.START_VM_LAUNCHER_SERVICE"
- const val EXTRA_DISPLAY_INFO = "EXTRA_DISPLAY_INFO"
- const val ACTION_STOP_VM_LAUNCHER_SERVICE: String =
- "android.virtualization.STOP_VM_LAUNCHER_SERVICE"
+ private const val ACTION_START_VM: String = PREFIX + "ACTION_START_VM"
+ private const val EXTRA_NOTIFICATION = PREFIX + "EXTRA_NOTIFICATION"
+ private const val EXTRA_DISPLAY_INFO = PREFIX + "EXTRA_DISPLAY_INFO"
+ private const val EXTRA_DISK_SIZE = PREFIX + "EXTRA_DISK_SIZE"
+
+ private const val ACTION_SHUTDOWN_VM: String = PREFIX + "ACTION_SHUTDOWN_VM"
private const val RESULT_START = 0
private const val RESULT_STOP = 1
@@ -467,28 +535,29 @@
private const val KEY_TERMINAL_IPADDRESS = "address"
private const val KEY_TERMINAL_PORT = "port"
- private const val INITIAL_MEM_BALLOON_PERCENT = 10
- private const val MAX_MEM_BALLOON_PERCENT = 50
- private const val MEM_BALLOON_INFLATE_INTERVAL_MILLIS = 60000L
- private const val MEM_BALLOON_PERCENT_STEP = 5
+ private const val SHUTDOWN_TIMEOUT_SECONDS = 3L
- private fun getMyIntent(context: Context): Intent {
- return Intent(context.getApplicationContext(), VmLauncherService::class.java)
- }
+ private const val GUEST_SPARSE_DISK_SIZE_PERCENTAGE = 95
+ private const val EXPECTED_PHYSICAL_SIZE_PERCENTAGE_FOR_NON_SPARSE = 90
- fun run(
- context: Context,
- callback: VmLauncherServiceCallback?,
- notification: Notification?,
- displayInfo: DisplayInfo,
- ) {
- val i = getMyIntent(context)
- val resultReceiver: ResultReceiver =
+ private val VM_BOOT_TIMEOUT_SECONDS: Int =
+ {
+ val deviceName = SystemProperties.get("ro.product.vendor.device", "")
+ val cuttlefish = deviceName.startsWith("vsoc_")
+ val goldfish = deviceName.startsWith("emu64")
+
+ if (cuttlefish || goldfish) {
+ 3 * 60
+ } else {
+ 30
+ }
+ }()
+
+ private fun prepareIntent(context: Context, callback: VmLauncherServiceCallback): Intent {
+ val intent = Intent(context.getApplicationContext(), VmLauncherService::class.java)
+ val resultReceiver =
object : ResultReceiver(Handler(Looper.myLooper()!!)) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
- if (callback == null) {
- return
- }
when (resultCode) {
RESULT_START -> callback.onVmStart()
RESULT_TERMINAL_AVAIL -> {
@@ -498,26 +567,42 @@
}
RESULT_STOP -> callback.onVmStop()
RESULT_ERROR -> callback.onVmError()
+ else -> Log.e(TAG, "unknown result code: " + resultCode)
}
}
}
- i.putExtra(Intent.EXTRA_RESULT_RECEIVER, getResultReceiverForIntent(resultReceiver))
+
+ val parcel = Parcel.obtain()
+ resultReceiver.writeToParcel(parcel, 0)
+ parcel.setDataPosition(0)
+ intent.putExtra(
+ Intent.EXTRA_RESULT_RECEIVER,
+ ResultReceiver.CREATOR.createFromParcel(parcel).also { parcel.recycle() },
+ )
+ return intent
+ }
+
+ fun getIntentForStart(
+ context: Context,
+ callback: VmLauncherServiceCallback,
+ notification: Notification?,
+ displayInfo: DisplayInfo,
+ diskSize: Long?,
+ ): Intent {
+ val i = prepareIntent(context, callback)
+ i.setAction(ACTION_START_VM)
i.putExtra(EXTRA_NOTIFICATION, notification)
i.putExtra(EXTRA_DISPLAY_INFO, displayInfo)
- context.startForegroundService(i)
+ if (diskSize != null) {
+ i.putExtra(EXTRA_DISK_SIZE, diskSize)
+ }
+ return i
}
- private fun getResultReceiverForIntent(r: ResultReceiver): ResultReceiver {
- val parcel = Parcel.obtain()
- r.writeToParcel(parcel, 0)
- parcel.setDataPosition(0)
- return ResultReceiver.CREATOR.createFromParcel(parcel).also { parcel.recycle() }
- }
-
- fun stop(context: Context) {
- val i = getMyIntent(context)
- i.setAction(ACTION_STOP_VM_LAUNCHER_SERVICE)
- context.startService(i)
+ fun getIntentForShutdown(context: Context, callback: VmLauncherServiceCallback): Intent {
+ val i = prepareIntent(context, callback)
+ i.setAction(ACTION_SHUTDOWN_VM)
+ return i
}
}
}
diff --git a/android/TerminalApp/res/layout/tabitem_terminal.xml b/android/TerminalApp/res/layout/tabitem_terminal.xml
index 92e3802..9eba163 100644
--- a/android/TerminalApp/res/layout/tabitem_terminal.xml
+++ b/android/TerminalApp/res/layout/tabitem_terminal.xml
@@ -25,7 +25,7 @@
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_toStartOf="@id/tab_close_button"
- android:gravity="center"
+ android:gravity="center_vertical"
android:padding="8dp"
android:text="@string/tab_default_title"/>
diff --git a/android/TerminalApp/res/values/config.xml b/android/TerminalApp/res/values/config.xml
index 7f0b5e6..a2c9183 100644
--- a/android/TerminalApp/res/values/config.xml
+++ b/android/TerminalApp/res/values/config.xml
@@ -16,4 +16,5 @@
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<bool name="terminal_portrait_only">true</bool>
+ <item name="activity_split_ratio" format="float" type="dimen">0.3</item>
</resources>
diff --git a/android/TerminalApp/res/values/dimens.xml b/android/TerminalApp/res/values/dimens.xml
deleted file mode 100644
index e00ef7c..0000000
--- a/android/TerminalApp/res/values/dimens.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright 2024 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- -->
-
-<resources>
- <dimen name="activity_split_ratio">0.3</dimen>
-</resources>
\ No newline at end of file
diff --git a/android/TerminalApp/res/values/strings.xml b/android/TerminalApp/res/values/strings.xml
index a6d461e..273032e 100644
--- a/android/TerminalApp/res/values/strings.xml
+++ b/android/TerminalApp/res/values/strings.xml
@@ -75,6 +75,8 @@
<string name="settings_disk_resize_resize_gb_assigned_format"><xliff:g id="assigned_size" example="10GB">\u200E%1$s\u200E</xliff:g> assigned</string>
<!-- Settings menu option description format of the maximum resizable disk size. [CHAR LIMIT=none] -->
<string name="settings_disk_resize_resize_gb_max_format"><xliff:g id="max_size" example="256GB">\u200E%1$s\u200E</xliff:g> max</string>
+ <!-- Snackbar message for showing not enough space error. [CHAR LIMIT=none] -->
+ <string name="settings_disk_resize_not_enough_space_message">Not enough space on the device to resize disk</string>
<!-- Settings menu button to cancel disk resize. [CHAR LIMIT=16] -->
<string name="settings_disk_resize_resize_cancel">Cancel</string>
<!-- Settings menu button to apply change Terminal app. This will launch a confirmation dialog [CHAR LIMIT=16] -->
diff --git a/android/TerminalApp/res/xml/main_split_config.xml b/android/TerminalApp/res/xml/main_split_config.xml
deleted file mode 100644
index bd0271b..0000000
--- a/android/TerminalApp/res/xml/main_split_config.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright 2024 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- -->
-
-<resources xmlns:window="http://schemas.android.com/apk/res-auto">
-
- <!-- Define a split for the named activities. -->
- <SplitPairRule
- window:clearTop="true"
- window:finishPrimaryWithSecondary="adjacent"
- window:finishSecondaryWithPrimary="always"
- window:splitLayoutDirection="locale"
- window:splitMaxAspectRatioInPortrait="alwaysAllow"
- window:splitMinWidthDp="@integer/split_min_width"
- window:splitRatio="@dimen/activity_split_ratio">
- <SplitPairFilter
- window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
- window:secondaryActivityName="com.android.virtualization.terminal.SettingsDiskResizeActivity" />
- <SplitPairFilter
- window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
- window:secondaryActivityName="com.android.virtualization.terminal.SettingsPortForwardingActivity" />
- <SplitPairFilter
- window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
- window:secondaryActivityName="com.android.virtualization.terminal.SettingsRecoveryActivity" />
- </SplitPairRule>
-
- <SplitPlaceholderRule
- window:placeholderActivityName="com.android.virtualization.terminal.SettingsDiskResizeActivity"
- window:finishPrimaryWithPlaceholder="adjacent"
- window:splitLayoutDirection="locale"
- window:splitMaxAspectRatioInPortrait="alwaysAllow"
- window:splitMinWidthDp="@integer/split_min_width"
- window:splitRatio="@dimen/activity_split_ratio"
- window:stickyPlaceholder="false">
- <ActivityFilter
- window:activityName="com.android.virtualization.terminal.SettingsActivity"/>
- </SplitPlaceholderRule>
-</resources>
\ No newline at end of file
diff --git a/android/virtmgr/src/aidl.rs b/android/virtmgr/src/aidl.rs
index 1c4c2eb..190acc7 100644
--- a/android/virtmgr/src/aidl.rs
+++ b/android/virtmgr/src/aidl.rs
@@ -597,9 +597,10 @@
config: &VirtualMachineConfig,
) -> binder::Result<(VmContext, Cid, PathBuf)> {
const NUM_ATTEMPTS: usize = 5;
+ let name = get_name(config);
for _ in 0..NUM_ATTEMPTS {
- let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
+ let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(name, requester_debug_pid)?;
let cid = vm_context.getCid()? as Cid;
let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
@@ -640,6 +641,24 @@
let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
+ let instance_id = extract_instance_id(config);
+ // Require vendor instance IDs to start with a specific prefix so that they don't conflict
+ // with system instance IDs.
+ //
+ // We should also make sure that non-vendor VMs do not use the vendor prefix, but there are
+ // already system VMs in the wild that may have randomly generated IDs with the prefix, so,
+ // for now, we only check in one direction.
+ const INSTANCE_ID_VENDOR_PREFIX: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF];
+ if matches!(calling_partition, CallingPartition::Vendor | CallingPartition::Odm)
+ && !instance_id.starts_with(INSTANCE_ID_VENDOR_PREFIX)
+ {
+ return Err(anyhow!(
+ "vendor initiated VMs must have instance IDs starting with 0xFFFFFFFF, got {}",
+ hex::encode(instance_id)
+ ))
+ .or_service_specific_exception(-1);
+ }
+
check_config_features(config)?;
if cfg!(early) {
@@ -667,7 +686,6 @@
check_gdb_allowed(config)?;
}
- let instance_id = extract_instance_id(config);
let mut device_tree_overlays = vec![];
if let Some(dt_overlay) =
maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
@@ -797,9 +815,8 @@
.or_service_specific_exception(-1)?;
}
- // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
- // have unstable interfaces.
- // TODO(b/316431494): remove once Treble interfaces are stabilized.
+ // Check if files for payloads and bases are on the same side of the Treble boundary as the
+ // calling process, as they may have unstable interfaces.
check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
let zero_filler_path = temporary_directory.join("zero.img");
@@ -1053,6 +1070,14 @@
}
}
+/// Returns the name of the config
+fn get_name(config: &VirtualMachineConfig) -> &str {
+ match config {
+ VirtualMachineConfig::AppConfig(config) => &config.name,
+ VirtualMachineConfig::RawConfig(config) => &config.name,
+ }
+}
+
fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
let VirtualMachineConfig::AppConfig(config) = config else {
return Ok(None);
diff --git a/android/virtmgr/src/crosvm.rs b/android/virtmgr/src/crosvm.rs
index 5f81e90..15a4199 100644
--- a/android/virtmgr/src/crosvm.rs
+++ b/android/virtmgr/src/crosvm.rs
@@ -677,6 +677,10 @@
}
}
+ fn is_vm_running(&self) -> bool {
+ matches!(&*self.vm_state.lock().unwrap(), VmState::Running { .. })
+ }
+
/// Returns the last reported state of the VM payload.
pub fn payload_state(&self) -> PayloadState {
*self.payload_state.lock().unwrap()
@@ -726,6 +730,9 @@
/// Returns current virtio-balloon size.
pub fn get_memory_balloon(&self) -> Result<u64, Error> {
+ if !self.is_vm_running() {
+ bail!("get_memory_balloon when VM is not running");
+ }
if !self.balloon_enabled {
bail!("virtio-balloon is not enabled");
}
@@ -748,6 +755,9 @@
/// Inflates the virtio-balloon by `num_bytes` to reclaim guest memory. Called in response to
/// memory-trimming notifications.
pub fn set_memory_balloon(&self, num_bytes: u64) -> Result<(), Error> {
+ if !self.is_vm_running() {
+ bail!("set_memory_balloon when VM is not running");
+ }
if !self.balloon_enabled {
bail!("virtio-balloon is not enabled");
}
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/VirtualMachineDebugInfo.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineDebugInfo.aidl
index 9f033b1..eb71028 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineDebugInfo.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineDebugInfo.aidl
@@ -19,6 +19,9 @@
/** Information about a running VM, for debug purposes only. */
parcelable VirtualMachineDebugInfo {
+ /** Name of the VM. */
+ String name;
+
/** The CID assigned to the VM. */
int cid;
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/aidl/android/system/virtualizationservice_internal/IVfioHandler.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVfioHandler.aidl
index 2cf4efd..4ded2a9 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVfioHandler.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVfioHandler.aidl
@@ -16,7 +16,6 @@
package android.system.virtualizationservice_internal;
import android.system.virtualizationservice.AssignableDevice;
-import android.system.virtualizationservice.VirtualMachineDebugInfo;
import android.system.virtualizationservice_internal.AtomVmBooted;
import android.system.virtualizationservice_internal.AtomVmCreationRequested;
import android.system.virtualizationservice_internal.AtomVmExited;
diff --git a/android/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVirtualizationServiceInternal.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVirtualizationServiceInternal.aidl
index 4f549cb..3d4a813 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVirtualizationServiceInternal.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVirtualizationServiceInternal.aidl
@@ -39,7 +39,7 @@
* The resources will not be recycled as long as there is a strong reference
* to the returned object.
*/
- IGlobalVmContext allocateGlobalVmContext(int requesterDebugPid);
+ IGlobalVmContext allocateGlobalVmContext(String name, int requesterDebugPid);
/** Forwards a VmBooted atom to statsd. */
void atomVmBooted(in AtomVmBooted atom);
diff --git a/android/virtualizationservice/src/aidl.rs b/android/virtualizationservice/src/aidl.rs
index 62cede8..e26cd4f 100644
--- a/android/virtualizationservice/src/aidl.rs
+++ b/android/virtualizationservice/src/aidl.rs
@@ -273,6 +273,7 @@
fn allocateGlobalVmContext(
&self,
+ name: &str,
requester_debug_pid: i32,
) -> binder::Result<Strong<dyn IGlobalVmContext>> {
check_manage_access()?;
@@ -281,7 +282,7 @@
let requester_debug_pid = requester_debug_pid as pid_t;
let state = &mut *self.state.lock().unwrap();
state
- .allocate_vm_context(requester_uid, requester_debug_pid)
+ .allocate_vm_context(name, requester_uid, requester_debug_pid)
.or_binder_exception(ExceptionCode::ILLEGAL_STATE)
}
@@ -311,6 +312,7 @@
.map(|vm| {
let vm = vm.lock().unwrap();
VirtualMachineDebugInfo {
+ name: vm.name.clone(),
cid: vm.cid as i32,
temporaryDirectory: vm.get_temp_dir().to_string_lossy().to_string(),
requesterUid: vm.requester_uid as i32,
@@ -487,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);
@@ -665,6 +670,8 @@
#[derive(Debug, Default)]
struct GlobalVmInstance {
+ /// Name of the VM
+ name: String,
/// The unique CID assigned to the VM for vsock communication.
cid: Cid,
/// UID of the client who requested this VM instance.
@@ -760,6 +767,7 @@
fn allocate_vm_context(
&mut self,
+ name: &str,
requester_uid: uid_t,
requester_debug_pid: pid_t,
) -> Result<Strong<dyn IGlobalVmContext>> {
@@ -768,6 +776,7 @@
let cid = self.get_next_available_cid()?;
let instance = Arc::new(Mutex::new(GlobalVmInstance {
+ name: name.to_owned(),
cid,
requester_uid,
requester_debug_pid,
diff --git a/build/apex/Android.bp b/build/apex/Android.bp
index 8934de0..f0eba7f 100644
--- a/build/apex/Android.bp
+++ b/build/apex/Android.bp
@@ -56,6 +56,7 @@
"libvirtualizationservice_jni",
"libvirtualmachine_jni",
],
+ native_shared_libs: ["libavf"],
// TODO(b/295593640) Unfortunately these are added to the apex even though they are unused.
// Once the build system is fixed, remove this.
unwanted_transitive_deps: [
@@ -108,7 +109,6 @@
"rialto_bin",
"android_bootloader_crosvm_aarch64",
],
- native_shared_libs: ["libavf"],
},
x86_64: {
binaries: [
@@ -129,7 +129,6 @@
prebuilts: [
"android_bootloader_crosvm_x86_64",
],
- native_shared_libs: ["libavf"],
},
},
binaries: [
diff --git a/build/avf_flags.aconfig b/build/avf_flags.aconfig
index 921c374..571c359 100644
--- a/build/avf_flags.aconfig
+++ b/build/avf_flags.aconfig
@@ -16,4 +16,12 @@
namespace: "virtualization"
description: "Flag for GUI support in terminal"
bug: "386296118"
+}
+
+flag {
+ name: "terminal_storage_balloon"
+ is_exported: true
+ namespace: "virtualization"
+ description: "Flag for storage ballooning support in terminal"
+ bug: "382174138"
}
\ No newline at end of file
diff --git a/build/debian/build.sh b/build/debian/build.sh
index dfbf493..f751b30 100755
--- a/build/debian/build.sh
+++ b/build/debian/build.sh
@@ -215,6 +215,7 @@
build_rust_as_deb forwarder_guest
build_rust_as_deb forwarder_guest_launcher
build_rust_as_deb shutdown_runner
+ build_rust_as_deb storage_balloon_agent
}
package_custom_kernel() {
diff --git a/build/debian/fai_config/package_config/AVF b/build/debian/fai_config/package_config/AVF
index 3aa8ab0..f1ee065 100644
--- a/build/debian/fai_config/package_config/AVF
+++ b/build/debian/fai_config/package_config/AVF
@@ -8,6 +8,7 @@
forwarder-guest
forwarder-guest-launcher
shutdown-runner
+storage-balloon-agent
weston
xwayland
mesa-vulkan-drivers
diff --git a/build/debian/fai_config/scripts/AVF/20-useradd b/build/debian/fai_config/scripts/AVF/20-useradd
index b92648a..2289a2a 100755
--- a/build/debian/fai_config/scripts/AVF/20-useradd
+++ b/build/debian/fai_config/scripts/AVF/20-useradd
@@ -2,3 +2,7 @@
$ROOTCMD useradd -m -u 1000 -N -G sudo,video,render -s /usr/bin/bash droid
$ROOTCMD echo 'droid ALL=(ALL) NOPASSWD:ALL' >> $target/etc/sudoers
+$ROOTCMD cat >> $target/home/droid/.bashrc <<EOF
+# Show title of current running command
+trap 'echo -ne "\e]0;\$BASH_COMMAND\007"' DEBUG
+EOF
diff --git a/guest/microdroid_manager/microdroid_manager.rc b/guest/microdroid_manager/microdroid_manager.rc
index 9fa8a9d..48cc6d7 100644
--- a/guest/microdroid_manager/microdroid_manager.rc
+++ b/guest/microdroid_manager/microdroid_manager.rc
@@ -8,6 +8,7 @@
# CAP_SYS_BOOT is required to exec kexecload from microdroid_manager
# CAP_SETPCAP is required to allow microdroid_manager to drop capabilities
# before executing the payload
- capabilities AUDIT_CONTROL SYS_ADMIN SYS_BOOT SETPCAP SETUID SETGID
+ # CAP_SYS_NICE is required for microdroid_manager to adjust priority of the payload
+ capabilities AUDIT_CONTROL SYS_ADMIN SYS_BOOT SETPCAP SETUID SETGID SYS_NICE
user root
socket vm_payload_service stream 0666 system system
diff --git a/guest/microdroid_manager/src/main.rs b/guest/microdroid_manager/src/main.rs
index 4537834..a95bcb2 100644
--- a/guest/microdroid_manager/src/main.rs
+++ b/guest/microdroid_manager/src/main.rs
@@ -710,7 +710,21 @@
info!("notifying payload started");
service.notifyPayloadStarted()?;
- let exit_status = command.spawn()?.wait()?;
+ let mut payload_process = command.spawn().context("failed to spawn payload process")?;
+ info!("payload pid = {:?}", payload_process.id());
+
+ // SAFETY: setpriority doesn't take any pointers
+ unsafe {
+ let ret = libc::setpriority(libc::PRIO_PROCESS, payload_process.id(), -20);
+ if ret != 0 {
+ error!(
+ "failed to adjust priority of the payload: {:#?}",
+ std::io::Error::last_os_error()
+ );
+ }
+ }
+
+ let exit_status = payload_process.wait()?;
match exit_status.code() {
Some(exit_code) => Ok(exit_code),
None => Err(match exit_status.signal() {
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 652ca90..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
@@ -147,6 +158,10 @@
| offset = (FOURTH - HEAD) |
| size = (FOURTH_END - FOURTH) |
+-------------------------------+
+| [Entry 4] | <-- Entry 4 is present since version 1.3
+| offset = (FIFTH - HEAD) |
+| size = (FIFTH_END - FIFTH) |
++-------------------------------+
| ... |
+-------------------------------+
| [Entry n] |
@@ -168,7 +183,11 @@
| {Fourth blob: VM reference DT}|
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ <-- FOURTH_END
| (Padding to 8-byte alignment) |
-+===============================+
++===============================+ <-- FIFTH
+| {Fifth blob: Reserved Memory} |
++~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ <-- FIFTH_END
+| (Padding to 8-byte alignment) |
++===============================+ <-- FIFTH
| ... |
+===============================+ <-- TAIL
```
@@ -238,6 +257,31 @@
[secretkeeper_key]: https://android.googlesource.com/platform/system/secretkeeper/+/refs/heads/main/README.md#secretkeeper-public-key
[vendor_hashtree_digest]: ../../build/microdroid/README.md#verification-of-vendor-image
+#### Version 1.3 {#pvmfw-data-v1-3}
+
+In version 1.3, a fifth blob is added.
+
+- entry 4, if present, contains potentially confidential data to be passed to
+ specific guests identified from their VM name. If the data is confidential,
+ this feature should only be used with guests using a fixed rollback
+ protection mechanism to prevent rollback attacks from a malicious host. Data
+ is passed as a reserved-memory region through the device tree with the
+ provided properties at an address which is implementation defined. Multiple
+ regions may be passed to the same guest. The format is as follows.
+
+ ```rust
+ #[repr(C)]
+ struct ReservedMemConfigEntry<const N: usize> {
+ /// The number of headers contained in this blob.
+ count: u32,
+ /// The [reserved memory headers](src/reserved_mem.rs) describing the passed data.
+ headers: [RMemHeader; N]
+ /// The actual data being passed. The reserved memory headers point to
+ /// offsets within this array.
+ data: [u8],
+ }
+ ```
+
#### Virtual Platform DICE Chain Handover
The format of the DICE chain entry mentioned above, compatible with the
@@ -477,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}
```
@@ -504,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..38541c5 100644
--- a/guest/pvmfw/avb/tests/utils.rs
+++ b/guest/pvmfw/avb/tests/utils.rs
@@ -148,6 +148,7 @@
expected_rollback_index: u64,
capabilities: Vec<Capability>,
page_size: Option<usize>,
+ expected_name: Option<String>,
) -> Result<()> {
let public_key = load_trusted_public_key()?;
let verified_boot_data = verify_payload(
@@ -168,7 +169,7 @@
capabilities,
rollback_index: expected_rollback_index,
page_size,
- name: None,
+ name: expected_name,
};
assert_eq!(expected_boot_data, verified_boot_data);
diff --git a/guest/pvmfw/src/arch/aarch64/exceptions.rs b/guest/pvmfw/src/arch/aarch64/exceptions.rs
index 4c867fb..c8c0156 100644
--- a/guest/pvmfw/src/arch/aarch64/exceptions.rs
+++ b/guest/pvmfw/src/arch/aarch64/exceptions.rs
@@ -18,9 +18,7 @@
arch::aarch64::exceptions::{
handle_permission_fault, handle_translation_fault, ArmException, Esr, HandleExceptionError,
},
- eprintln, logger,
- power::reboot,
- read_sysreg,
+ logger, read_sysreg,
};
fn handle_exception(exception: &ArmException) -> Result<(), HandleExceptionError> {
@@ -41,55 +39,44 @@
let exception = ArmException::from_el1_regs();
if let Err(e) = handle_exception(&exception) {
- exception.print("sync_exception_current", e, elr);
- reboot()
+ exception.print_and_reboot("sync_exception_current", e, elr);
}
}
#[no_mangle]
extern "C" fn irq_current(_elr: u64, _spsr: u64) {
- eprintln!("irq_current");
- reboot();
+ panic!("irq_current");
}
#[no_mangle]
extern "C" fn fiq_current(_elr: u64, _spsr: u64) {
- eprintln!("fiq_current");
- reboot();
+ panic!("fiq_current");
}
#[no_mangle]
extern "C" fn serr_current(_elr: u64, _spsr: u64) {
let esr = read_sysreg!("esr_el1");
- eprintln!("serr_current");
- eprintln!("esr={esr:#08x}");
- reboot();
+ panic!("serr_current, esr={esr:#08x}");
}
#[no_mangle]
extern "C" fn sync_lower(_elr: u64, _spsr: u64) {
let esr = read_sysreg!("esr_el1");
- eprintln!("sync_lower");
- eprintln!("esr={esr:#08x}");
- reboot();
+ panic!("sync_lower, esr={esr:#08x}");
}
#[no_mangle]
extern "C" fn irq_lower(_elr: u64, _spsr: u64) {
- eprintln!("irq_lower");
- reboot();
+ panic!("irq_lower");
}
#[no_mangle]
extern "C" fn fiq_lower(_elr: u64, _spsr: u64) {
- eprintln!("fiq_lower");
- reboot();
+ panic!("fiq_lower");
}
#[no_mangle]
extern "C" fn serr_lower(_elr: u64, _spsr: u64) {
let esr = read_sysreg!("esr_el1");
- eprintln!("serr_lower");
- eprintln!("esr={esr:#08x}");
- reboot();
+ panic!("serr_lower, esr={esr:#08x}");
}
diff --git a/guest/pvmfw/src/arch/aarch64/payload.rs b/guest/pvmfw/src/arch/aarch64/payload.rs
index 0da8297..3f3ee33 100644
--- a/guest/pvmfw/src/arch/aarch64/payload.rs
+++ b/guest/pvmfw/src/arch/aarch64/payload.rs
@@ -23,13 +23,13 @@
/// 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
+ let dice_handover = slices
+ .dice_handover
.map(|slice| {
let r = slice.as_ptr_range();
(r.start as usize)..(r.end as usize)
})
- .expect("Missing DICE chain");
+ .expect("Missing DICE handover");
deactivate_dynamic_page_tables();
@@ -50,9 +50,9 @@
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.");
+ assert!(dice_handover.is_within(&(scratch.start.0..scratch.end.0)));
+ assert_eq!(dice_handover.start % ASM_STP_ALIGN, 0, "Misaligned guest DICE handover.");
+ assert_eq!(dice_handover.end % ASM_STP_ALIGN, 0, "Misaligned guest DICE handover.");
let stack = layout::stack_range();
@@ -73,17 +73,17 @@
// SAFETY: We're exiting pvmfw by passing the register values we need to a noreturn asm!().
unsafe {
asm!(
- "cmp {scratch}, {bcc}",
+ "cmp {scratch}, {dice_handover}",
"b.hs 1f",
- // Zero .data & .bss until BCC.
+ // Zero .data & .bss until DICE handover.
"0: stp xzr, xzr, [{scratch}], 16",
- "cmp {scratch}, {bcc}",
+ "cmp {scratch}, {dice_handover}",
"b.lo 0b",
"1:",
- // Skip BCC.
- "mov {scratch}, {bcc_end}",
+ // Skip DICE handover.
+ "mov {scratch}, {dice_handover_end}",
"cmp {scratch}, {scratch_end}",
"b.hs 1f",
@@ -93,7 +93,7 @@
"b.lo 0b",
"1:",
- // Flush d-cache over .data & .bss (including BCC).
+ // Flush d-cache over .data & .bss (including DICE handover).
"0: dc cvau, {cache_line}",
"add {cache_line}, {cache_line}, {dcache_line_size}",
"cmp {cache_line}, {scratch_end}",
@@ -159,8 +159,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(),
+ dice_handover = in(reg) u64::try_from(dice_handover.start).unwrap(),
+ dice_handover_end = in(reg) u64::try_from(dice_handover.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..1f9eacf 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: &'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,15 @@
entries[i] = Some(chunk);
}
}
- let [bcc, debug_policy, vm_dtbo, vm_ref_dt] = entries;
+ let [dice_handover, debug_policy, vm_dtbo, vm_ref_dt] = entries;
- // The platform BCC has always been required.
- let bcc = bcc.unwrap();
+ // The platform DICE handover has always been required.
+ let dice_handover = dice_handover.unwrap();
// 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/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 87%
rename from guest/pvmfw/src/dice.rs
rename to guest/pvmfw/src/dice/mod.rs
index 49a3807..8317e48 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;
@@ -101,13 +104,13 @@
Ok(Self { code_hash, auth_hash, mode, security_version, rkp_vm_marker, 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
@@ -121,7 +124,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(())
}
@@ -181,6 +184,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;
@@ -334,7 +338,7 @@
inputs
.clone()
- .write_next_bcc(
+ .write_next_handover(
sample_dice_input,
&[0u8; HIDDEN_SIZE],
Some([0u8; 64]),
@@ -343,11 +347,11 @@
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]),
@@ -356,11 +360,11 @@
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]),
@@ -369,25 +373,24 @@
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 mut buffer = [0; 4096];
inputs
.clone()
- .write_next_bcc(
- &bcc_handover0_bytes,
+ .write_next_handover(
+ &handover0_bytes,
&[0u8; HIDDEN_SIZE],
Some([0u8; 64]),
true,
@@ -397,15 +400,15 @@
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,
@@ -415,15 +418,15 @@
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,
@@ -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..46b1971 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,21 @@
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,
config_entries.debug_policy,
config_entries.vm_dtbo,
config_entries.vm_ref_dt,
)?;
- slices.add_dice_chain(next_bcc);
+ slices.add_dice_handover(next_dice_handover);
// 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();
+ config_entries.dice_handover.zeroize();
unshare_all_mmio_except_uart().map_err(|e| {
error!("Failed to unshare MMIO ranges: {e}");
@@ -180,8 +180,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 +201,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 +218,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(dice_handover) => {
+ config::Entries { dice_handover, ..Default::default() }
+ }
}
}
}
diff --git a/guest/pvmfw/src/fdt.rs b/guest/pvmfw/src/fdt.rs
index 59399b3..8adf8e5 100644
--- a/guest/pvmfw/src/fdt.rs
+++ b/guest/pvmfw/src/fdt.rs
@@ -1360,7 +1360,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: &[u8],
new_instance: bool,
strict_boot: bool,
debug_policy: Option<&[u8]>,
@@ -1382,7 +1382,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 +1400,15 @@
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: &[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())
+ let addr = (handover.as_ptr() as usize).try_into().unwrap();
+ let size = handover.len().try_into().unwrap();
+ node.setprop_addrrange_inplace(c"reg", addr, size)
}
fn empty_or_delete_prop(
diff --git a/guest/pvmfw/src/main.rs b/guest/pvmfw/src/main.rs
index 9afbcc3..9f1b5e6 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,8 +31,7 @@
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;
@@ -41,7 +39,6 @@
use alloc::boxed::Box;
use bssl_avf::Digester;
use diced_open_dice::{bcc_handover_parse, DiceArtifacts, DiceContext, Hidden, VM_KEY_ALGORITHM};
-use hypervisor_backends::get_mem_sharer;
use libfdt::Fdt;
use log::{debug, error, info, trace, warn};
use pvmfw_avb::verify_payload;
@@ -55,7 +52,7 @@
untrusted_fdt: &mut Fdt,
signed_kernel: &[u8],
ramdisk: Option<&[u8]>,
- current_bcc_handover: &[u8],
+ current_dice_handover: &[u8],
mut debug_policy: Option<&[u8]>,
vm_dtbo: Option<&mut [u8]>,
vm_ref_dt: Option<&[u8]>,
@@ -70,21 +67,21 @@
debug!("Ramdisk: None");
}
- let bcc_handover = bcc_handover_parse(current_bcc_handover).map_err(|e| {
- error!("Invalid BCC Handover: {e:?}");
- RebootReason::InvalidBcc
+ let dice_handover = bcc_handover_parse(current_dice_handover).map_err(|e| {
+ error!("Invalid DICE Handover: {e:?}");
+ RebootReason::InvalidDiceHandover
})?;
- trace!("BCC: {bcc_handover:x?}");
+ trace!("DICE handover: {dice_handover:x?}");
- let bcc = Bcc::new(bcc_handover.bcc()).map_err(|e| {
+ let dice_chain_info = DiceChainInfo::new(dice_handover.bcc()).map_err(|e| {
error!("{e}");
- RebootReason::InvalidBcc
+ RebootReason::InvalidDiceHandover
})?;
// 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_chain_info.is_debug_mode() {
+ warn!("Ignoring debug policy, DICE handover does not indicate Debug mode");
debug_policy = None;
}
@@ -99,26 +96,19 @@
}
let guest_page_size = verified_boot_data.page_size.unwrap_or(SIZE_4KB);
- // TODO(ptosi): Cache the (single?) granule once, in vmbase.
- let hyp_page_size = if let Some(mem_sharer) = get_mem_sharer() {
- Some(mem_sharer.granule().map_err(|e| {
- error!("Failed to get granule size: {e}");
- RebootReason::InternalError
- })?)
- } else {
- None
- };
+ 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
- })?;
+ let next_dice_handover_size = guest_page_size;
+ let next_dice_handover = heap::aligned_boxed_slice(next_dice_handover_size, guest_page_size)
+ .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_bcc = Box::leak(next_bcc);
+ let next_dice_handover = Box::leak(next_dice_handover);
let dice_inputs = PartialInputs::new(&verified_boot_data).map_err(|e| {
error!("Failed to compute partial DICE inputs: {e:?}");
@@ -130,49 +120,50 @@
fdt,
&verified_boot_data,
&dice_inputs,
- bcc_handover.cdi_seal(),
+ dice_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)
+ let new_dice_handover = if cfg!(dice_changes) {
+ Cow::Borrowed(current_dice_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| {
+ let truncated_dice_handover = dice::chain::truncate(dice_handover).map_err(|e| {
error!("{e}");
RebootReason::InternalError
})?;
- Cow::Owned(truncated_bcc_handover)
+ Cow::Owned(truncated_dice_handover)
};
- trace!("BCC leaf subject public key algorithm: {:?}", bcc.leaf_subject_pubkey().cose_alg);
+ 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: bcc.leaf_subject_pubkey().cose_alg.try_into().map_err(|e| {
+ authority_algorithm: 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(),
+ .write_next_handover(
+ new_dice_handover.as_ref(),
&salt,
instance_hash,
defer_rollback_protection,
- next_bcc,
+ next_dice_handover,
dice_context,
)
.map_err(|e| {
error!("Failed to derive next-stage DICE secrets: {e:?}");
RebootReason::SecretDerivationError
})?;
- flush(next_bcc);
+ flush(next_dice_handover);
let kaslr_seed = u64::from_ne_bytes(rand::random_array().map_err(|e| {
error!("Failed to generated guest KASLR seed: {e}");
@@ -181,7 +172,7 @@
let strict_boot = true;
modify_for_next_stage(
fdt,
- next_bcc,
+ next_dice_handover,
new_instance,
strict_boot,
debug_policy,
@@ -194,7 +185,7 @@
})?;
info!("Starting payload...");
- Ok((next_bcc, debuggable))
+ Ok((next_dice_handover, debuggable))
}
// 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/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/storage_balloon_agent/.cargo/config.toml b/guest/storage_balloon_agent/.cargo/config.toml
new file mode 100644
index 0000000..a451cda
--- /dev/null
+++ b/guest/storage_balloon_agent/.cargo/config.toml
@@ -0,0 +1,6 @@
+[target.aarch64-unknown-linux-gnu]
+linker = "aarch64-linux-gnu-gcc"
+rustflags = ["-C", "target-feature=+crt-static"]
+
+[target.x86_64-unknown-linux-gnu]
+rustflags = ["-C", "target-feature=+crt-static"]
diff --git a/guest/storage_balloon_agent/.gitignore b/guest/storage_balloon_agent/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/guest/storage_balloon_agent/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/guest/storage_balloon_agent/Cargo.toml b/guest/storage_balloon_agent/Cargo.toml
new file mode 100644
index 0000000..ce0e5d7
--- /dev/null
+++ b/guest/storage_balloon_agent/Cargo.toml
@@ -0,0 +1,26 @@
+[package]
+name = "storage_balloon_agent"
+version = "0.1.0"
+edition = "2021"
+license = "Apache-2.0"
+
+[dependencies]
+anyhow = "1.0.94"
+clap = { version = "4.5.20", features = ["derive"] }
+env_logger = "0.10.2"
+log = "0.4.22"
+netdev = "0.31.0"
+nix = { version = "0.28.0", features = ["fs"] }
+prost = "0.13.3"
+tokio = { version = "1.40.0", features = ["rt-multi-thread"] }
+tonic = "0.12.3"
+
+[build-dependencies]
+tonic-build = "0.12.3"
+
+[package.metadata.deb]
+maintainer = "ferrochrome-dev@google.com"
+copyright = "2025, The Android Open Source Project"
+depends = "$auto"
+maintainer-scripts = "debian/"
+systemd-units = { }
diff --git a/guest/storage_balloon_agent/build.rs b/guest/storage_balloon_agent/build.rs
new file mode 100644
index 0000000..e3939d4
--- /dev/null
+++ b/guest/storage_balloon_agent/build.rs
@@ -0,0 +1,7 @@
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let proto_file = "../../libs/debian_service/proto/DebianService.proto";
+
+ tonic_build::compile_protos(proto_file).unwrap();
+
+ Ok(())
+}
diff --git a/guest/storage_balloon_agent/debian/service b/guest/storage_balloon_agent/debian/service
new file mode 100644
index 0000000..0e9b03a
--- /dev/null
+++ b/guest/storage_balloon_agent/debian/service
@@ -0,0 +1,17 @@
+[Unit]
+After=syslog.target
+After=network.target
+After=virtiofs_internal.service
+
+[Service]
+ExecStart=/usr/bin/bash -c '/usr/bin/storage_balloon_agent --grpc_port_file /mnt/internal/debian_service_port'
+Type=simple
+Restart=on-failure
+RestartSec=1
+User=root
+Group=root
+StandardOutput=journal
+StandardError=journal
+
+[Install]
+WantedBy=multi-user.target
diff --git a/guest/storage_balloon_agent/rustfmt.toml b/guest/storage_balloon_agent/rustfmt.toml
new file mode 120000
index 0000000..be3dbe2
--- /dev/null
+++ b/guest/storage_balloon_agent/rustfmt.toml
@@ -0,0 +1 @@
+../../../../../build/soong/scripts/rustfmt.toml
\ No newline at end of file
diff --git a/guest/storage_balloon_agent/src/main.rs b/guest/storage_balloon_agent/src/main.rs
new file mode 100644
index 0000000..817b337
--- /dev/null
+++ b/guest/storage_balloon_agent/src/main.rs
@@ -0,0 +1,141 @@
+// 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.
+
+//! gRPC daemon for the storage ballooning feature.
+
+use anyhow::anyhow;
+use anyhow::Context;
+use anyhow::Result;
+use api::debian_service_client::DebianServiceClient;
+use api::StorageBalloonQueueOpeningRequest;
+use api::StorageBalloonRequestItem;
+use clap::Parser;
+use log::debug;
+use log::error;
+use log::info;
+use nix::sys::statvfs::statvfs;
+pub mod api {
+ tonic::include_proto!("com.android.virtualization.terminal.proto");
+}
+
+#[derive(Parser)]
+/// Flags for running command
+pub struct Args {
+ /// IP address
+ #[arg(long)]
+ addr: Option<String>,
+
+ /// path to a file where grpc port number is written
+ #[arg(long)]
+ #[arg(alias = "grpc_port_file")]
+ grpc_port_file: String,
+}
+
+// Calculates how many blocks to be reserved.
+fn calculate_clusters_count(guest_available_bytes: u64) -> Result<u64> {
+ let stat = statvfs("/").context("failed to get statvfs")?;
+ let fr_size = stat.fragment_size() as u64;
+
+ if fr_size == 0 {
+ return Err(anyhow::anyhow!("fragment size is zero, fr_size: {}", fr_size));
+ }
+
+ let total = fr_size.checked_mul(stat.blocks() as u64).context(format!(
+ "overflow in total size calculation, fr_size: {}, blocks: {}",
+ fr_size,
+ stat.blocks()
+ ))?;
+
+ let free = fr_size.checked_mul(stat.blocks_available() as u64).context(format!(
+ "overflow in free size calculation, fr_size: {}, blocks_available: {}",
+ fr_size,
+ stat.blocks_available()
+ ))?;
+
+ let used = total
+ .checked_sub(free)
+ .context(format!("underflow in used size calculation (free > total), which should not happen, total: {}, free: {}", total, free))?;
+
+ let avail = std::cmp::min(free, guest_available_bytes);
+ let balloon_size_bytes = free - avail;
+
+ let reserved_clusters_count = balloon_size_bytes.div_ceil(fr_size);
+
+ debug!("total: {total}, free: {free}, used: {used}, avail: {avail}, balloon: {balloon_size_bytes}, clusters_count: {reserved_clusters_count}");
+
+ Ok(reserved_clusters_count)
+}
+
+fn set_reserved_clusters(clusters_count: u64) -> anyhow::Result<()> {
+ const ROOTFS_DEVICE_NAME: &str = "vda1";
+ std::fs::write(
+ format!("/sys/fs/ext4/{ROOTFS_DEVICE_NAME}/reserved_clusters"),
+ clusters_count.to_string(),
+ )
+ .context("failed to write reserved_clusters")?;
+ Ok(())
+}
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ env_logger::builder().filter_level(log::LevelFilter::Debug).init();
+
+ let args = Args::parse();
+ let gateway_ip_addr = netdev::get_default_gateway()?.ipv4[0];
+ let addr = args.addr.unwrap_or_else(|| gateway_ip_addr.to_string());
+
+ // Wait for `grpc_port_file` becomes available.
+ const GRPC_PORT_MAX_RETRY_COUNT: u32 = 10;
+ for _ in 0..GRPC_PORT_MAX_RETRY_COUNT {
+ if std::path::Path::new(&args.grpc_port_file).exists() {
+ break;
+ }
+ debug!("{} does not exist. Wait 1 second", args.grpc_port_file);
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+ }
+ let grpc_port = std::fs::read_to_string(&args.grpc_port_file)?.trim().to_string();
+ let server_addr = format!("http://{}:{}", addr, grpc_port);
+
+ info!("connect to grpc server {}", server_addr);
+ let mut client = DebianServiceClient::connect(server_addr)
+ .await
+ .map_err(|e| anyhow!("failed to connect to grpc server: {:#}", e))?;
+ info!("connection established");
+
+ let mut res_stream = client
+ .open_storage_balloon_request_queue(tonic::Request::new(
+ StorageBalloonQueueOpeningRequest {},
+ ))
+ .await
+ .map_err(|e| anyhow!("failed to open storage balloon queue: {:#}", e))?
+ .into_inner();
+
+ while let Some(StorageBalloonRequestItem { available_bytes }) =
+ res_stream.message().await.map_err(|e| anyhow!("failed to receive message: {:#}", e))?
+ {
+ let clusters_count = match calculate_clusters_count(available_bytes) {
+ Ok(c) => c,
+ Err(e) => {
+ error!("failed to calculate cluster size to be reserved: {:#}", e);
+ continue;
+ }
+ };
+
+ if let Err(e) = set_reserved_clusters(clusters_count) {
+ error!("failed to set storage balloon size: {}", e);
+ }
+ }
+
+ Ok(())
+}
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/AndroidTest.xml b/guest/trusty/test_vm/AndroidTest.xml
index 925b43c..43d9ef8 100644
--- a/guest/trusty/test_vm/AndroidTest.xml
+++ b/guest/trusty/test_vm/AndroidTest.xml
@@ -15,10 +15,10 @@
limitations under the License.
-->
<configuration description="Runs {MODULE}">
- <!-- object type="module_controller" class="com.android.tradefed.testtype.suite.module.CommandSuccessModuleController" -->
+ <object type="module_controller" class="com.android.tradefed.testtype.suite.module.CommandSuccessModuleController">
<!--Skip the test when trusty VM is not enabled. -->
- <!--option name="run-command" value="getprop trusty.test_vm.nonsecure_vm_ready | grep 1" /-->
- <!--/object-->
+ <option name="run-command" value="getprop trusty.security_vm.enabled | grep 1" />
+ </object>
<target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer" />
<!-- Target Preparers - Run Shell Commands -->
<target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
@@ -38,13 +38,19 @@
<option name="run-command" value="start storageproxyd_test_vm" />
<option name="teardown-command" value="stop storageproxyd_test_vm" />
<option name="teardown-command" value="killall storageproxyd_test_vm || true" />
+ <!--option name="teardown-command" value="rm -rf /data/local/trusty_test_vm"/-->
</target_preparer>
<test class="com.android.tradefed.testtype.binary.ExecutableTargetTest" >
<option name="parse-gtest" value="true" />
<option name="abort-if-device-lost" value="true"/>
<option name="abort-if-root-lost" value="true" />
<option name="per-binary-timeout" value="10m" />
+ <option name="test-command-line" key="com.android.trusty.rust.authmgr_be_lib.test" value="/data/local/tmp/trusty_test_vm/trusty-ut-ctrl.sh com.android.trusty.rust.authmgr_be_lib.test"/>
<option name="test-command-line" key="com.android.trusty.rust.hwcryptokey_test.test" value="/data/local/tmp/trusty_test_vm/trusty-ut-ctrl.sh com.android.trusty.rust.hwcryptokey_test.test"/>
<option name="test-command-line" key="com.android.trusty.rust.storage_unittest_aidl.test" value="/data/local/tmp/trusty_test_vm/trusty-ut-ctrl.sh com.android.trusty.rust.storage_unittest_aidl.test"/>
</test>
+ <metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector">
+ <option name="directory-keys" value="/data/local/tmp/trusty_test_vm/logs" />
+ <option name="clean-up" value="false"/>
+ </metrics_collector>
</configuration>
diff --git a/guest/trusty/test_vm/README.md b/guest/trusty/test_vm/README.md
index 71368b5..81382c5 100644
--- a/guest/trusty/test_vm/README.md
+++ b/guest/trusty/test_vm/README.md
@@ -11,3 +11,16 @@
The Trusty test_vm also includes the VINTF test which allows to check the vendor
support of the Trusted HALs (version and API hash), against the expected
compatibility matrix for a given Android Dessert Release.
+
+### instructions
+
+`atest -s <device-serial-port> VtsSeeHalTargetTest
+
+### test_vm console
+
+The test_vm console can be retrieved from `/data/local/tmp/trusty_test_vm/logs/console.log`.
+The script `trusty-vm-laucher.sh` uses `/apex/com.android.virt/bin/vm run` with the option
+`--console` to store the console log.
+
+This log can be consulted when the tests are running and will be uploaded
+by the Tradefed FilePullerLogCollector runner (see AndroidTest.xml).
diff --git a/guest/trusty/test_vm/TEST_MAPPING b/guest/trusty/test_vm/TEST_MAPPING
deleted file mode 100644
index aa9d65d..0000000
--- a/guest/trusty/test_vm/TEST_MAPPING
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "trusty_test_vm_presubmit": [
- ],
- "trusty_test_vm_postsubmit": [
- {
- "name": "TrustyTestVM_UnitTests"
- }
- ]
-}
diff --git a/guest/trusty/test_vm/trusty-vm-launcher.sh b/guest/trusty/test_vm/trusty-vm-launcher.sh
index cb8661f..079a66a 100755
--- a/guest/trusty/test_vm/trusty-vm-launcher.sh
+++ b/guest/trusty/test_vm/trusty-vm-launcher.sh
@@ -14,4 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-/apex/com.android.virt/bin/vm run /data/local/tmp/trusty_test_vm/trusty-test_vm-config.json
+mkdir -p /data/local/tmp/trusty_test_vm/logs || true
+/apex/com.android.virt/bin/vm run \
+ --console /data/local/tmp/trusty_test_vm/logs/console.log \
+ /data/local/tmp/trusty_test_vm/trusty-test_vm-config.json
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/AndroidTest.xml b/guest/trusty/test_vm_os/AndroidTest.xml
index be5c467..5adafff 100644
--- a/guest/trusty/test_vm_os/AndroidTest.xml
+++ b/guest/trusty/test_vm_os/AndroidTest.xml
@@ -15,10 +15,10 @@
limitations under the License.
-->
<configuration description="Runs {MODULE}">
- <!-- object type="module_controller" class="com.android.tradefed.testtype.suite.module.CommandSuccessModuleController" -->
+ <object type="module_controller" class="com.android.tradefed.testtype.suite.module.CommandSuccessModuleController">
<!--Skip the test when trusty VM is not enabled. -->
- <!--option name="run-command" value="getprop trusty.test_vm.nonsecure_vm_ready | grep 1" /-->
- <!--/object-->
+ <option name="run-command" value="getprop trusty.security_vm.enabled | grep 1" />
+ </object>
<target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer" />
<!-- Target Preparers - Run Shell Commands -->
<target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
@@ -38,6 +38,7 @@
<option name="run-command" value="start storageproxyd_test_vm_os" />
<option name="teardown-command" value="stop storageproxyd_test_vm_os" />
<option name="teardown-command" value="killall storageproxyd_test_vm_os || true" />
+ <!--option name="teardown-command" value="rm -rf /data/local/trusty_test_vm_os"/-->
</target_preparer>
<test class="com.android.tradefed.testtype.binary.ExecutableTargetTest" >
<option name="parse-gtest" value="true" />
@@ -79,4 +80,10 @@
<option name="test-command-line" key="com.android.trusty.rust.binder_rpc_test.test" value="/data/local/tmp/trusty_test_vm_os/trusty-ut-ctrl.sh com.android.trusty.rust.binder_rpc_test.test"/>
<option name="test-command-line" key="com.android.trusty.binder.test" value="/data/local/tmp/trusty_test_vm_os/trusty-ut-ctrl.sh com.android.trusty.binder.test"/>
</test>
+ <metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector">
+ <option name="directory-keys" value="/data/local/tmp/trusty_test_vm_os/logs" />
+ <option name="collect-on-run-ended-only" value="true" />
+ <option name="clean-up" value="true"/>
+ <option name="collect-on-run-ended-only" value="false" />
+ </metrics_collector>
</configuration>
diff --git a/guest/trusty/test_vm_os/README.md b/guest/trusty/test_vm_os/README.md
index 4d65d9f..b37a4da 100644
--- a/guest/trusty/test_vm_os/README.md
+++ b/guest/trusty/test_vm_os/README.md
@@ -5,3 +5,6 @@
- Trusty kernel OS test
- Trusty/Binder IPC tests
- Trusty user-space tests for service TAs (DT tree for example)
+
+
+see instructions at [test_vm/README.md](../test_vm/README.md)
diff --git a/guest/trusty/test_vm_os/TEST_MAPPING b/guest/trusty/test_vm_os/TEST_MAPPING
deleted file mode 100644
index 1506720..0000000
--- a/guest/trusty/test_vm_os/TEST_MAPPING
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "trusty_test_vm_presubmit": [
- ],
- "trusty_test_vm_postsubmit": [
- {
- "name": "TrustyVMOS_UnitTests"
- }
- ]
-}
diff --git a/guest/trusty/test_vm_os/trusty-vm-launcher.sh b/guest/trusty/test_vm_os/trusty-vm-launcher.sh
index 497b188..bc256ed 100755
--- a/guest/trusty/test_vm_os/trusty-vm-launcher.sh
+++ b/guest/trusty/test_vm_os/trusty-vm-launcher.sh
@@ -14,4 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-/apex/com.android.virt/bin/vm run /data/local/tmp/trusty_test_vm_os/trusty-test_vm-config.json
+mkdir -p /data/local/tmp/trusty_test_vm_os/logs || true
+/apex/com.android.virt/bin/vm run \
+ --console /data/local/tmp/trusty_test_vm_os/logs/console.log \
+ /data/local/tmp/trusty_test_vm_os/trusty-test_vm-config.json
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/debian_service/proto/DebianService.proto b/libs/debian_service/proto/DebianService.proto
index 43955fa..e52b28a 100644
--- a/libs/debian_service/proto/DebianService.proto
+++ b/libs/debian_service/proto/DebianService.proto
@@ -25,6 +25,7 @@
rpc ReportVmActivePorts (ReportVmActivePortsRequest) returns (ReportVmActivePortsResponse) {}
rpc OpenForwardingRequestQueue (QueueOpeningRequest) returns (stream ForwardingRequestItem) {}
rpc OpenShutdownRequestQueue (ShutdownQueueOpeningRequest) returns (stream ShutdownRequestItem) {}
+ rpc OpenStorageBalloonRequestQueue (StorageBalloonQueueOpeningRequest) returns (stream StorageBalloonRequestItem) {}
}
message QueueOpeningRequest {
@@ -52,3 +53,9 @@
message ShutdownQueueOpeningRequest {}
message ShutdownRequestItem {}
+
+message StorageBalloonQueueOpeningRequest {}
+
+message StorageBalloonRequestItem {
+ uint64 available_bytes = 1;
+}
diff --git a/libs/dice/TEST_MAPPING b/libs/dice/TEST_MAPPING
index a43d7a2..d2d89e4 100644
--- a/libs/dice/TEST_MAPPING
+++ b/libs/dice/TEST_MAPPING
@@ -12,6 +12,9 @@
"name": "libdiced_open_dice.integration_test"
},
{
+ "name": "libdiced_open_dice_multialg.integration_test"
+ },
+ {
"name": "libdiced_open_dice_nostd.integration_test"
},
{
diff --git a/libs/dice/open_dice/Android.bp b/libs/dice/open_dice/Android.bp
index 986f496..9e4544d 100644
--- a/libs/dice/open_dice/Android.bp
+++ b/libs/dice/open_dice/Android.bp
@@ -61,6 +61,35 @@
"//apex_available:platform",
"com.android.virt",
],
+ min_sdk_version: "35",
+}
+
+rust_library {
+ name: "libdiced_open_dice_multialg",
+ defaults: ["libdiced_open_dice_defaults"],
+ host_supported: true,
+ vendor_available: true,
+ rustlibs: [
+ "libcoset",
+ "libopen_dice_android_bindgen_multialg",
+ "libopen_dice_cbor_bindgen_multialg",
+ "libzeroize",
+ ],
+ features: [
+ "std",
+ "multialg",
+ ],
+ shared_libs: [
+ "libcrypto",
+ ],
+ visibility: [
+ "//system/software_defined_vehicle:__subpackages__",
+ ],
+ apex_available: [
+ "//apex_available:platform",
+ "com.android.virt",
+ ],
+ min_sdk_version: "35",
}
rust_defaults {
@@ -80,6 +109,18 @@
}
rust_test {
+ name: "libdiced_open_dice_multialg.integration_test",
+ defaults: ["libdiced_open_dice_test_defaults"],
+ rustlibs: [
+ "libdiced_open_dice_multialg",
+ "libcoset",
+ ],
+ features: [
+ "multialg",
+ ],
+}
+
+rust_test {
name: "libdiced_open_dice_nostd.integration_test",
defaults: ["libdiced_open_dice_test_defaults"],
rustlibs: [
@@ -171,6 +212,22 @@
],
whole_static_libs: ["libopen_dice_cbor"],
shared_libs: ["libcrypto"],
+ min_sdk_version: "35",
+}
+
+rust_bindgen {
+ name: "libopen_dice_cbor_bindgen_multialg",
+ defaults: [
+ "libopen_dice.rust_defaults",
+ "libopen_dice_cbor_bindgen.rust_defaults",
+ ],
+ bindgen_flags: [
+ "--rustified-enum DiceKeyAlgorithm",
+ "--allowlist-type=DiceContext",
+ ],
+ whole_static_libs: ["libopen_dice_cbor_multialg"],
+ shared_libs: ["libcrypto"],
+ min_sdk_version: "35",
}
rust_bindgen {
@@ -228,6 +285,20 @@
"libopen_dice_cbor_bindgen",
],
whole_static_libs: ["libopen_dice_android"],
+ min_sdk_version: "35",
+}
+
+rust_bindgen {
+ name: "libopen_dice_android_bindgen_multialg",
+ defaults: [
+ "libopen_dice.rust_defaults",
+ "libopen_dice_android_bindgen.rust_defaults",
+ ],
+ rustlibs: [
+ "libopen_dice_cbor_bindgen_multialg",
+ ],
+ whole_static_libs: ["libopen_dice_android_multialg"],
+ min_sdk_version: "35",
}
rust_bindgen {
diff --git a/libs/dice/open_dice/src/error.rs b/libs/dice/open_dice/src/error.rs
index c9eb5cc..87d463e 100644
--- a/libs/dice/open_dice/src/error.rs
+++ b/libs/dice/open_dice/src/error.rs
@@ -33,6 +33,8 @@
UnsupportedKeyAlgorithm(coset::iana::Algorithm),
/// A failed fallible allocation. Used in no_std environments.
MemoryAllocationError,
+ /// DICE chain not found in artifacts.
+ DiceChainNotFound,
}
/// This makes `DiceError` accepted by anyhow.
@@ -51,6 +53,7 @@
write!(f, "Unsupported key algorithm: {algorithm:?}")
}
Self::MemoryAllocationError => write!(f, "Memory allocation failed"),
+ Self::DiceChainNotFound => write!(f, "DICE chain not found in artifacts"),
}
}
}
diff --git a/libs/dice/open_dice/src/lib.rs b/libs/dice/open_dice/src/lib.rs
index 33fb65c..9268b03 100644
--- a/libs/dice/open_dice/src/lib.rs
+++ b/libs/dice/open_dice/src/lib.rs
@@ -43,11 +43,19 @@
};
pub use error::{DiceError, Result};
pub use ops::{
- derive_cdi_leaf_priv, generate_certificate, hash, kdf, keypair_from_seed, sign,
- sign_cose_sign1, sign_cose_sign1_with_cdi_leaf_priv, verify,
+ derive_cdi_leaf_priv, generate_certificate, hash, kdf, keypair_from_seed, sign, verify,
+};
+#[cfg(feature = "multialg")]
+pub use ops::{
+ derive_cdi_leaf_priv_multialg, keypair_from_seed_multialg, sign_cose_sign1_multialg,
+ sign_cose_sign1_with_cdi_leaf_priv_multialg, verify_multialg,
};
pub use retry::{
retry_bcc_format_config_descriptor, retry_bcc_main_flow, retry_dice_main_flow,
retry_generate_certificate, retry_sign_cose_sign1, retry_sign_cose_sign1_with_cdi_leaf_priv,
OwnedDiceArtifacts,
};
+#[cfg(feature = "multialg")]
+pub use retry::{
+ retry_sign_cose_sign1_multialg, retry_sign_cose_sign1_with_cdi_leaf_priv_multialg,
+};
diff --git a/libs/dice/open_dice/src/ops.rs b/libs/dice/open_dice/src/ops.rs
index 2014118..b22b113 100644
--- a/libs/dice/open_dice/src/ops.rs
+++ b/libs/dice/open_dice/src/ops.rs
@@ -21,11 +21,17 @@
PRIVATE_KEY_SEED_SIZE, PRIVATE_KEY_SIZE, VM_KEY_ALGORITHM,
};
use crate::error::{check_result, DiceError, Result};
+#[cfg(feature = "multialg")]
+use crate::KeyAlgorithm;
use alloc::{vec, vec::Vec};
+#[cfg(feature = "multialg")]
+use open_dice_cbor_bindgen::DiceContext_;
use open_dice_cbor_bindgen::{
DiceCoseSignAndEncodeSign1, DiceGenerateCertificate, DiceHash, DiceKdf, DiceKeypairFromSeed,
DicePrincipal, DiceSign, DiceVerify,
};
+#[cfg(feature = "multialg")]
+use std::ffi::c_void;
use std::ptr;
/// Hashes the provided input using DICE's hash function `DiceHash`.
@@ -100,6 +106,44 @@
Ok((public_key, private_key))
}
+/// Deterministically generates a public and private key pair from `seed` and `key_algorithm`.
+/// Since this is deterministic, `seed` is as sensitive as a private key and can
+/// be used directly as the private key.
+#[cfg(feature = "multialg")]
+pub fn keypair_from_seed_multialg(
+ seed: &[u8; PRIVATE_KEY_SEED_SIZE],
+ key_algorithm: KeyAlgorithm,
+) -> Result<(Vec<u8>, PrivateKey)> {
+ let mut public_key = vec![0u8; key_algorithm.public_key_size()];
+ let mut private_key = PrivateKey::default();
+ // This function is used with an open-dice config that uses the same algorithms for the
+ // subject and authority. Therefore, the principal is irrelevant in this context as this
+ // function only derives the key pair cryptographically without caring about which
+ // principal it is for. Hence, we arbitrarily set it to `DicePrincipal::kDicePrincipalSubject`.
+ let principal = DicePrincipal::kDicePrincipalSubject;
+ let context = DiceContext_ {
+ authority_algorithm: key_algorithm.into(),
+ subject_algorithm: key_algorithm.into(),
+ };
+ check_result(
+ // SAFETY: The function writes to the `public_key` and `private_key` within the given
+ // bounds, and only reads the `seed`.
+ // The first argument is a pointer to a valid |DiceContext_| object for multi-alg
+ // open-dice.
+ unsafe {
+ DiceKeypairFromSeed(
+ &context as *const DiceContext_ as *mut c_void,
+ principal,
+ seed.as_ptr(),
+ public_key.as_mut_ptr(),
+ private_key.as_mut_ptr(),
+ )
+ },
+ public_key.len(),
+ )?;
+ Ok((public_key, private_key))
+}
+
/// Derives the CDI_Leaf_Priv from the provided `dice_artifacts`.
///
/// The corresponding public key is included in the leaf certificate of the DICE chain
@@ -114,6 +158,17 @@
Ok(private_key)
}
+/// Multialg variant of `derive_cdi_leaf_priv`.
+#[cfg(feature = "multialg")]
+pub fn derive_cdi_leaf_priv_multialg(
+ dice_artifacts: &dyn DiceArtifacts,
+ key_algorithm: KeyAlgorithm,
+) -> Result<PrivateKey> {
+ let cdi_priv_key_seed = derive_cdi_private_key_seed(dice_artifacts.cdi_attest())?;
+ let (_, private_key) = keypair_from_seed_multialg(cdi_priv_key_seed.as_array(), key_algorithm)?;
+ Ok(private_key)
+}
+
/// Signs the `message` with the given `private_key` using `DiceSign`.
pub fn sign(message: &[u8], private_key: &[u8; PRIVATE_KEY_SIZE]) -> Result<Vec<u8>> {
let mut signature = vec![0u8; VM_KEY_ALGORITHM.signature_size()];
@@ -173,6 +228,45 @@
Ok(encoded_signature_actual_size)
}
+/// Multialg variant of `sign_cose_sign1`.
+#[cfg(feature = "multialg")]
+pub fn sign_cose_sign1_multialg(
+ message: &[u8],
+ aad: &[u8],
+ private_key: &[u8; PRIVATE_KEY_SIZE],
+ encoded_signature: &mut [u8],
+ key_algorithm: KeyAlgorithm,
+) -> Result<usize> {
+ let mut encoded_signature_actual_size = 0;
+ let context = DiceContext_ {
+ authority_algorithm: key_algorithm.into(),
+ subject_algorithm: key_algorithm.into(),
+ };
+ check_result(
+ // SAFETY: The function writes to `encoded_signature` and `encoded_signature_actual_size`
+ // within the given bounds. It only reads `message`, `aad`, and `private_key` within their
+ // given bounds.
+ //
+ // The first argument is a pointer to a valid |DiceContext_| object for multi-alg
+ // open-dice.
+ unsafe {
+ DiceCoseSignAndEncodeSign1(
+ &context as *const DiceContext_ as *mut c_void,
+ message.as_ptr(),
+ message.len(),
+ aad.as_ptr(),
+ aad.len(),
+ private_key.as_ptr(),
+ encoded_signature.len(),
+ encoded_signature.as_mut_ptr(),
+ &mut encoded_signature_actual_size,
+ )
+ },
+ encoded_signature_actual_size,
+ )?;
+ Ok(encoded_signature_actual_size)
+}
+
/// Signs the `message` with a private key derived from the given `dice_artifacts`
/// CDI Attest. On success, places a `CoseSign1` encoded object in `encoded_signature`.
/// Uses `DiceCoseSignAndEncodeSign1`.
@@ -188,6 +282,19 @@
sign_cose_sign1(message, aad, private_key.as_array(), encoded_signature)
}
+/// Multialg variant of `sign_cose_sign1_with_cdi_leaf_priv`.
+#[cfg(feature = "multialg")]
+pub fn sign_cose_sign1_with_cdi_leaf_priv_multialg(
+ message: &[u8],
+ aad: &[u8],
+ dice_artifacts: &dyn DiceArtifacts,
+ encoded_signature: &mut [u8],
+ key_algorithm: KeyAlgorithm,
+) -> Result<usize> {
+ let private_key = derive_cdi_leaf_priv_multialg(dice_artifacts, key_algorithm)?;
+ sign_cose_sign1_multialg(message, aad, private_key.as_array(), encoded_signature, key_algorithm)
+}
+
/// Verifies the `signature` of the `message` with the given `public_key` using `DiceVerify`.
pub fn verify(message: &[u8], signature: &[u8], public_key: &[u8]) -> Result<()> {
if signature.len() != VM_KEY_ALGORITHM.signature_size()
@@ -212,6 +319,40 @@
)
}
+/// Multialg variant of `verify`.
+#[cfg(feature = "multialg")]
+pub fn verify_multialg(
+ message: &[u8],
+ signature: &[u8],
+ public_key: &[u8],
+ key_algorithm: KeyAlgorithm,
+) -> Result<()> {
+ if signature.len() != key_algorithm.signature_size()
+ || public_key.len() != key_algorithm.public_key_size()
+ {
+ return Err(DiceError::InvalidInput);
+ }
+ let context = DiceContext_ {
+ authority_algorithm: key_algorithm.into(),
+ subject_algorithm: key_algorithm.into(),
+ };
+ check_result(
+ // SAFETY: only reads the messages, signature and public key as constant values.
+ // The first argument is a pointer to a valid |DiceContext_| object for multi-alg
+ // open-dice.
+ unsafe {
+ DiceVerify(
+ &context as *const DiceContext_ as *mut c_void,
+ message.as_ptr(),
+ message.len(),
+ signature.as_ptr(),
+ public_key.as_ptr(),
+ )
+ },
+ 0,
+ )
+}
+
/// Generates an X.509 certificate from the given `subject_private_key_seed` and
/// `input_values`, and signed by `authority_private_key_seed`.
/// The subject private key seed is supplied here so the implementation can choose
diff --git a/libs/dice/open_dice/src/retry.rs b/libs/dice/open_dice/src/retry.rs
index cf36bc0..2b7b740 100644
--- a/libs/dice/open_dice/src/retry.rs
+++ b/libs/dice/open_dice/src/retry.rs
@@ -17,13 +17,18 @@
//! of this buffer may fail and callers will see Error::MemoryAllocationError.
//! When running with std, allocation may fail.
-use crate::bcc::{bcc_format_config_descriptor, bcc_main_flow, DiceConfigValues};
+use crate::bcc::{bcc_format_config_descriptor, bcc_main_flow, BccHandover, DiceConfigValues};
use crate::dice::{
dice_main_flow, Cdi, CdiValues, DiceArtifacts, InputValues, CDI_SIZE, PRIVATE_KEY_SEED_SIZE,
PRIVATE_KEY_SIZE,
};
use crate::error::{DiceError, Result};
use crate::ops::{generate_certificate, sign_cose_sign1, sign_cose_sign1_with_cdi_leaf_priv};
+#[cfg(feature = "multialg")]
+use crate::{
+ ops::{sign_cose_sign1_multialg, sign_cose_sign1_with_cdi_leaf_priv_multialg},
+ KeyAlgorithm,
+};
use alloc::vec::Vec;
#[cfg(feature = "serde_derive")]
use serde_derive::{Deserialize, Serialize};
@@ -55,6 +60,20 @@
}
}
+impl TryFrom<BccHandover<'_>> for OwnedDiceArtifacts {
+ type Error = DiceError;
+
+ fn try_from(artifacts: BccHandover<'_>) -> Result<Self> {
+ let cdi_attest = artifacts.cdi_attest().to_vec().try_into().unwrap();
+ let cdi_seal = artifacts.cdi_seal().to_vec().try_into().unwrap();
+ let bcc = artifacts
+ .bcc()
+ .map(|bcc_slice| bcc_slice.to_vec())
+ .ok_or(DiceError::DiceChainNotFound)?;
+ Ok(OwnedDiceArtifacts { cdi_values: CdiValues { cdi_attest, cdi_seal }, bcc })
+ }
+}
+
/// Retries the given function with bigger measured buffer size.
fn retry_with_measured_buffer<F>(mut f: F) -> Result<Vec<u8>>
where
@@ -158,6 +177,19 @@
})
}
+/// Multialg variant of `retry_sign_cose_sign1`.
+#[cfg(feature = "multialg")]
+pub fn retry_sign_cose_sign1_multialg(
+ message: &[u8],
+ aad: &[u8],
+ private_key: &[u8; PRIVATE_KEY_SIZE],
+ key_algorithm: KeyAlgorithm,
+) -> Result<Vec<u8>> {
+ retry_with_measured_buffer(|encoded_signature| {
+ sign_cose_sign1_multialg(message, aad, private_key, encoded_signature, key_algorithm)
+ })
+}
+
/// Signs a message with the given the private key derived from the
/// CDI Attest of the given `dice_artifacts` and returns the signature
/// as an encoded CoseSign1 object.
@@ -170,3 +202,22 @@
sign_cose_sign1_with_cdi_leaf_priv(message, aad, dice_artifacts, encoded_signature)
})
}
+
+/// Multialg variant of `retry_sign_cose_sign1_with_cdi_leaf_priv`.
+#[cfg(feature = "multialg")]
+pub fn retry_sign_cose_sign1_with_cdi_leaf_priv_multialg(
+ message: &[u8],
+ aad: &[u8],
+ dice_artifacts: &dyn DiceArtifacts,
+ key_algorithm: KeyAlgorithm,
+) -> Result<Vec<u8>> {
+ retry_with_measured_buffer(|encoded_signature| {
+ sign_cose_sign1_with_cdi_leaf_priv_multialg(
+ message,
+ aad,
+ dice_artifacts,
+ encoded_signature,
+ key_algorithm,
+ )
+ })
+}
diff --git a/libs/dice/open_dice/tests/api_test.rs b/libs/dice/open_dice/tests/api_test.rs
index b0c2ca7..0f8af10 100644
--- a/libs/dice/open_dice/tests/api_test.rs
+++ b/libs/dice/open_dice/tests/api_test.rs
@@ -21,6 +21,11 @@
retry_sign_cose_sign1, retry_sign_cose_sign1_with_cdi_leaf_priv, sign, verify,
DiceArtifacts, PrivateKey, CDI_SIZE, HASH_SIZE, ID_SIZE, PRIVATE_KEY_SEED_SIZE,
};
+ #[cfg(feature = "multialg")]
+ use diced_open_dice::{
+ keypair_from_seed_multialg, retry_sign_cose_sign1_multialg,
+ retry_sign_cose_sign1_with_cdi_leaf_priv_multialg, verify_multialg, KeyAlgorithm,
+ };
use coset::{CborSerializable, CoseSign1};
@@ -93,7 +98,21 @@
0xfc, 0x23, 0xc9, 0x21, 0x5c, 0x48, 0x21, 0x47, 0xee, 0x5b, 0xfa, 0xaf, 0x88, 0x9a, 0x52,
0xf1, 0x61, 0x06, 0x37,
];
-
+ #[cfg(feature = "multialg")]
+ const EXPECTED_EC_P256_PUB_KEY: &[u8] = &[
+ 0xa7, 0x93, 0x70, 0x16, 0xff, 0xe8, 0x3c, 0x23, 0x5f, 0x6b, 0xf9, 0x38, 0x7e, 0x9c, 0xe5,
+ 0x21, 0xb5, 0x8a, 0x9b, 0x68, 0x5a, 0x2f, 0x62, 0xf4, 0x15, 0x94, 0x1c, 0x61, 0xb3, 0xbb,
+ 0xe1, 0x26, 0x61, 0x47, 0x97, 0xbf, 0x3a, 0x1f, 0x6b, 0x87, 0x86, 0x47, 0x5e, 0xc3, 0xa6,
+ 0x8b, 0x95, 0x89, 0x9e, 0x29, 0xd5, 0x55, 0x2a, 0xdd, 0x2a, 0x3f, 0xe5, 0xf0, 0x7a, 0xd6,
+ 0xc4, 0x7b, 0x64, 0xe0,
+ ];
+ #[cfg(feature = "multialg")]
+ const EXPECTED_EC_P256_PRIV_KEY: &[u8] = &[
+ 0x62, 0x32, 0x1b, 0xb, 0x5c, 0xac, 0x8f, 0x20, 0x61, 0xb7, 0xa3, 0xbb, 0x46, 0x2b, 0x4e,
+ 0xb3, 0x3f, 0xa7, 0xf6, 0x9b, 0x2f, 0x5b, 0x80, 0xa8, 0x55, 0x5e, 0x80, 0x26, 0xbb, 0x72,
+ 0xbe, 0xe7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ ];
const EXPECTED_SIGNATURE: &[u8] = &[
0x44, 0xae, 0xcc, 0xe2, 0xb9, 0x96, 0x18, 0x39, 0x0e, 0x61, 0x0f, 0x53, 0x07, 0xbf, 0xf2,
0x32, 0x3d, 0x44, 0xd4, 0xf2, 0x07, 0x23, 0x30, 0x85, 0x32, 0x18, 0xd2, 0x69, 0xb8, 0x29,
@@ -140,6 +159,41 @@
assert!(verify_result.is_err());
}
+ #[cfg(feature = "multialg")]
+ #[test]
+ fn sign_cose_sign1_verify_multialg() {
+ let (pub_key, priv_key) = get_test_key_pair_ec_p256();
+
+ let signature_res = retry_sign_cose_sign1_multialg(
+ b"MyMessage",
+ b"MyAad",
+ priv_key.as_array(),
+ KeyAlgorithm::EcdsaP256,
+ );
+ assert!(signature_res.is_ok());
+ let signature = signature_res.unwrap();
+ let cose_sign1_res = CoseSign1::from_slice(&signature);
+ assert!(cose_sign1_res.is_ok());
+ let mut cose_sign1 = cose_sign1_res.unwrap();
+
+ let mut verify_result = cose_sign1.verify_signature(b"MyAad", |sign, data| {
+ verify_multialg(data, sign, &pub_key, KeyAlgorithm::EcdsaP256)
+ });
+ assert!(verify_result.is_ok());
+
+ verify_result = cose_sign1.verify_signature(b"BadAad", |sign, data| {
+ verify_multialg(data, sign, &pub_key, KeyAlgorithm::EcdsaP256)
+ });
+ assert!(verify_result.is_err());
+
+ // if we modify the signature, the payload should no longer verify
+ cose_sign1.signature.push(0xAA);
+ verify_result = cose_sign1.verify_signature(b"MyAad", |sign, data| {
+ verify_multialg(data, sign, &pub_key, KeyAlgorithm::EcdsaP256)
+ });
+ assert!(verify_result.is_err());
+ }
+
struct TestArtifactsForSigning {}
impl DiceArtifacts for TestArtifactsForSigning {
@@ -182,6 +236,41 @@
assert!(verify_result.is_err());
}
+ #[cfg(feature = "multialg")]
+ #[test]
+ fn sign_cose_sign1_with_cdi_leaf_priv_verify_multialg() {
+ let dice = TestArtifactsForSigning {};
+
+ let signature_res = retry_sign_cose_sign1_with_cdi_leaf_priv_multialg(
+ b"MyMessage",
+ b"MyAad",
+ &dice,
+ KeyAlgorithm::EcdsaP256,
+ );
+ assert!(signature_res.is_ok());
+ let signature = signature_res.unwrap();
+ let cose_sign1_res = CoseSign1::from_slice(&signature);
+ assert!(cose_sign1_res.is_ok());
+ let mut cose_sign1 = cose_sign1_res.unwrap();
+
+ let mut verify_result = cose_sign1.verify_signature(b"MyAad", |sign, data| {
+ verify_multialg(data, sign, EXPECTED_EC_P256_PUB_KEY, KeyAlgorithm::EcdsaP256)
+ });
+ assert!(verify_result.is_ok());
+
+ verify_result = cose_sign1.verify_signature(b"BadAad", |sign, data| {
+ verify_multialg(data, sign, EXPECTED_EC_P256_PUB_KEY, KeyAlgorithm::EcdsaP256)
+ });
+ assert!(verify_result.is_err());
+
+ // if we modify the signature, the payload should no longer verify
+ cose_sign1.signature.push(0xAA);
+ verify_result = cose_sign1.verify_signature(b"MyAad", |sign, data| {
+ verify_multialg(data, sign, EXPECTED_EC_P256_PUB_KEY, KeyAlgorithm::EcdsaP256)
+ });
+ assert!(verify_result.is_err());
+ }
+
fn get_test_key_pair() -> (Vec<u8>, PrivateKey) {
let seed = hash(b"MySeedString").unwrap();
assert_eq!(seed, EXPECTED_SEED);
@@ -196,4 +285,23 @@
(pub_key, priv_key)
}
+
+ #[cfg(feature = "multialg")]
+ fn get_test_key_pair_ec_p256() -> (Vec<u8>, PrivateKey) {
+ let seed = hash(b"MySeedString").unwrap();
+ assert_eq!(seed, EXPECTED_SEED);
+ let cdi_attest = &seed[..CDI_SIZE];
+ assert_eq!(cdi_attest, EXPECTED_CDI_ATTEST);
+ let cdi_private_key_seed =
+ derive_cdi_private_key_seed(cdi_attest.try_into().unwrap()).unwrap();
+ assert_eq!(cdi_private_key_seed.as_array(), EXPECTED_CDI_PRIVATE_KEY_SEED);
+ let (pub_key, priv_key) =
+ keypair_from_seed_multialg(cdi_private_key_seed.as_array(), KeyAlgorithm::EcdsaP256)
+ .unwrap();
+
+ assert_eq!(&pub_key, EXPECTED_EC_P256_PUB_KEY);
+ assert_eq!(priv_key.as_array(), EXPECTED_EC_P256_PRIV_KEY);
+
+ (pub_key, priv_key)
+ }
}
diff --git a/libs/dice/sample_inputs/Android.bp b/libs/dice/sample_inputs/Android.bp
index c1c4566..4010741 100644
--- a/libs/dice/sample_inputs/Android.bp
+++ b/libs/dice/sample_inputs/Android.bp
@@ -80,3 +80,9 @@
],
static_libs: ["libopen_dice_clear_memory"],
}
+
+dirgroup {
+ name: "trusty_dirgroup_packages_modules_virtualization_libs_dice_sample_inputs",
+ visibility: ["//trusty/vendor/google/aosp/scripts"],
+ dirs: ["."],
+}
diff --git a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
index ad63206..4f58cd6 100644
--- a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
+++ b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
@@ -813,6 +813,10 @@
*/
@GuardedBy("mLock")
private void dropVm() {
+ if (mInputEventExecutor != null) {
+ mInputEventExecutor.shutdownNow();
+ mInputEventExecutor = null;
+ }
if (mMemoryManagementCallbacks != null) {
mContext.unregisterComponentCallbacks(mMemoryManagementCallbacks);
}
@@ -1825,9 +1829,6 @@
try {
mVirtualMachine.stop();
dropVm();
- if (mInputEventExecutor != null) {
- mInputEventExecutor.shutdownNow();
- }
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
} catch (ServiceSpecificException e) {
diff --git a/libs/libavf/Android.bp b/libs/libavf/Android.bp
index aceb927..4469af5 100644
--- a/libs/libavf/Android.bp
+++ b/libs/libavf/Android.bp
@@ -40,30 +40,8 @@
defaults: ["libavf.default"],
}
-soong_config_module_type {
- name: "virt_cc_defaults",
- module_type: "cc_defaults",
- config_namespace: "ANDROID",
- bool_variables: [
- "avf_enabled",
- ],
- properties: [
- "apex_available",
- ],
-}
-
-virt_cc_defaults {
- name: "libavf_apex_available_defaults",
- soong_config_variables: {
- avf_enabled: {
- apex_available: ["com.android.virt"],
- },
- },
-}
-
cc_library {
name: "libavf",
- defaults: ["libavf_apex_available_defaults"],
llndk: {
symbol_file: "libavf.map.txt",
moved_to_apex: true,
@@ -79,4 +57,5 @@
stubs: {
symbol_file: "libavf.map.txt",
},
+ apex_available: ["com.android.virt"],
}
diff --git a/libs/libavf/include/android/virtualization.h b/libs/libavf/include/android/virtualization.h
index 4bfe47a..e907ac4 100644
--- a/libs/libavf/include/android/virtualization.h
+++ b/libs/libavf/include/android/virtualization.h
@@ -78,6 +78,9 @@
* The `instanceId` is expected to be re-used for the VM instance with an associated state (secret,
* encrypted storage) - i.e., rebooting the VM must not change the instanceId.
*
+ * `instanceId` MUST start with 0xFFFFFFFF if and only if this library is being
+ * called from code in a vendor or odm partition,
+ *
* \param config a virtual machine config object.
* \param instanceId a pointer to a 64-byte buffer for the instance ID.
* \param instanceIdSize the number of bytes in `instanceId`.
diff --git a/libs/libhypervisor_backends/src/hypervisor.rs b/libs/libhypervisor_backends/src/hypervisor.rs
index aa65133..7c274f5 100644
--- a/libs/libhypervisor_backends/src/hypervisor.rs
+++ b/libs/libhypervisor_backends/src/hypervisor.rs
@@ -152,3 +152,8 @@
pub fn get_device_assigner() -> Option<&'static dyn DeviceAssigningHypervisor> {
get_hypervisor().as_device_assigner()
}
+
+/// Gets the unique hypervisor granule size, if any.
+pub fn get_granule_size() -> Option<usize> {
+ get_hypervisor().get_granule_size()
+}
diff --git a/libs/libhypervisor_backends/src/hypervisor/common.rs b/libs/libhypervisor_backends/src/hypervisor/common.rs
index bfe638f..f229e14 100644
--- a/libs/libhypervisor_backends/src/hypervisor/common.rs
+++ b/libs/libhypervisor_backends/src/hypervisor/common.rs
@@ -32,6 +32,13 @@
fn as_device_assigner(&self) -> Option<&dyn DeviceAssigningHypervisor> {
None
}
+
+ /// Returns the granule used by all APIs (MEM_SHARE, MMIO_GUARD, device assignment, ...).
+ ///
+ /// If no such API is supported or if they support different granule sizes, returns None.
+ fn get_granule_size(&self) -> Option<usize> {
+ None
+ }
}
pub trait MmioGuardedHypervisor {
diff --git a/libs/libhypervisor_backends/src/hypervisor/geniezone.rs b/libs/libhypervisor_backends/src/hypervisor/geniezone.rs
index 76e010b..0913ff3 100644
--- a/libs/libhypervisor_backends/src/hypervisor/geniezone.rs
+++ b/libs/libhypervisor_backends/src/hypervisor/geniezone.rs
@@ -84,6 +84,10 @@
fn as_mem_sharer(&self) -> Option<&dyn MemSharingHypervisor> {
Some(self)
}
+
+ fn get_granule_size(&self) -> Option<usize> {
+ <Self as MemSharingHypervisor>::granule(self).ok()
+ }
}
impl MmioGuardedHypervisor for GeniezoneHypervisor {
diff --git a/libs/libhypervisor_backends/src/hypervisor/kvm_aarch64.rs b/libs/libhypervisor_backends/src/hypervisor/kvm_aarch64.rs
index 233097b..f183107 100644
--- a/libs/libhypervisor_backends/src/hypervisor/kvm_aarch64.rs
+++ b/libs/libhypervisor_backends/src/hypervisor/kvm_aarch64.rs
@@ -90,6 +90,10 @@
fn as_device_assigner(&self) -> Option<&dyn DeviceAssigningHypervisor> {
Some(self)
}
+
+ fn get_granule_size(&self) -> Option<usize> {
+ <Self as MemSharingHypervisor>::granule(self).ok()
+ }
}
impl MmioGuardedHypervisor for ProtectedKvmHypervisor {
diff --git a/libs/libhypervisor_backends/src/hypervisor/kvm_x86.rs b/libs/libhypervisor_backends/src/hypervisor/kvm_x86.rs
index 7f9ea4d..d72f788 100644
--- a/libs/libhypervisor_backends/src/hypervisor/kvm_x86.rs
+++ b/libs/libhypervisor_backends/src/hypervisor/kvm_x86.rs
@@ -84,6 +84,10 @@
fn as_mem_sharer(&self) -> Option<&dyn MemSharingHypervisor> {
Some(self)
}
+
+ fn get_granule_size(&self) -> Option<usize> {
+ <Self as MemSharingHypervisor>::granule(self).ok()
+ }
}
macro_rules! vmcall {
diff --git a/libs/libhypervisor_backends/src/lib.rs b/libs/libhypervisor_backends/src/lib.rs
index 33dc5ad..3c81ac8 100644
--- a/libs/libhypervisor_backends/src/lib.rs
+++ b/libs/libhypervisor_backends/src/lib.rs
@@ -24,5 +24,6 @@
pub use error::{Error, Result};
pub use hypervisor::{
- get_device_assigner, get_mem_sharer, get_mmio_guard, DeviceAssigningHypervisor, KvmError,
+ get_device_assigner, get_granule_size, get_mem_sharer, get_mmio_guard,
+ DeviceAssigningHypervisor, KvmError,
};
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/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
index 4294df4..4523572 100644
--- a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
+++ b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
@@ -625,7 +625,7 @@
stdout.transferTo(out);
stderr.transferTo(out);
String output = out.toString("UTF-8");
- Log.i(tag, "Got output : " + stdout);
+ Log.i(tag, "Got stdout + stderr : " + output);
return output;
} catch (IOException e) {
Log.e(tag, "Error executing: " + command, e);
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/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]");
}