Merge "Grant CAP_SYS_NICE for virtmgr/crosvm" into main
diff --git a/Android.bp b/Android.bp
index 54919d4..696a963 100644
--- a/Android.bp
+++ b/Android.bp
@@ -28,6 +28,7 @@
"release_avf_enable_multi_tenant_microdroid_vm",
"release_avf_enable_remote_attestation",
"release_avf_enable_vendor_modules",
+ "release_avf_enable_virt_cpufreq",
],
properties: [
"cfgs",
@@ -55,6 +56,9 @@
release_avf_enable_vendor_modules: {
cfgs: ["vendor_modules"],
},
+ release_avf_enable_virt_cpufreq: {
+ cfgs: ["virt_cpufreq"],
+ },
},
}
diff --git a/apex/Android.bp b/apex/Android.bp
index 7c45cc5..ba42c88 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
@@ -32,7 +33,26 @@
},
}
-apex_defaults {
+soong_config_module_type {
+ name: "avf_flag_aware_apex_defaults",
+ module_type: "apex_defaults",
+ config_namespace: "ANDROID",
+ bool_variables: [
+ "release_avf_enable_device_assignment",
+ "release_avf_enable_llpvm_changes",
+ "release_avf_enable_remote_attestation",
+ "release_avf_enable_vendor_modules",
+ ],
+ properties: [
+ "androidManifest",
+ "arch",
+ "prebuilts",
+ "systemserverclasspath_fragments",
+ "vintf_fragments",
+ ],
+}
+
+avf_flag_aware_apex_defaults {
name: "com.android.virt_common",
// TODO(jiyong): make it updatable
updatable: false,
@@ -65,22 +85,13 @@
"libsso",
"libutils",
],
-}
-
-soong_config_module_type {
- name: "avf_flag_aware_apex_defaults",
- module_type: "apex_defaults",
- config_namespace: "ANDROID",
- bool_variables: [
- "release_avf_enable_device_assignment",
- "release_avf_enable_remote_attestation",
- "release_avf_enable_vendor_modules",
- ],
- properties: [
- "arch",
- "prebuilts",
- "vintf_fragments",
- ],
+ soong_config_variables: {
+ release_avf_enable_llpvm_changes: {
+ systemserverclasspath_fragments: [
+ "com.android.virt-systemserver-fragment",
+ ],
+ },
+ },
}
avf_flag_aware_apex_defaults {
@@ -143,6 +154,9 @@
},
},
},
+ release_avf_enable_llpvm_changes: {
+ androidManifest: "AndroidManifest.xml",
+ },
release_avf_enable_vendor_modules: {
prebuilts: [
"microdroid_gki-android14-6.1_initrd_debuggable",
@@ -322,3 +336,29 @@
],
},
}
+
+soong_config_module_type {
+ name: "avf_flag_aware_systemserverclasspath_fragment",
+ module_type: "systemserverclasspath_fragment",
+ config_namespace: "ANDROID",
+ bool_variables: [
+ "release_avf_enable_llpvm_changes",
+ ],
+ properties: [
+ "enabled",
+ ],
+}
+
+avf_flag_aware_systemserverclasspath_fragment {
+ name: "com.android.virt-systemserver-fragment",
+ contents: [
+ "service-virtualization",
+ ],
+ apex_available: ["com.android.virt"],
+ enabled: false,
+ soong_config_variables: {
+ release_avf_enable_llpvm_changes: {
+ enabled: true,
+ },
+ },
+}
diff --git a/apex/AndroidManifest.xml b/apex/AndroidManifest.xml
new file mode 100644
index 0000000..be52f42
--- /dev/null
+++ b/apex/AndroidManifest.xml
@@ -0,0 +1,26 @@
+<?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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.virt">
+ <!-- APEX does not have classes.dex -->
+ <application android:hasCode="false">
+ <apex-system-service
+ android:name="com.android.system.virtualmachine.VirtualizationSystemService"
+ />
+ </application>
+</manifest>
diff --git a/apex/empty-payload-apk/Android.bp b/apex/empty-payload-apk/Android.bp
index 8bd138f..e78daec 100644
--- a/apex/empty-payload-apk/Android.bp
+++ b/apex/empty-payload-apk/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/apex/permissions/Android.bp b/apex/permissions/Android.bp
index 0c925ce..38fd9a1 100644
--- a/apex/permissions/Android.bp
+++ b/apex/permissions/Android.bp
@@ -14,6 +14,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/apex/product_packages.mk b/apex/product_packages.mk
index 4c03836..a318817 100644
--- a/apex/product_packages.mk
+++ b/apex/product_packages.mk
@@ -44,3 +44,15 @@
$(error RELEASE_AVF_ENABLE_VENDOR_MODULES must also be enabled)
endif
endif
+
+ifdef RELEASE_AVF_ENABLE_LLPVM_CHANGES
+ ifndef RELEASE_AVF_ENABLE_DICE_CHANGES
+ $(error RELEASE_AVF_ENABLE_DICE_CHANGES must also be enabled)
+ endif
+endif
+
+ifdef RELEASE_AVF_ENABLE_REMOTE_ATTESTATION
+ ifndef RELEASE_AVF_ENABLE_DICE_CHANGES
+ $(error RELEASE_AVF_ENABLE_DICE_CHANGES must also be enabled)
+ endif
+endif
diff --git a/apkdmverity/Android.bp b/apkdmverity/Android.bp
index 0cb8ca1..40c5f72 100644
--- a/apkdmverity/Android.bp
+++ b/apkdmverity/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/authfs/Android.bp b/authfs/Android.bp
index 8ac600d..8dc6d86 100644
--- a/authfs/Android.bp
+++ b/authfs/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/authfs/aidl/Android.bp b/authfs/aidl/Android.bp
index 9504037..277a964 100644
--- a/authfs/aidl/Android.bp
+++ b/authfs/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/authfs/fd_server/Android.bp b/authfs/fd_server/Android.bp
index b02c104..9a16d04 100644
--- a/authfs/fd_server/Android.bp
+++ b/authfs/fd_server/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/authfs/fd_server/src/main.rs b/authfs/fd_server/src/main.rs
index 47983cb..26315bf 100644
--- a/authfs/fd_server/src/main.rs
+++ b/authfs/fd_server/src/main.rs
@@ -123,7 +123,9 @@
fn main() -> Result<()> {
android_logger::init_once(
- android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
+ android_logger::Config::default()
+ .with_tag("fd_server")
+ .with_max_level(log::LevelFilter::Debug),
);
let args = Args::parse();
diff --git a/authfs/service/Android.bp b/authfs/service/Android.bp
index 2101a36..b4d3b09 100644
--- a/authfs/service/Android.bp
+++ b/authfs/service/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/authfs/service/src/main.rs b/authfs/service/src/main.rs
index 67e22a5..97e684d 100644
--- a/authfs/service/src/main.rs
+++ b/authfs/service/src/main.rs
@@ -130,9 +130,9 @@
#[allow(clippy::eq_op)]
fn try_main() -> Result<()> {
let debuggable = env!("TARGET_BUILD_VARIANT") != "user";
- let log_level = if debuggable { log::Level::Trace } else { log::Level::Info };
+ let log_level = if debuggable { log::LevelFilter::Trace } else { log::LevelFilter::Info };
android_logger::init_once(
- android_logger::Config::default().with_tag("authfs_service").with_min_level(log_level),
+ android_logger::Config::default().with_tag("authfs_service").with_max_level(log_level),
);
clean_up_working_directory()?;
diff --git a/authfs/src/fsverity/metadata/Android.bp b/authfs/src/fsverity/metadata/Android.bp
index c874c2b..c468b7d 100644
--- a/authfs/src/fsverity/metadata/Android.bp
+++ b/authfs/src/fsverity/metadata/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/authfs/src/main.rs b/authfs/src/main.rs
index e14b771..e46b197 100644
--- a/authfs/src/main.rs
+++ b/authfs/src/main.rs
@@ -293,9 +293,9 @@
fn try_main() -> Result<()> {
let args = Args::parse();
- let log_level = if args.debug { log::Level::Debug } else { log::Level::Info };
+ let log_level = if args.debug { log::LevelFilter::Debug } else { log::LevelFilter::Info };
android_logger::init_once(
- android_logger::Config::default().with_tag("authfs").with_min_level(log_level),
+ android_logger::Config::default().with_tag("authfs").with_max_level(log_level),
);
let service = file::get_rpc_binder_service(args.cid)?;
diff --git a/authfs/tests/benchmarks/Android.bp b/authfs/tests/benchmarks/Android.bp
index cea5a81..5ef01cc 100644
--- a/authfs/tests/benchmarks/Android.bp
+++ b/authfs/tests/benchmarks/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/authfs/tests/common/Android.bp b/authfs/tests/common/Android.bp
index bba329e..60d2df3 100644
--- a/authfs/tests/common/Android.bp
+++ b/authfs/tests/common/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/authfs/tests/common/src/open_then_run.rs b/authfs/tests/common/src/open_then_run.rs
index 6d828e4..a976784 100644
--- a/authfs/tests/common/src/open_then_run.rs
+++ b/authfs/tests/common/src/open_then_run.rs
@@ -161,7 +161,7 @@
android_logger::init_once(
android_logger::Config::default()
.with_tag("open_then_run")
- .with_min_level(log::Level::Debug),
+ .with_max_level(log::LevelFilter::Debug),
);
if let Err(e) = try_main() {
diff --git a/authfs/tests/hosttests/Android.bp b/authfs/tests/hosttests/Android.bp
index 83ef853..1e95e10 100644
--- a/authfs/tests/hosttests/Android.bp
+++ b/authfs/tests/hosttests/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/Android.bp b/compos/Android.bp
index b840506..bf57e27 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/aidl/Android.bp b/compos/aidl/Android.bp
index 7036511..1660837 100644
--- a/compos/aidl/Android.bp
+++ b/compos/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/apex/Android.bp b/compos/apex/Android.bp
index 55cc446..8b1ba27 100644
--- a/compos/apex/Android.bp
+++ b/compos/apex/Android.bp
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/apk/Android.bp b/compos/apk/Android.bp
index c6192b9..a06a5a4 100644
--- a/compos/apk/Android.bp
+++ b/compos/apk/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/benchmark/Android.bp b/compos/benchmark/Android.bp
index 93927a2..96d35b4 100644
--- a/compos/benchmark/Android.bp
+++ b/compos/benchmark/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/common/Android.bp b/compos/common/Android.bp
index 01ab7c9..32bdf8a 100644
--- a/compos/common/Android.bp
+++ b/compos/common/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/compos_key_helper/Android.bp b/compos/compos_key_helper/Android.bp
index f8dc783..6b4b61e 100644
--- a/compos/compos_key_helper/Android.bp
+++ b/compos/compos_key_helper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/composd/Android.bp b/compos/composd/Android.bp
index b0294dd..96d4da7 100644
--- a/compos/composd/Android.bp
+++ b/compos/composd/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/composd/aidl/Android.bp b/compos/composd/aidl/Android.bp
index 56b0b60..20e3679 100644
--- a/compos/composd/aidl/Android.bp
+++ b/compos/composd/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/composd/native/Android.bp b/compos/composd/native/Android.bp
index f35517f..a0923ef 100644
--- a/compos/composd/native/Android.bp
+++ b/compos/composd/native/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/composd/src/composd_main.rs b/compos/composd/src/composd_main.rs
index 9f6ce9c..e5d6c75 100644
--- a/compos/composd/src/composd_main.rs
+++ b/compos/composd/src/composd_main.rs
@@ -34,9 +34,9 @@
#[allow(clippy::eq_op)]
fn try_main() -> Result<()> {
let debuggable = env!("TARGET_BUILD_VARIANT") != "user";
- let log_level = if debuggable { log::Level::Debug } else { log::Level::Info };
+ let log_level = if debuggable { log::LevelFilter::Debug } else { log::LevelFilter::Info };
android_logger::init_once(
- android_logger::Config::default().with_tag("composd").with_min_level(log_level),
+ android_logger::Config::default().with_tag("composd").with_max_level(log_level),
);
// Redirect panic messages to logcat.
diff --git a/compos/composd/src/instance_manager.rs b/compos/composd/src/instance_manager.rs
index d7c0f9a..510ad11 100644
--- a/compos/composd/src/instance_manager.rs
+++ b/compos/composd/src/instance_manager.rs
@@ -90,7 +90,7 @@
fn compos_memory_mib() -> Result<i32> {
// Enough memory to complete odrefresh in the VM, for older versions of ART that don't set the
// property explicitly.
- const DEFAULT_MEMORY_MIB: u32 = 400;
+ const DEFAULT_MEMORY_MIB: u32 = 600;
let art_requested_mib =
read_property("composd.vm.art.memory_mib.config")?.unwrap_or(DEFAULT_MEMORY_MIB);
diff --git a/compos/composd_cmd/Android.bp b/compos/composd_cmd/Android.bp
index 4d3ed5f..8b7a909 100644
--- a/compos/composd_cmd/Android.bp
+++ b/compos/composd_cmd/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/service/Android.bp b/compos/service/Android.bp
index 3dcf8be..478ea3b 100644
--- a/compos/service/Android.bp
+++ b/compos/service/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
index 128d581..06cc599 100644
--- a/compos/src/compsvc_main.rs
+++ b/compos/src/compsvc_main.rs
@@ -40,7 +40,9 @@
fn try_main() -> Result<()> {
android_logger::init_once(
- android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
+ android_logger::Config::default()
+ .with_tag("compsvc")
+ .with_max_level(log::LevelFilter::Debug),
);
// Redirect panic messages to logcat.
panic::set_hook(Box::new(|panic_info| {
diff --git a/compos/tests/Android.bp b/compos/tests/Android.bp
index 511ecd0..1213a16 100644
--- a/compos/tests/Android.bp
+++ b/compos/tests/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/verify/Android.bp b/compos/verify/Android.bp
index f4d8695..6fba1fd 100644
--- a/compos/verify/Android.bp
+++ b/compos/verify/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/verify/native/Android.bp b/compos/verify/native/Android.bp
index 438d93a..70cb2ab 100644
--- a/compos/verify/native/Android.bp
+++ b/compos/verify/native/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/compos/verify/verify.rs b/compos/verify/verify.rs
index 952e9c7..567083d 100644
--- a/compos/verify/verify.rs
+++ b/compos/verify/verify.rs
@@ -60,8 +60,8 @@
android_logger::init_once(
android_logger::Config::default()
.with_tag("compos_verify")
- .with_min_level(log::Level::Info)
- .with_log_id(LogId::System), // Needed to log successfully early in boot
+ .with_max_level(log::LevelFilter::Info)
+ .with_log_buffer(LogId::System), // Needed to log successfully early in boot
);
// Redirect panic messages to logcat.
diff --git a/demo/Android.bp b/demo/Android.bp
index a291ee1..90e302a 100644
--- a/demo/Android.bp
+++ b/demo/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/demo_native/Android.bp b/demo_native/Android.bp
index 901f829..7b6967e 100644
--- a/demo_native/Android.bp
+++ b/demo_native/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/encryptedstore/Android.bp b/encryptedstore/Android.bp
index aa46c35..225eedd 100644
--- a/encryptedstore/Android.bp
+++ b/encryptedstore/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/encryptedstore/src/main.rs b/encryptedstore/src/main.rs
index dcb1cba..983e3e9 100644
--- a/encryptedstore/src/main.rs
+++ b/encryptedstore/src/main.rs
@@ -37,7 +37,7 @@
android_logger::init_once(
android_logger::Config::default()
.with_tag("encryptedstore")
- .with_min_level(log::Level::Info),
+ .with_max_level(log::LevelFilter::Info),
);
if let Err(e) = try_main() {
diff --git a/javalib/Android.bp b/javalib/Android.bp
index e3cb2e3..680d59b 100644
--- a/javalib/Android.bp
+++ b/javalib/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/javalib/jni/Android.bp b/javalib/jni/Android.bp
index e82b2ce..6e2a129 100644
--- a/javalib/jni/Android.bp
+++ b/javalib/jni/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/javalib/service/Android.bp b/javalib/service/Android.bp
new file mode 100644
index 0000000..9c1fa01
--- /dev/null
+++ b/javalib/service/Android.bp
@@ -0,0 +1,30 @@
+// Copyright (C) 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.
+
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+java_library {
+ name: "service-virtualization",
+ srcs: [
+ "src/**/*.java",
+ ],
+ defaults: [
+ "framework-system-server-module-defaults",
+ ],
+ sdk_version: "system_server_current",
+ apex_available: ["com.android.virt"],
+ installable: true,
+}
diff --git a/javalib/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java b/javalib/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java
new file mode 100644
index 0000000..2905acd
--- /dev/null
+++ b/javalib/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 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.
+ */
+
+package com.android.system.virtualmachine;
+
+import android.content.Context;
+import com.android.server.SystemService;
+
+/** TODO */
+public class VirtualizationSystemService extends SystemService {
+
+ public VirtualizationSystemService(Context context) {
+ super(context);
+ }
+
+ @Override
+ public void onStart() {}
+}
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index a6381ac..e8ef195 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -49,6 +49,7 @@
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.Collections;
import java.util.Objects;
import java.util.zip.ZipFile;
@@ -519,6 +520,7 @@
VirtualMachinePayloadConfig payloadConfig = new VirtualMachinePayloadConfig();
payloadConfig.payloadBinaryName = mPayloadBinaryName;
payloadConfig.osName = mOs;
+ payloadConfig.extraApks = Collections.emptyList();
vsConfig.payload =
VirtualMachineAppConfig.Payload.payloadConfig(payloadConfig);
} else {
@@ -947,7 +949,8 @@
@FlaggedApi("RELEASE_AVF_ENABLE_VENDOR_MODULES")
@NonNull
public Builder setVendorDiskImage(@NonNull File vendorDiskImage) {
- mVendorDiskImage = vendorDiskImage;
+ mVendorDiskImage =
+ requireNonNull(vendorDiskImage, "vendor disk image must not be null");
return this;
}
diff --git a/javalib/src/android/system/virtualmachine/VirtualizationService.java b/javalib/src/android/system/virtualmachine/VirtualizationService.java
index 1cf97b5..57990a9 100644
--- a/javalib/src/android/system/virtualmachine/VirtualizationService.java
+++ b/javalib/src/android/system/virtualmachine/VirtualizationService.java
@@ -57,13 +57,13 @@
private VirtualizationService() throws VirtualMachineException {
int clientFd = nativeSpawn();
if (clientFd < 0) {
- throw new VirtualMachineException("Could not spawn VirtualizationService");
+ throw new VirtualMachineException("Could not spawn Virtualization Manager");
}
mClientFd = ParcelFileDescriptor.adoptFd(clientFd);
IBinder binder = nativeConnect(mClientFd.getFd());
if (binder == null) {
- throw new VirtualMachineException("Could not connect to VirtualizationService");
+ throw new VirtualMachineException("Could not connect to Virtualization Manager");
}
mBinder = IVirtualizationService.Stub.asInterface(binder);
}
diff --git a/launcher/Android.bp b/launcher/Android.bp
index 6c6417f..c6873ce 100644
--- a/launcher/Android.bp
+++ b/launcher/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/apexutil/Android.bp b/libs/apexutil/Android.bp
index beff58d..410c3cf 100644
--- a/libs/apexutil/Android.bp
+++ b/libs/apexutil/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/apkverify/Android.bp b/libs/apkverify/Android.bp
index 4c5a622..e39c46d 100644
--- a/libs/apkverify/Android.bp
+++ b/libs/apkverify/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/apkverify/tests/apkverify_test.rs b/libs/apkverify/tests/apkverify_test.rs
index 441b708..96fad5f 100644
--- a/libs/apkverify/tests/apkverify_test.rs
+++ b/libs/apkverify/tests/apkverify_test.rs
@@ -37,7 +37,7 @@
android_logger::init_once(
android_logger::Config::default()
.with_tag("apkverify_test")
- .with_min_level(log::Level::Info),
+ .with_max_level(log::LevelFilter::Info),
);
info!("Test starting");
}
diff --git a/libs/apkzip/Android.bp b/libs/apkzip/Android.bp
index dc35b5e..f3622b1 100644
--- a/libs/apkzip/Android.bp
+++ b/libs/apkzip/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/avflog/Android.bp b/libs/avflog/Android.bp
index 695a6c6..7e8daef 100644
--- a/libs/avflog/Android.bp
+++ b/libs/avflog/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/bssl/Android.bp b/libs/bssl/Android.bp
index 2bb5ba5..b023e87 100644
--- a/libs/bssl/Android.bp
+++ b/libs/bssl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/bssl/error/Android.bp b/libs/bssl/error/Android.bp
index 000e385..ebdbc0a 100644
--- a/libs/bssl/error/Android.bp
+++ b/libs/bssl/error/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/capabilities/Android.bp b/libs/capabilities/Android.bp
index 55112e1..2799926 100644
--- a/libs/capabilities/Android.bp
+++ b/libs/capabilities/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/cstr/Android.bp b/libs/cstr/Android.bp
index 4ea87df..88f43a0 100644
--- a/libs/cstr/Android.bp
+++ b/libs/cstr/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/devicemapper/Android.bp b/libs/devicemapper/Android.bp
index 5332469..5c74162 100644
--- a/libs/devicemapper/Android.bp
+++ b/libs/devicemapper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/dice/open_dice/Android.bp b/libs/dice/open_dice/Android.bp
index 79d0b96..9481f5d 100644
--- a/libs/dice/open_dice/Android.bp
+++ b/libs/dice/open_dice/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_visibility: [":__subpackages__"],
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/dice/sample_inputs/Android.bp b/libs/dice/sample_inputs/Android.bp
index 013038c..e5d35a7 100644
--- a/libs/dice/sample_inputs/Android.bp
+++ b/libs/dice/sample_inputs/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/libfdt/Android.bp b/libs/libfdt/Android.bp
index ba9e971..7231904 100644
--- a/libs/libfdt/Android.bp
+++ b/libs/libfdt/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/libs/vbmeta/Android.bp b/libs/vbmeta/Android.bp
index 4fb6ae4..48f9e51 100644
--- a/libs/vbmeta/Android.bp
+++ b/libs/vbmeta/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index 233754a..e2d7af4 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid/fstab.microdroid b/microdroid/fstab.microdroid
index 2742757..3209442 100644
--- a/microdroid/fstab.microdroid
+++ b/microdroid/fstab.microdroid
@@ -2,4 +2,4 @@
# This is a temporary solution to unblock other devs that depend on /vendor partition in Microdroid
# The /vendor partition will only be mounted if the kernel cmdline contains
# androidboot.microdroid.mount_vendor=1.
-/dev/block/by-name/microdroid-vendor /vendor ext4 noatime,ro,errors=panic wait,first_stage_mount,avb_hashtree_digest=/sys/firmware/devicetree/base/avf/vendor_hashtree_descriptor_root_digest
+/dev/block/by-name/microdroid-vendor /vendor ext4 noatime,ro,errors=panic wait,first_stage_mount,avb_hashtree_digest=/proc/device-tree/avf/vendor_hashtree_descriptor_root_digest
diff --git a/microdroid/init_debug_policy/Android.bp b/microdroid/init_debug_policy/Android.bp
index 2a87ac9..320417d 100644
--- a/microdroid/init_debug_policy/Android.bp
+++ b/microdroid/init_debug_policy/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid/init_debug_policy/src/init_debug_policy.rs b/microdroid/init_debug_policy/src/init_debug_policy.rs
index 6c80926..90d04ac 100644
--- a/microdroid/init_debug_policy/src/init_debug_policy.rs
+++ b/microdroid/init_debug_policy/src/init_debug_policy.rs
@@ -29,11 +29,10 @@
}
fn main() -> Result<(), PropertyWatcherError> {
- // If VM is debuggable or debug policy says so, send logs to outside ot the VM via the serial console.
- // Otherwise logs are internally consumed at /dev/null
+ // If VM is debuggable or debug policy says so, send logs to outside ot the VM via the serial
+ // console. Otherwise logs are internally consumed at /dev/null
let log_path = if system_properties::read_bool("ro.boot.microdroid.debuggable", false)?
- || get_debug_policy_bool("/sys/firmware/devicetree/base/avf/guest/common/log")
- .unwrap_or_default()
+ || get_debug_policy_bool("/proc/device-tree/avf/guest/common/log").unwrap_or_default()
{
"/dev/hvc2"
} else {
@@ -42,8 +41,7 @@
system_properties::write("ro.log.file_logger.path", log_path)?;
let (adbd_enabled, debuggable) = if system_properties::read_bool("ro.boot.adb.enabled", false)?
- || get_debug_policy_bool("/sys/firmware/devicetree/base/avf/guest/microdroid/adb")
- .unwrap_or_default()
+ || get_debug_policy_bool("/proc/device-tree/avf/guest/microdroid/adb").unwrap_or_default()
{
// debuggable is required for adb root and bypassing adb authorization.
("1", "1")
diff --git a/microdroid/initrd/Android.bp b/microdroid/initrd/Android.bp
index ec971fa..6f1c9a1 100644
--- a/microdroid/initrd/Android.bp
+++ b/microdroid/initrd/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid/kdump/Android.bp b/microdroid/kdump/Android.bp
index b9a18fe..ff73fdb 100644
--- a/microdroid/kdump/Android.bp
+++ b/microdroid/kdump/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid/kdump/kernel/Android.bp b/microdroid/kdump/kernel/Android.bp
index 0705875..9d241b4 100644
--- a/microdroid/kdump/kernel/Android.bp
+++ b/microdroid/kdump/kernel/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["microdroid_crashdump_kernel_license"],
}
diff --git a/microdroid/kernel/arm64/Android.bp b/microdroid/kernel/arm64/Android.bp
index 0975993..e014509 100644
--- a/microdroid/kernel/arm64/Android.bp
+++ b/microdroid/kernel/arm64/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["microdroid_kernel_prebuilts_6.1_arm64_license"],
}
diff --git a/microdroid/kernel/x86_64/Android.bp b/microdroid/kernel/x86_64/Android.bp
index b3041cd..f7161de 100644
--- a/microdroid/kernel/x86_64/Android.bp
+++ b/microdroid/kernel/x86_64/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["microdroid_kernel_prebuilts_6.1_x86_64_license"],
}
diff --git a/microdroid/payload/Android.bp b/microdroid/payload/Android.bp
index 4814a64..7e11de3 100644
--- a/microdroid/payload/Android.bp
+++ b/microdroid/payload/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid/payload/config/Android.bp b/microdroid/payload/config/Android.bp
index 4c72b97..7abee15 100644
--- a/microdroid/payload/config/Android.bp
+++ b/microdroid/payload/config/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid/payload/metadata.proto b/microdroid/payload/metadata.proto
index b03d466..e47fc83 100644
--- a/microdroid/payload/metadata.proto
+++ b/microdroid/payload/metadata.proto
@@ -74,4 +74,8 @@
// Required.
// Name of the payload binary file inside the APK.
string payload_binary_name = 1;
+
+ // Optional.
+ // The number of extra APKs that are present.
+ uint32 extra_apk_count = 2;
}
diff --git a/microdroid/payload/metadata/Android.bp b/microdroid/payload/metadata/Android.bp
index cd182fc..be87fb8 100644
--- a/microdroid/payload/metadata/Android.bp
+++ b/microdroid/payload/metadata/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid_manager/Android.bp b/microdroid_manager/Android.bp
index 1696aae..0174ce4 100644
--- a/microdroid_manager/Android.bp
+++ b/microdroid_manager/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
@@ -29,7 +30,7 @@
"libclient_vm_csr",
"libciborium",
"libcoset",
- "libdice_policy",
+ "libdice_policy_builder",
"libdiced_open_dice",
"libdiced_sample_inputs",
"libglob",
diff --git a/microdroid_manager/aidl/Android.bp b/microdroid_manager/aidl/Android.bp
index 353e9cc..be035df 100644
--- a/microdroid_manager/aidl/Android.bp
+++ b/microdroid_manager/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 8888feb..86284a5 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -43,7 +43,7 @@
use libc::VMADDR_CID_HOST;
use log::{error, info};
use microdroid_metadata::PayloadMetadata;
-use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
+use microdroid_payload_config::{ApkConfig, OsConfig, Task, TaskType, VmPayloadConfig};
use nix::sys::signal::Signal;
use openssl::hkdf::hkdf;
use openssl::md::Md;
@@ -68,11 +68,11 @@
use vm_secret::VmSecret;
const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
-const AVF_STRICT_BOOT: &str = "/sys/firmware/devicetree/base/chosen/avf,strict-boot";
-const AVF_NEW_INSTANCE: &str = "/sys/firmware/devicetree/base/chosen/avf,new-instance";
-const AVF_DEBUG_POLICY_RAMDUMP: &str = "/sys/firmware/devicetree/base/avf/guest/common/ramdump";
+const AVF_STRICT_BOOT: &str = "/proc/device-tree/chosen/avf,strict-boot";
+const AVF_NEW_INSTANCE: &str = "/proc/device-tree/chosen/avf,new-instance";
+const AVF_DEBUG_POLICY_RAMDUMP: &str = "/proc/device-tree/avf/guest/common/ramdump";
const DEBUG_MICRODROID_NO_VERIFIED_BOOT: &str =
- "/sys/firmware/devicetree/base/virtualization/guest/debug-microdroid,no-verified-boot";
+ "/proc/device-tree/virtualization/guest/debug-microdroid,no-verified-boot";
const ENCRYPTEDSTORE_BIN: &str = "/system/bin/encryptedstore";
const ZIPFUSE_BIN: &str = "/system/bin/zipfuse";
@@ -171,7 +171,7 @@
android_logger::init_once(
android_logger::Config::default()
.with_tag("microdroid_manager")
- .with_min_level(log::Level::Info),
+ .with_max_level(log::LevelFilter::Info),
);
info!("started.");
@@ -580,11 +580,15 @@
type_: TaskType::MicrodroidLauncher,
command: payload_config.payload_binary_name,
};
+ // We don't care about the paths, only the number of extra APKs really matters.
+ let extra_apks = (0..payload_config.extra_apk_count)
+ .map(|i| ApkConfig { path: format!("extra-apk-{i}") })
+ .collect();
Ok(VmPayloadConfig {
os: OsConfig { name: "microdroid".to_owned() },
task: Some(task),
apexes: vec![],
- extra_apks: vec![],
+ extra_apks,
prefer_staged: false,
export_tombstones: None,
enable_authfs: false,
diff --git a/microdroid_manager/src/vm_secret.rs b/microdroid_manager/src/vm_secret.rs
index 9b7d4f1..0e1ec71 100644
--- a/microdroid_manager/src/vm_secret.rs
+++ b/microdroid_manager/src/vm_secret.rs
@@ -20,7 +20,7 @@
use secretkeeper_comm::data_types::request::Request;
use binder::{Strong};
use coset::CborSerializable;
-use dice_policy::{ConstraintSpec, ConstraintType, DicePolicy, MissingAction};
+use dice_policy_builder::{CertIndex, ConstraintSpec, ConstraintType, policy_for_dice_chain, MissingAction, WILDCARD_FULL_ARRAY};
use diced_open_dice::{DiceArtifacts, OwnedDiceArtifacts};
use keystore2_crypto::ZVec;
use openssl::hkdf::hkdf;
@@ -41,6 +41,12 @@
const MODE: i64 = -4670551;
const CONFIG_DESC: i64 = -4670548;
const SECURITY_VERSION: i64 = -70005;
+const SUBCOMPONENT_DESCRIPTORS: i64 = -71002;
+const SUBCOMPONENT_SECURITY_VERSION: i64 = 2;
+const SUBCOMPONENT_AUTHORITY_HASH: i64 = 4;
+// Index of DiceChainEntry corresponding to Payload (relative to the end considering DICE Chain
+// as an array)
+const PAYLOAD_INDEX_FROM_END: usize = 0;
// Generated using hexdump -vn32 -e'14/1 "0x%02X, " 1 "\n"' /dev/urandom
const SALT_ENCRYPTED_STORE: &[u8] = &[
@@ -161,19 +167,55 @@
// components may chose to prevent booting of rollback images for ex, ABL is expected to provide
// rollback protection of pvmfw. Such components may chose to not put SECURITY_VERSION in the
// corresponding DiceChainEntry.
-// TODO(b/291219197) : Add constraints on Extra apks as well!
+// 4. For each Subcomponent on the last DiceChainEntry (which corresponds to VM payload, See
+// microdroid_manager/src/vm_config.cddl):
+// - GreaterOrEqual on SECURITY_VERSION (Required)
+// - ExactMatch on AUTHORITY_HASH (Required).
fn sealing_policy(dice: &[u8]) -> Result<Vec<u8>, String> {
let constraint_spec = [
- ConstraintSpec::new(ConstraintType::ExactMatch, vec![AUTHORITY_HASH], MissingAction::Fail),
- ConstraintSpec::new(ConstraintType::ExactMatch, vec![MODE], MissingAction::Fail),
+ ConstraintSpec::new(
+ ConstraintType::ExactMatch,
+ vec![AUTHORITY_HASH],
+ MissingAction::Fail,
+ CertIndex::All,
+ ),
+ ConstraintSpec::new(
+ ConstraintType::ExactMatch,
+ vec![MODE],
+ MissingAction::Fail,
+ CertIndex::All,
+ ),
ConstraintSpec::new(
ConstraintType::GreaterOrEqual,
vec![CONFIG_DESC, SECURITY_VERSION],
MissingAction::Ignore,
+ CertIndex::All,
+ ),
+ ConstraintSpec::new(
+ ConstraintType::GreaterOrEqual,
+ vec![
+ CONFIG_DESC,
+ SUBCOMPONENT_DESCRIPTORS,
+ WILDCARD_FULL_ARRAY,
+ SUBCOMPONENT_SECURITY_VERSION,
+ ],
+ MissingAction::Fail,
+ CertIndex::FromEnd(PAYLOAD_INDEX_FROM_END),
+ ),
+ ConstraintSpec::new(
+ ConstraintType::ExactMatch,
+ vec![
+ CONFIG_DESC,
+ SUBCOMPONENT_DESCRIPTORS,
+ WILDCARD_FULL_ARRAY,
+ SUBCOMPONENT_AUTHORITY_HASH,
+ ],
+ MissingAction::Fail,
+ CertIndex::FromEnd(PAYLOAD_INDEX_FROM_END),
),
];
- DicePolicy::from_dice_chain(dice, &constraint_spec)?
+ policy_for_dice_chain(dice, &constraint_spec)?
.to_vec()
.map_err(|e| format!("DicePolicy construction failed {e:?}"))
}
diff --git a/pvmfw/Android.bp b/pvmfw/Android.bp
index b7b17e4..ee77f14 100644
--- a/pvmfw/Android.bp
+++ b/pvmfw/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/pvmfw/avb/Android.bp b/pvmfw/avb/Android.bp
index 6df1c4d..3bb8354 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
@@ -9,7 +10,6 @@
srcs: ["src/lib.rs"],
prefer_rlib: true,
rustlibs: [
- "libavb_bindgen_nostd",
"libavb_rs_nostd",
"libtinyvec_nostd",
],
diff --git a/pvmfw/avb/fuzz/Android.bp b/pvmfw/avb/fuzz/Android.bp
index e970eed..fe3af0f 100644
--- a/pvmfw/avb/fuzz/Android.bp
+++ b/pvmfw/avb/fuzz/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/pvmfw/avb/src/descriptor.rs b/pvmfw/avb/src/descriptor.rs
deleted file mode 100644
index a3db0e5..0000000
--- a/pvmfw/avb/src/descriptor.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2023, 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.
-
-//! Structs and functions relating to the descriptors.
-
-mod collection;
-mod common;
-mod hash;
-mod property;
-
-pub(crate) use collection::Descriptors;
-pub use hash::Digest;
diff --git a/pvmfw/avb/src/descriptor/collection.rs b/pvmfw/avb/src/descriptor/collection.rs
deleted file mode 100644
index 6784758..0000000
--- a/pvmfw/avb/src/descriptor/collection.rs
+++ /dev/null
@@ -1,190 +0,0 @@
-// Copyright 2023, 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.
-
-//! Structs and functions relating to the descriptor collection.
-
-use super::common::get_valid_descriptor;
-use super::hash::HashDescriptor;
-use super::property::PropertyDescriptor;
-use crate::partition::PartitionName;
-use crate::utils::{to_usize, usize_checked_add};
-use crate::PvmfwVerifyError;
-use avb::{IoError, IoResult, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData};
-use avb_bindgen::{
- avb_descriptor_foreach, avb_descriptor_validate_and_byteswap, AvbDescriptor, AvbDescriptorTag,
-};
-use core::{ffi::c_void, mem::size_of, slice};
-use tinyvec::ArrayVec;
-
-/// `Descriptors` can have at most one `HashDescriptor` per known partition and at most one
-/// `PropertyDescriptor`.
-#[derive(Default)]
-pub(crate) struct Descriptors<'a> {
- hash_descriptors: ArrayVec<[HashDescriptor<'a>; PartitionName::NUM_OF_KNOWN_PARTITIONS]>,
- prop_descriptor: Option<PropertyDescriptor<'a>>,
-}
-
-impl<'a> Descriptors<'a> {
- /// Builds `Descriptors` from `VbmetaData`.
- /// Returns an error if the given `VbmetaData` contains non-hash descriptor, hash
- /// descriptor of unknown `PartitionName` or duplicated hash descriptors.
- pub(crate) fn from_vbmeta(vbmeta: &'a VbmetaData) -> Result<Self, PvmfwVerifyError> {
- let mut res: IoResult<Self> = Ok(Self::default());
- // SAFETY: It is safe as `vbmeta.data()` contains a valid VBMeta structure.
- let output = unsafe {
- avb_descriptor_foreach(
- vbmeta.data().as_ptr(),
- vbmeta.data().len(),
- Some(check_and_save_descriptor),
- &mut res as *mut _ as *mut c_void,
- )
- };
- if output == res.is_ok() {
- res.map_err(PvmfwVerifyError::InvalidDescriptors)
- } else {
- Err(SlotVerifyError::InvalidMetadata.into())
- }
- }
-
- pub(crate) fn num_hash_descriptor(&self) -> usize {
- self.hash_descriptors.len()
- }
-
- /// Finds the `HashDescriptor` for the given `PartitionName`.
- /// Throws an error if no corresponding descriptor found.
- pub(crate) fn find_hash_descriptor(
- &self,
- partition_name: PartitionName,
- ) -> SlotVerifyNoDataResult<&HashDescriptor> {
- self.hash_descriptors
- .iter()
- .find(|d| d.partition_name == partition_name)
- .ok_or(SlotVerifyError::InvalidMetadata)
- }
-
- pub(crate) fn has_property_descriptor(&self) -> bool {
- self.prop_descriptor.is_some()
- }
-
- pub(crate) fn find_property_value(&self, key: &[u8]) -> Option<&[u8]> {
- self.prop_descriptor.as_ref().filter(|desc| desc.key == key).map(|desc| desc.value)
- }
-
- fn push(&mut self, descriptor: Descriptor<'a>) -> IoResult<()> {
- match descriptor {
- Descriptor::Hash(d) => self.push_hash_descriptor(d),
- Descriptor::Property(d) => self.push_property_descriptor(d),
- }
- }
-
- fn push_hash_descriptor(&mut self, descriptor: HashDescriptor<'a>) -> IoResult<()> {
- if self.hash_descriptors.iter().any(|d| d.partition_name == descriptor.partition_name) {
- return Err(IoError::Io);
- }
- self.hash_descriptors.push(descriptor);
- Ok(())
- }
-
- fn push_property_descriptor(&mut self, descriptor: PropertyDescriptor<'a>) -> IoResult<()> {
- if self.prop_descriptor.is_some() {
- return Err(IoError::Io);
- }
- self.prop_descriptor.replace(descriptor);
- Ok(())
- }
-}
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor` pointer must be non-null and points to a valid `AvbDescriptor` struct.
-/// * The `user_data` pointer must be non-null, points to a valid `IoResult<Descriptors>`
-/// struct and is initialized.
-unsafe extern "C" fn check_and_save_descriptor(
- descriptor: *const AvbDescriptor,
- user_data: *mut c_void,
-) -> bool {
- // SAFETY: It is safe because the caller ensures that `user_data` points to a valid struct and
- // is initialized.
- let Some(res) = (unsafe { (user_data as *mut IoResult<Descriptors>).as_mut() }) else {
- return false;
- };
- let Ok(descriptors) = res else {
- return false;
- };
- // SAFETY: It is safe because the caller ensures that the `descriptor` pointer is non-null
- // and valid.
- unsafe { try_check_and_save_descriptor(descriptor, descriptors) }.map_or_else(
- |e| {
- *res = Err(e);
- false
- },
- |_| true,
- )
-}
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor` pointer must be non-null and points to a valid `AvbDescriptor` struct.
-unsafe fn try_check_and_save_descriptor(
- descriptor: *const AvbDescriptor,
- descriptors: &mut Descriptors,
-) -> IoResult<()> {
- // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null pointer
- // pointing to a valid struct.
- let descriptor = unsafe { Descriptor::from_descriptor_ptr(descriptor)? };
- descriptors.push(descriptor)
-}
-
-enum Descriptor<'a> {
- Hash(HashDescriptor<'a>),
- Property(PropertyDescriptor<'a>),
-}
-
-impl<'a> Descriptor<'a> {
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
- let avb_descriptor =
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- unsafe { get_valid_descriptor(descriptor, avb_descriptor_validate_and_byteswap)? };
- let len = usize_checked_add(
- size_of::<AvbDescriptor>(),
- to_usize(avb_descriptor.num_bytes_following)?,
- )?;
- // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null pointer
- // pointing to a valid struct.
- let data = unsafe { slice::from_raw_parts(descriptor as *const u8, len) };
- match avb_descriptor.tag.try_into() {
- Ok(AvbDescriptorTag::AVB_DESCRIPTOR_TAG_HASH) => {
- // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null
- // pointer pointing to a valid struct.
- let descriptor = unsafe { HashDescriptor::from_descriptor_ptr(descriptor, data)? };
- Ok(Self::Hash(descriptor))
- }
- Ok(AvbDescriptorTag::AVB_DESCRIPTOR_TAG_PROPERTY) => {
- let descriptor =
- // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null
- // pointer pointing to a valid struct.
- unsafe { PropertyDescriptor::from_descriptor_ptr(descriptor, data)? };
- Ok(Self::Property(descriptor))
- }
- _ => Err(IoError::NoSuchValue),
- }
- }
-}
diff --git a/pvmfw/avb/src/descriptor/common.rs b/pvmfw/avb/src/descriptor/common.rs
deleted file mode 100644
index 6063a7c..0000000
--- a/pvmfw/avb/src/descriptor/common.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2023, 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.
-
-//! Structs and functions used by all the descriptors.
-
-use crate::utils::is_not_null;
-use avb::{IoError, IoResult};
-use core::mem::MaybeUninit;
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor_ptr` pointer must be non-null and point to a valid `AvbDescriptor`.
-pub(super) unsafe fn get_valid_descriptor<T>(
- descriptor_ptr: *const T,
- descriptor_validate_and_byteswap: unsafe extern "C" fn(src: *const T, dest: *mut T) -> bool,
-) -> IoResult<T> {
- is_not_null(descriptor_ptr)?;
- // SAFETY: It is safe because the caller ensures that `descriptor_ptr` is a non-null pointer
- // pointing to a valid struct.
- let descriptor = unsafe {
- let mut desc = MaybeUninit::uninit();
- if !descriptor_validate_and_byteswap(descriptor_ptr, desc.as_mut_ptr()) {
- return Err(IoError::Io);
- }
- desc.assume_init()
- };
- Ok(descriptor)
-}
diff --git a/pvmfw/avb/src/descriptor/hash.rs b/pvmfw/avb/src/descriptor/hash.rs
deleted file mode 100644
index 35db66d..0000000
--- a/pvmfw/avb/src/descriptor/hash.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2023, 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.
-
-//! Structs and functions relating to the hash descriptor.
-
-use super::common::get_valid_descriptor;
-use crate::partition::PartitionName;
-use crate::utils::{to_usize, usize_checked_add};
-use avb::{IoError, IoResult};
-use avb_bindgen::{
- avb_hash_descriptor_validate_and_byteswap, AvbDescriptor, AvbHashDescriptor,
- AVB_SHA256_DIGEST_SIZE,
-};
-use core::{mem::size_of, ops::Range};
-
-/// Digest type for kernel and initrd.
-pub type Digest = [u8; AVB_SHA256_DIGEST_SIZE as usize];
-
-pub(crate) struct HashDescriptor<'a> {
- pub(crate) partition_name: PartitionName,
- pub(crate) digest: &'a Digest,
-}
-
-impl<'a> Default for HashDescriptor<'a> {
- fn default() -> Self {
- Self { partition_name: Default::default(), digest: &Self::EMPTY_DIGEST }
- }
-}
-
-impl<'a> HashDescriptor<'a> {
- const EMPTY_DIGEST: Digest = [0u8; AVB_SHA256_DIGEST_SIZE as usize];
-
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- pub(super) unsafe fn from_descriptor_ptr(
- descriptor: *const AvbDescriptor,
- data: &'a [u8],
- ) -> IoResult<Self> {
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- let h = unsafe { HashDescriptorHeader::from_descriptor_ptr(descriptor)? };
- let partition_name = data
- .get(h.partition_name_range()?)
- .ok_or(IoError::RangeOutsidePartition)?
- .try_into()?;
- let digest = data
- .get(h.digest_range()?)
- .ok_or(IoError::RangeOutsidePartition)?
- .try_into()
- .map_err(|_| IoError::InvalidValueSize)?;
- Ok(Self { partition_name, digest })
- }
-}
-
-struct HashDescriptorHeader(AvbHashDescriptor);
-
-impl HashDescriptorHeader {
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- unsafe {
- get_valid_descriptor(
- descriptor as *const AvbHashDescriptor,
- avb_hash_descriptor_validate_and_byteswap,
- )
- .map(Self)
- }
- }
-
- fn partition_name_end(&self) -> IoResult<usize> {
- usize_checked_add(size_of::<AvbHashDescriptor>(), to_usize(self.0.partition_name_len)?)
- }
-
- fn partition_name_range(&self) -> IoResult<Range<usize>> {
- let start = size_of::<AvbHashDescriptor>();
- Ok(start..(self.partition_name_end()?))
- }
-
- fn digest_range(&self) -> IoResult<Range<usize>> {
- let start = usize_checked_add(self.partition_name_end()?, to_usize(self.0.salt_len)?)?;
- let end = usize_checked_add(start, to_usize(self.0.digest_len)?)?;
- Ok(start..end)
- }
-}
diff --git a/pvmfw/avb/src/descriptor/property.rs b/pvmfw/avb/src/descriptor/property.rs
deleted file mode 100644
index 8145d64..0000000
--- a/pvmfw/avb/src/descriptor/property.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2023, 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.
-
-//! Structs and functions relating to the property descriptor.
-
-use super::common::get_valid_descriptor;
-use crate::utils::{to_usize, usize_checked_add};
-use avb::{IoError, IoResult};
-use avb_bindgen::{
- avb_property_descriptor_validate_and_byteswap, AvbDescriptor, AvbPropertyDescriptor,
-};
-use core::mem::size_of;
-
-pub(super) struct PropertyDescriptor<'a> {
- pub(super) key: &'a [u8],
- pub(super) value: &'a [u8],
-}
-
-impl<'a> PropertyDescriptor<'a> {
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- pub(super) unsafe fn from_descriptor_ptr(
- descriptor: *const AvbDescriptor,
- data: &'a [u8],
- ) -> IoResult<Self> {
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- let h = unsafe { PropertyDescriptorHeader::from_descriptor_ptr(descriptor)? };
- let key = Self::get_valid_slice(data, h.key_start(), h.key_end()?)?;
- let value = Self::get_valid_slice(data, h.value_start()?, h.value_end()?)?;
- Ok(Self { key, value })
- }
-
- fn get_valid_slice(data: &[u8], start: usize, end: usize) -> IoResult<&[u8]> {
- const NUL_BYTE: u8 = b'\0';
-
- match data.get(end) {
- Some(&NUL_BYTE) => data.get(start..end).ok_or(IoError::RangeOutsidePartition),
- _ => Err(IoError::NoSuchValue),
- }
- }
-}
-
-struct PropertyDescriptorHeader(AvbPropertyDescriptor);
-
-impl PropertyDescriptorHeader {
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- unsafe {
- get_valid_descriptor(
- descriptor as *const AvbPropertyDescriptor,
- avb_property_descriptor_validate_and_byteswap,
- )
- .map(Self)
- }
- }
-
- fn key_start(&self) -> usize {
- size_of::<AvbPropertyDescriptor>()
- }
-
- fn key_end(&self) -> IoResult<usize> {
- usize_checked_add(self.key_start(), to_usize(self.0.key_num_bytes)?)
- }
-
- fn value_start(&self) -> IoResult<usize> {
- // There is a NUL byte between key and value.
- usize_checked_add(self.key_end()?, 1)
- }
-
- fn value_end(&self) -> IoResult<usize> {
- usize_checked_add(self.value_start()?, to_usize(self.0.value_num_bytes)?)
- }
-}
diff --git a/pvmfw/avb/src/error.rs b/pvmfw/avb/src/error.rs
index 4e3f27e..2e1950a 100644
--- a/pvmfw/avb/src/error.rs
+++ b/pvmfw/avb/src/error.rs
@@ -15,7 +15,7 @@
//! This module contains the error thrown by the payload verification API
//! and other errors used in the library.
-use avb::{IoError, SlotVerifyError};
+use avb::{DescriptorError, SlotVerifyError};
use core::fmt;
/// Wrapper around `SlotVerifyError` to add custom pvmfw errors.
@@ -25,7 +25,7 @@
/// Passthrough `SlotVerifyError` with no `SlotVerifyData`.
AvbError(SlotVerifyError<'static>),
/// VBMeta has invalid descriptors.
- InvalidDescriptors(IoError),
+ InvalidDescriptors(DescriptorError),
/// Unknown vbmeta property.
UnknownVbmetaProperty,
}
@@ -37,6 +37,12 @@
}
}
+impl From<DescriptorError> for PvmfwVerifyError {
+ fn from(error: DescriptorError) -> Self {
+ Self::InvalidDescriptors(error)
+ }
+}
+
impl fmt::Display for PvmfwVerifyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
diff --git a/pvmfw/avb/src/lib.rs b/pvmfw/avb/src/lib.rs
index 9c3fe11..fd68652 100644
--- a/pvmfw/avb/src/lib.rs
+++ b/pvmfw/avb/src/lib.rs
@@ -18,13 +18,10 @@
extern crate alloc;
-mod descriptor;
mod error;
mod ops;
mod partition;
-mod utils;
mod verify;
-pub use descriptor::Digest;
pub use error::PvmfwVerifyError;
-pub use verify::{verify_payload, Capability, DebugLevel, VerifiedBootData};
+pub use verify::{verify_payload, Capability, DebugLevel, Digest, VerifiedBootData};
diff --git a/pvmfw/avb/src/partition.rs b/pvmfw/avb/src/partition.rs
index c05a0ac..02a78c6 100644
--- a/pvmfw/avb/src/partition.rs
+++ b/pvmfw/avb/src/partition.rs
@@ -27,8 +27,6 @@
}
impl PartitionName {
- pub(crate) const NUM_OF_KNOWN_PARTITIONS: usize = 3;
-
const KERNEL_PARTITION_NAME: &'static [u8] = b"boot\0";
const INITRD_NORMAL_PARTITION_NAME: &'static [u8] = b"initrd_normal\0";
const INITRD_DEBUG_PARTITION_NAME: &'static [u8] = b"initrd_debug\0";
diff --git a/pvmfw/avb/src/utils.rs b/pvmfw/avb/src/utils.rs
deleted file mode 100644
index b4f099b..0000000
--- a/pvmfw/avb/src/utils.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2023, 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.
-
-//! Common utility functions.
-
-use avb::{IoError, IoResult};
-
-pub(crate) fn is_not_null<T>(ptr: *const T) -> IoResult<()> {
- if ptr.is_null() {
- Err(IoError::NoSuchValue)
- } else {
- Ok(())
- }
-}
-
-pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> IoResult<usize> {
- num.try_into().map_err(|_| IoError::InvalidValueSize)
-}
-
-pub(crate) fn usize_checked_add(x: usize, y: usize) -> IoResult<usize> {
- x.checked_add(y).ok_or(IoError::InvalidValueSize)
-}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index a85dbbb..2ebe9a1 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -14,17 +14,22 @@
//! This module handles the pvmfw payload verification.
-use crate::descriptor::{Descriptors, Digest};
use crate::ops::{Ops, Payload};
use crate::partition::PartitionName;
use crate::PvmfwVerifyError;
use alloc::vec;
use alloc::vec::Vec;
-use avb::{PartitionData, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData};
+use avb::{
+ Descriptor, DescriptorError, DescriptorResult, HashDescriptor, PartitionData,
+ PropertyDescriptor, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData,
+};
// We use this for the rollback_index field if SlotVerifyData has empty rollback_indexes
const DEFAULT_ROLLBACK_INDEX: u64 = 0;
+/// SHA256 digest type for kernel and initrd.
+pub type Digest = [u8; 32];
+
/// Verified data returned when the payload verification succeeds.
#[derive(Debug, PartialEq, Eq)]
pub struct VerifiedBootData<'a> {
@@ -68,15 +73,21 @@
}
impl Capability {
- const KEY: &'static [u8] = b"com.android.virt.cap";
+ const KEY: &'static str = "com.android.virt.cap";
const REMOTE_ATTEST: &'static [u8] = b"remote_attest";
const SECRETKEEPER_PROTECTION: &'static [u8] = b"secretkeeper_protection";
const SEPARATOR: u8 = b'|';
- fn get_capabilities(property_value: &[u8]) -> Result<Vec<Self>, PvmfwVerifyError> {
+ /// Returns the capabilities indicated in `descriptor`, or error if the descriptor has
+ /// unexpected contents.
+ fn get_capabilities(descriptor: &PropertyDescriptor) -> Result<Vec<Self>, PvmfwVerifyError> {
+ if descriptor.key != Self::KEY {
+ return Err(PvmfwVerifyError::UnknownVbmetaProperty);
+ }
+
let mut res = Vec::new();
- for v in property_value.split(|b| *b == Self::SEPARATOR) {
+ for v in descriptor.value.split(|b| *b == Self::SEPARATOR) {
let cap = match v {
Self::REMOTE_ATTEST => Self::RemoteAttest,
Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
@@ -106,16 +117,6 @@
}
}
-fn verify_vbmeta_has_only_one_hash_descriptor(
- descriptors: &Descriptors,
-) -> SlotVerifyNoDataResult<()> {
- if descriptors.num_hash_descriptor() == 1 {
- Ok(())
- } else {
- Err(SlotVerifyError::InvalidMetadata)
- }
-}
-
fn verify_loaded_partition_has_expected_length(
loaded_partitions: &[PartitionData],
partition_name: PartitionName,
@@ -142,15 +143,91 @@
/// Verifies that the vbmeta contains at most one property descriptor and it indicates the
/// vm type is service VM.
fn verify_property_and_get_capabilities(
- descriptors: &Descriptors,
+ descriptors: &[Descriptor],
) -> Result<Vec<Capability>, PvmfwVerifyError> {
- if !descriptors.has_property_descriptor() {
- return Ok(vec![]);
+ let mut iter = descriptors.iter().filter_map(|d| match d {
+ Descriptor::Property(p) => Some(p),
+ _ => None,
+ });
+
+ let descriptor = match iter.next() {
+ // No property descriptors -> no capabilities.
+ None => return Ok(vec![]),
+ Some(d) => d,
+ };
+
+ // Multiple property descriptors -> error.
+ if iter.next().is_some() {
+ return Err(DescriptorError::InvalidContents.into());
}
- descriptors
- .find_property_value(Capability::KEY)
- .ok_or(PvmfwVerifyError::UnknownVbmetaProperty)
- .and_then(Capability::get_capabilities)
+
+ Capability::get_capabilities(descriptor)
+}
+
+/// Hash descriptors extracted from a vbmeta image.
+///
+/// We always have a kernel hash descriptor and may have initrd normal or debug descriptors.
+struct HashDescriptors<'a> {
+ kernel: &'a HashDescriptor<'a>,
+ initrd_normal: Option<&'a HashDescriptor<'a>>,
+ initrd_debug: Option<&'a HashDescriptor<'a>>,
+}
+
+impl<'a> HashDescriptors<'a> {
+ /// Extracts the hash descriptors from all vbmeta descriptors. Any unexpected hash descriptor
+ /// is an error.
+ fn get(descriptors: &'a [Descriptor<'a>]) -> DescriptorResult<Self> {
+ let mut kernel = None;
+ let mut initrd_normal = None;
+ let mut initrd_debug = None;
+
+ for descriptor in descriptors.iter().filter_map(|d| match d {
+ Descriptor::Hash(h) => Some(h),
+ _ => None,
+ }) {
+ let target = match descriptor
+ .partition_name
+ .as_bytes()
+ .try_into()
+ .map_err(|_| DescriptorError::InvalidContents)?
+ {
+ PartitionName::Kernel => &mut kernel,
+ PartitionName::InitrdNormal => &mut initrd_normal,
+ PartitionName::InitrdDebug => &mut initrd_debug,
+ };
+
+ if target.is_some() {
+ // Duplicates of the same partition name is an error.
+ return Err(DescriptorError::InvalidContents);
+ }
+ target.replace(descriptor);
+ }
+
+ // Kernel is required, the others are optional.
+ Ok(Self {
+ kernel: kernel.ok_or(DescriptorError::InvalidContents)?,
+ initrd_normal,
+ initrd_debug,
+ })
+ }
+
+ /// Returns an error if either initrd descriptor exists.
+ fn verify_no_initrd(&self) -> Result<(), PvmfwVerifyError> {
+ match self.initrd_normal.or(self.initrd_debug) {
+ Some(_) => Err(SlotVerifyError::InvalidMetadata.into()),
+ None => Ok(()),
+ }
+ }
+}
+
+/// Returns a copy of the SHA256 digest in `descriptor`, or error if the sizes don't match.
+fn copy_digest(descriptor: &HashDescriptor) -> SlotVerifyNoDataResult<Digest> {
+ let mut digest = Digest::default();
+ if descriptor.digest.len() != digest.len() {
+ return Err(SlotVerifyError::InvalidMetadata);
+ }
+ digest.clone_from_slice(descriptor.digest);
+ Ok(digest)
}
/// Verifies the given initrd partition, and checks that the resulting contents looks like expected.
@@ -186,15 +263,15 @@
verify_only_one_vbmeta_exists(vbmeta_images)?;
let vbmeta_image = &vbmeta_images[0];
verify_vbmeta_is_from_kernel_partition(vbmeta_image)?;
- let descriptors = Descriptors::from_vbmeta(vbmeta_image)?;
+ let descriptors = vbmeta_image.descriptors()?;
+ let hash_descriptors = HashDescriptors::get(&descriptors)?;
let capabilities = verify_property_and_get_capabilities(&descriptors)?;
- let kernel_descriptor = descriptors.find_hash_descriptor(PartitionName::Kernel)?;
if initrd.is_none() {
- verify_vbmeta_has_only_one_hash_descriptor(&descriptors)?;
+ hash_descriptors.verify_no_initrd()?;
return Ok(VerifiedBootData {
debug_level: DebugLevel::None,
- kernel_digest: *kernel_descriptor.digest,
+ kernel_digest: copy_digest(hash_descriptors.kernel)?,
initrd_digest: None,
public_key: trusted_public_key,
capabilities,
@@ -204,19 +281,19 @@
let initrd = initrd.unwrap();
let mut initrd_ops = Ops::new(&payload);
- let (debug_level, initrd_partition_name) =
+ let (debug_level, initrd_descriptor) =
if verify_initrd(&mut initrd_ops, PartitionName::InitrdNormal, initrd).is_ok() {
- (DebugLevel::None, PartitionName::InitrdNormal)
+ (DebugLevel::None, hash_descriptors.initrd_normal)
} else if verify_initrd(&mut initrd_ops, PartitionName::InitrdDebug, initrd).is_ok() {
- (DebugLevel::Full, PartitionName::InitrdDebug)
+ (DebugLevel::Full, hash_descriptors.initrd_debug)
} else {
return Err(SlotVerifyError::Verification(None).into());
};
- let initrd_descriptor = descriptors.find_hash_descriptor(initrd_partition_name)?;
+ let initrd_descriptor = initrd_descriptor.ok_or(DescriptorError::InvalidContents)?;
Ok(VerifiedBootData {
debug_level,
- kernel_digest: *kernel_descriptor.digest,
- initrd_digest: Some(*initrd_descriptor.digest),
+ kernel_digest: copy_digest(hash_descriptors.kernel)?,
+ initrd_digest: Some(copy_digest(initrd_descriptor)?),
public_key: trusted_public_key,
capabilities,
rollback_index,
diff --git a/pvmfw/avb/tests/api_test.rs b/pvmfw/avb/tests/api_test.rs
index 6dc5a0a..c6f26ac 100644
--- a/pvmfw/avb/tests/api_test.rs
+++ b/pvmfw/avb/tests/api_test.rs
@@ -17,7 +17,7 @@
mod utils;
use anyhow::{anyhow, Result};
-use avb::{IoError, SlotVerifyError};
+use avb::{DescriptorError, SlotVerifyError};
use avb_bindgen::{AvbFooter, AvbVBMetaImageHeader};
use pvmfw_avb::{verify_payload, Capability, DebugLevel, PvmfwVerifyError, VerifiedBootData};
use std::{fs, mem::size_of, ptr};
@@ -88,7 +88,7 @@
&fs::read(TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH)?,
/* initrd= */ None,
&load_trusted_public_key()?,
- PvmfwVerifyError::InvalidDescriptors(IoError::NoSuchPartition),
+ PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
)
}
@@ -98,7 +98,7 @@
&fs::read(TEST_IMG_WITH_INITRD_AND_NON_INITRD_DESC_PATH)?,
&load_latest_initrd_normal()?,
&load_trusted_public_key()?,
- PvmfwVerifyError::InvalidDescriptors(IoError::NoSuchPartition),
+ PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
)
}
@@ -142,7 +142,7 @@
&fs::read(TEST_IMG_WITH_MULTIPLE_PROPS_PATH)?,
/* initrd= */ None,
&load_trusted_public_key()?,
- PvmfwVerifyError::InvalidDescriptors(IoError::Io),
+ PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
)
}
diff --git a/pvmfw/src/fdt.rs b/pvmfw/src/fdt.rs
index 2ea4599..d2aad61 100644
--- a/pvmfw/src/fdt.rs
+++ b/pvmfw/src/fdt.rs
@@ -47,6 +47,7 @@
use vmbase::memory::SIZE_4KB;
use vmbase::util::flatten;
use vmbase::util::RangeExt as _;
+use zerocopy::AsBytes as _;
/// An enumeration of errors that can occur during the FDT validation.
#[derive(Clone, Debug)]
@@ -164,10 +165,11 @@
}
fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
- let size = memory_range.len() as u64;
+ let addr = u64::try_from(MEM_START).unwrap();
+ let size = u64::try_from(memory_range.len()).unwrap();
fdt.node_mut(cstr!("/memory"))?
.ok_or(FdtError::NotFound)?
- .setprop_inplace(cstr!("reg"), flatten(&[MEM_START.to_be_bytes(), size.to_be_bytes()]))
+ .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
}
/// Read the number of CPUs from DT
@@ -486,11 +488,17 @@
}
fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
- let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
- for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
+ let mut addrs = ArrayVec::new();
+
+ let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
+ for node in serial_nodes.by_ref().take(addrs.capacity()) {
let reg = node.first_reg()?;
addrs.push(reg.addr);
}
+ if serial_nodes.next().is_some() {
+ warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
+ }
+
Ok(SerialInfo { addrs })
}
@@ -581,14 +589,9 @@
range1.addr = addr - size;
range1.size = Some(size);
- let range0 = range0.to_cells();
- let range1 = range1.to_cells();
- let value = [
- range0.0, // addr
- range0.1.unwrap(), //size
- range1.0, // addr
- range1.1.unwrap(), //size
- ];
+ let (addr0, size0) = range0.to_cells();
+ let (addr1, size1) = range1.to_cells();
+ let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
let mut node =
fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
@@ -612,17 +615,11 @@
*v = v.to_be();
}
- // SAFETY: array size is the same
- let value = unsafe {
- core::mem::transmute::<
- [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
- [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
- >(value.into_inner())
- };
+ let value = value.into_inner();
let mut node =
fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
- node.setprop_inplace(cstr!("interrupts"), value.as_slice())
+ node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
}
#[derive(Debug)]
diff --git a/rialto/tests/test.rs b/rialto/tests/test.rs
index c918db5..1302bcd 100644
--- a/rialto/tests/test.rs
+++ b/rialto/tests/test.rs
@@ -287,7 +287,9 @@
fn start_service_vm(vm_type: VmType) -> Result<ServiceVm> {
android_logger::init_once(
- android_logger::Config::default().with_tag("rialto").with_min_level(log::Level::Debug),
+ android_logger::Config::default()
+ .with_tag("rialto")
+ .with_max_level(log::LevelFilter::Debug),
);
// Redirect panic messages to logcat.
panic::set_hook(Box::new(|panic_info| {
diff --git a/service_vm/client_vm_csr/Android.bp b/service_vm/client_vm_csr/Android.bp
index 8d738d8..e2ac573 100644
--- a/service_vm/client_vm_csr/Android.bp
+++ b/service_vm/client_vm_csr/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/service_vm/comm/Android.bp b/service_vm/comm/Android.bp
index bf923a4..23ff202 100644
--- a/service_vm/comm/Android.bp
+++ b/service_vm/comm/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/service_vm/fake_chain/Android.bp b/service_vm/fake_chain/Android.bp
index 2bc7b4e..7735aac 100644
--- a/service_vm/fake_chain/Android.bp
+++ b/service_vm/fake_chain/Android.bp
@@ -13,6 +13,7 @@
// limitations under the License.
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/service_vm/kernel/Android.bp b/service_vm/kernel/Android.bp
index 79158e6..3817495 100644
--- a/service_vm/kernel/Android.bp
+++ b/service_vm/kernel/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/service_vm/manager/Android.bp b/service_vm/manager/Android.bp
index 6469212..6e186a5 100644
--- a/service_vm/manager/Android.bp
+++ b/service_vm/manager/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/service_vm/requests/Android.bp b/service_vm/requests/Android.bp
index 57da012..5a49207 100644
--- a/service_vm/requests/Android.bp
+++ b/service_vm/requests/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/service_vm/test_apk/Android.bp b/service_vm/test_apk/Android.bp
index 4da3f81..681f4e8 100644
--- a/service_vm/test_apk/Android.bp
+++ b/service_vm/test_apk/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/service_vm/test_apk/src/main.rs b/service_vm/test_apk/src/main.rs
index ba65aca..df60325 100644
--- a/service_vm/test_apk/src/main.rs
+++ b/service_vm/test_apk/src/main.rs
@@ -36,7 +36,7 @@
android_logger::init_once(
android_logger::Config::default()
.with_tag("service_vm_client")
- .with_min_level(log::Level::Debug),
+ .with_max_level(log::LevelFilter::Debug),
);
// Redirect panic messages to logcat.
panic::set_hook(Box::new(|panic_info| {
diff --git a/tests/aidl/Android.bp b/tests/aidl/Android.bp
index ed4e8ff..7e22646 100644
--- a/tests/aidl/Android.bp
+++ b/tests/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/benchmark/Android.bp b/tests/benchmark/Android.bp
index 657241c..31fe0f6 100644
--- a/tests/benchmark/Android.bp
+++ b/tests/benchmark/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
index e0de9b3..b9faa85 100644
--- a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
+++ b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
@@ -278,9 +278,7 @@
@Test
public void testMicrodroidDebugBootTime_withVendorPartition() throws Exception {
- assume().withMessage(
- "Cuttlefish doesn't support device tree under"
- + " /sys/firmware/devicetree/base")
+ assume().withMessage("Cuttlefish doesn't support device tree under" + " /proc/device-tree")
.that(isCuttlefish())
.isFalse();
// TODO(b/317567210): Boots fails with vendor partition in HWASAN enabled microdroid
diff --git a/tests/benchmark/src/jni/Android.bp b/tests/benchmark/src/jni/Android.bp
index e1bc8b0..c2e1b7c 100644
--- a/tests/benchmark/src/jni/Android.bp
+++ b/tests/benchmark/src/jni/Android.bp
@@ -1,10 +1,11 @@
-package{
- default_applicable_licenses : ["Android-Apache-2.0"],
+package {
+ default_team: "trendy_team_virtualization",
+ default_applicable_licenses: ["Android-Apache-2.0"],
}
cc_library_shared {
name: "libiovsock_host_jni",
- srcs: [ "io_vsock_host_jni.cpp" ],
+ srcs: ["io_vsock_host_jni.cpp"],
header_libs: ["jni_headers"],
shared_libs: ["libbase"],
-}
\ No newline at end of file
+}
diff --git a/tests/benchmark_hostside/Android.bp b/tests/benchmark_hostside/Android.bp
index b613a8a..8727b05 100644
--- a/tests/benchmark_hostside/Android.bp
+++ b/tests/benchmark_hostside/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/benchmark_hostside/java/android/avf/test/AVFHostTestCase.java b/tests/benchmark_hostside/java/android/avf/test/AVFHostTestCase.java
index b176cfc..f01a76b 100644
--- a/tests/benchmark_hostside/java/android/avf/test/AVFHostTestCase.java
+++ b/tests/benchmark_hostside/java/android/avf/test/AVFHostTestCase.java
@@ -231,7 +231,7 @@
android.tryRun("rm", "-rf", MicrodroidHostTestCaseBase.TEST_ROOT);
// Donate 80% of the available device memory to the VM
- final String configPath = "assets/vm_config.json";
+ final String configPath = "assets/microdroid/vm_config.json";
final int vm_mem_mb = getFreeMemoryInfoMb(android) * 80 / 100;
ITestDevice microdroidDevice =
MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
diff --git a/tests/helper/Android.bp b/tests/helper/Android.bp
index 614c70c..9223391 100644
--- a/tests/helper/Android.bp
+++ b/tests/helper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/hostside/Android.bp b/tests/hostside/Android.bp
index e3d9cbe..2cfaffa 100644
--- a/tests/hostside/Android.bp
+++ b/tests/hostside/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/hostside/helper/Android.bp b/tests/hostside/helper/Android.bp
index 75553d0..890e14a 100644
--- a/tests/hostside/helper/Android.bp
+++ b/tests/hostside/helper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
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 848b43b..9e19b7d 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
@@ -33,12 +33,17 @@
import com.android.tradefed.util.CommandResult;
import com.android.tradefed.util.RunUtil;
+import org.json.JSONArray;
+
import java.io.File;
import java.io.FileNotFoundException;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
+import java.util.List;
import java.util.Set;
+import java.util.stream.Collectors;
public abstract class MicrodroidHostTestCaseBase extends BaseHostJUnit4Test {
protected static final String TEST_ROOT = "/data/local/tmp/virt/";
@@ -164,4 +169,35 @@
.that(pathLine).startsWith("package:");
return pathLine.substring("package:".length());
}
+
+ public List<String> parseStringArrayFieldsFromVmInfo(String header) throws Exception {
+ CommandRunner android = new CommandRunner(getDevice());
+ String result = android.run("/apex/com.android.virt/bin/vm", "info");
+ List<String> ret = new ArrayList<>();
+ for (String line : result.split("\n")) {
+ if (!line.startsWith(header)) continue;
+
+ JSONArray jsonArray = new JSONArray(line.substring(header.length()));
+ for (int i = 0; i < jsonArray.length(); i++) {
+ ret.add(jsonArray.getString(i));
+ }
+ break;
+ }
+ return ret;
+ }
+
+ public List<String> getAssignableDevices() throws Exception {
+ return parseStringArrayFieldsFromVmInfo("Assignable devices: ");
+ }
+
+ public List<String> getSupportedOSList() throws Exception {
+ return parseStringArrayFieldsFromVmInfo("Available OS list: ");
+ }
+
+ public List<String> getSupportedGKIVersions() throws Exception {
+ return getSupportedOSList().stream()
+ .filter(os -> os.startsWith("microdroid_gki-"))
+ .map(os -> os.replaceFirst("^microdroid_gki-", ""))
+ .collect(Collectors.toList());
+ }
}
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 21abdaa..7a5d69b 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -938,7 +938,7 @@
assumeFalse("Unlocked devices may have AVF debug policy", lockProp.equals("orange"));
// Test that AVF debug policy doesn't exist.
- boolean hasDebugPolicy = device.doesFileExist("/sys/firmware/devicetree/base/avf");
+ boolean hasDebugPolicy = device.doesFileExist("/proc/device-tree/avf");
assertThat(hasDebugPolicy).isFalse();
}
@@ -1075,37 +1075,6 @@
&& device.doesFileExist("/sys/bus/platform/drivers/vfio-platform"));
}
- private List<String> parseStringArrayFieldsFromVmInfo(String header) throws Exception {
- CommandRunner android = new CommandRunner(getDevice());
- String result = android.run("/apex/com.android.virt/bin/vm", "info");
- List<String> ret = new ArrayList<>();
- for (String line : result.split("\n")) {
- if (!line.startsWith(header)) continue;
-
- JSONArray jsonArray = new JSONArray(line.substring(header.length()));
- for (int i = 0; i < jsonArray.length(); i++) {
- ret.add(jsonArray.getString(i));
- }
- break;
- }
- return ret;
- }
-
- private List<String> getAssignableDevices() throws Exception {
- return parseStringArrayFieldsFromVmInfo("Assignable devices: ");
- }
-
- private List<String> getSupportedOSList() throws Exception {
- return parseStringArrayFieldsFromVmInfo("Available OS list: ");
- }
-
- private List<String> getSupportedGKIVersions() throws Exception {
- return getSupportedOSList().stream()
- .filter(os -> os.startsWith("microdroid_gki-"))
- .map(os -> os.replaceFirst("^microdroid_gki-", ""))
- .collect(Collectors.toList());
- }
-
private TestDevice getAndroidDevice() {
TestDevice androidDevice = (TestDevice) getDevice();
assertThat(androidDevice).isNotNull();
diff --git a/tests/no_avf/Android.bp b/tests/no_avf/Android.bp
index 22d099e..cdc9e9f 100644
--- a/tests/no_avf/Android.bp
+++ b/tests/no_avf/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/pvmfw/Android.bp b/tests/pvmfw/Android.bp
index c12f67a..03dcc35 100644
--- a/tests/pvmfw/Android.bp
+++ b/tests/pvmfw/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/pvmfw/helper/Android.bp b/tests/pvmfw/helper/Android.bp
index 1b96842..7258c68 100644
--- a/tests/pvmfw/helper/Android.bp
+++ b/tests/pvmfw/helper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/pvmfw/tools/Android.bp b/tests/pvmfw/tools/Android.bp
index 7bd3ef5..e4a31d5 100644
--- a/tests/pvmfw/tools/Android.bp
+++ b/tests/pvmfw/tools/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/testapk/Android.bp b/tests/testapk/Android.bp
index 6a30b1c..10bbfb4 100644
--- a/tests/testapk/Android.bp
+++ b/tests/testapk/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
index 33d41ab..df6280d 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -73,6 +73,7 @@
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
@@ -543,6 +544,7 @@
assertThrows(NullPointerException.class, () -> builder.setApkPath(null));
assertThrows(NullPointerException.class, () -> builder.setPayloadConfigPath(null));
assertThrows(NullPointerException.class, () -> builder.setPayloadBinaryName(null));
+ assertThrows(NullPointerException.class, () -> builder.setVendorDiskImage(null));
assertThrows(NullPointerException.class, () -> builder.setOs(null));
// Individual property checks.
@@ -2105,8 +2107,7 @@
public void configuringVendorDiskImageRequiresCustomPermission() throws Exception {
assumeSupportedDevice();
assumeFalse(
- "Cuttlefish doesn't support device tree under /sys/firmware/devicetree/base",
- isCuttlefish());
+ "Cuttlefish doesn't support device tree under /proc/device-tree", isCuttlefish());
// TODO(b/317567210): Boots fails with vendor partition in HWASAN enabled microdroid
// after introducing verification based on DT and fstab in microdroid vendor partition.
assumeFalse(
@@ -2132,20 +2133,19 @@
.contains("android.permission.USE_CUSTOM_VIRTUAL_MACHINE permission");
}
+ // TODO(b/323768068): Enable this test when we can inject vendor hashkey for test purpose.
+ // After introducing VM reference DT, non-pVM cannot trust test_microdroid_vendor_image.img
+ // as well, because it doesn't pass the hashtree digest of testing image into VM.
+ @Ignore
@Test
public void bootsWithVendorPartition() throws Exception {
assumeSupportedDevice();
assumeFalse(
- "Cuttlefish doesn't support device tree under /sys/firmware/devicetree/base",
- isCuttlefish());
+ "Cuttlefish doesn't support device tree under /proc/device-tree", isCuttlefish());
// TODO(b/317567210): Boots fails with vendor partition in HWASAN enabled microdroid
// after introducing verification based on DT and fstab in microdroid vendor partition.
assumeFalse(
"Boot with vendor partition is failing in HWASAN enabled Microdroid.", isHwasan());
- assumeFalse(
- "Skip test for protected VM, pvmfw config data doesn't contain any information of"
- + " test images, such as root digest.",
- isProtectedVm());
assumeFeatureEnabled(VirtualMachineManager.FEATURE_VENDOR_MODULES);
grantPermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
@@ -2177,8 +2177,7 @@
public void creationFailsWithUnsignedVendorPartition() throws Exception {
assumeSupportedDevice();
assumeFalse(
- "Cuttlefish doesn't support device tree under /sys/firmware/devicetree/base",
- isCuttlefish());
+ "Cuttlefish doesn't support device tree under /proc/device-tree", isCuttlefish());
// TODO(b/317567210): Boots fails with vendor partition in HWASAN enabled microdroid
// after introducing verification based on DT and fstab in microdroid vendor partition.
assumeFalse(
@@ -2197,8 +2196,9 @@
.build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_boot_with_unsigned_vendor", config);
- assertThrowsVmExceptionContaining(
- () -> vm.run(), "Failed to get vbmeta from microdroid-vendor.img");
+ BootResult bootResult = tryBootVm(TAG, "test_boot_with_unsigned_vendor");
+ assertThat(bootResult.payloadStarted).isFalse();
+ assertThat(bootResult.deathReason).isEqualTo(VirtualMachineCallback.STOP_REASON_REBOOT);
}
@Test
diff --git a/tests/vendor_images/Android.bp b/tests/vendor_images/Android.bp
index 26dbc01..ecf0bb4 100644
--- a/tests/vendor_images/Android.bp
+++ b/tests/vendor_images/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/vmshareapp/Android.bp b/tests/vmshareapp/Android.bp
index 5f6dc57..d4113bf 100644
--- a/tests/vmshareapp/Android.bp
+++ b/tests/vmshareapp/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/vmshareapp/aidl/Android.bp b/tests/vmshareapp/aidl/Android.bp
index df4a4b4..09e3405 100644
--- a/tests/vmshareapp/aidl/Android.bp
+++ b/tests/vmshareapp/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/virtualizationmanager/Android.bp b/virtualizationmanager/Android.bp
index f58e999..39d296f 100644
--- a/virtualizationmanager/Android.bp
+++ b/virtualizationmanager/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
@@ -36,10 +37,10 @@
"libbase_rust",
"libbinder_rs",
"libclap",
+ "libcstr",
"libcommand_fds",
"libdisk",
"libglob",
- "libhex",
"libhypervisor_props",
"liblazy_static",
"liblibc",
@@ -60,12 +61,12 @@
"libshared_child",
"libstatslog_virtualization_rust",
"libtombstoned_client_rust",
- "libvbmeta_rust",
"libvm_control",
"libvmconfig",
"libzip",
"libvsock",
"liblibfdt",
+ "libfsfdt",
// TODO(b/202115393) stabilize the interface
"packagemanager_aidl-rust",
],
diff --git a/virtualizationmanager/fsfdt/Android.bp b/virtualizationmanager/fsfdt/Android.bp
new file mode 100644
index 0000000..0aa2ef0
--- /dev/null
+++ b/virtualizationmanager/fsfdt/Android.bp
@@ -0,0 +1,33 @@
+package {
+ default_team: "trendy_team_virtualization",
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_binary {
+ name: "fsfdt",
+ crate_name: "fsfdt",
+ defaults: ["avf_build_flags_rust"],
+ edition: "2021",
+ srcs: ["src/main.rs"],
+ prefer_rlib: true,
+ rustlibs: [
+ "libanyhow",
+ "libclap",
+ "libfsfdt",
+ "liblibfdt",
+ ],
+}
+
+rust_library_rlib {
+ name: "libfsfdt",
+ crate_name: "fsfdt",
+ defaults: ["avf_build_flags_rust"],
+ edition: "2021",
+ srcs: ["src/lib.rs"],
+ prefer_rlib: true,
+ rustlibs: [
+ "liblibfdt",
+ "libanyhow",
+ ],
+ apex_available: ["com.android.virt"],
+}
diff --git a/virtualizationmanager/fsfdt/src/lib.rs b/virtualizationmanager/fsfdt/src/lib.rs
new file mode 100644
index 0000000..a2ca519
--- /dev/null
+++ b/virtualizationmanager/fsfdt/src/lib.rs
@@ -0,0 +1,100 @@
+// 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.
+
+//! Implements converting file system to FDT blob
+
+use anyhow::{anyhow, Context, Result};
+use libfdt::Fdt;
+use std::ffi::{CStr, CString};
+use std::fs;
+use std::os::unix::ffi::OsStrExt;
+use std::path::Path;
+
+/// Trait for Fdt's file system support
+pub trait FsFdt<'a> {
+ /// Creates a Fdt from /proc/device-tree style directory by wrapping a mutable slice
+ fn from_fs(fs_path: &Path, fdt_buffer: &'a mut [u8]) -> Result<&'a mut Self>;
+
+ /// Appends a FDT from /proc/device-tree style directory at the given node path
+ fn append(&mut self, fdt_node_path: &CStr, fs_path: &Path) -> Result<()>;
+}
+
+impl<'a> FsFdt<'a> for Fdt {
+ fn from_fs(fs_path: &Path, fdt_buffer: &'a mut [u8]) -> Result<&'a mut Fdt> {
+ let fdt = Fdt::create_empty_tree(fdt_buffer)
+ .map_err(|e| anyhow!("Failed to create FDT, {e:?}"))?;
+
+ fdt.append(&CString::new("").unwrap(), fs_path)?;
+
+ Ok(fdt)
+ }
+
+ fn append(&mut self, fdt_node_path: &CStr, fs_path: &Path) -> Result<()> {
+ // Recursively traverse fs_path with DFS algorithm.
+ let mut stack = vec![fs_path.to_path_buf()];
+ while let Some(dir_path) = stack.pop() {
+ let relative_path = dir_path
+ .strip_prefix(fs_path)
+ .context("Internal error. Path does not have expected prefix")?
+ .as_os_str();
+ let fdt_path = CString::from_vec_with_nul(
+ [fdt_node_path.to_bytes(), b"/", relative_path.as_bytes(), b"\0"].concat(),
+ )
+ .context("Internal error. Path is not a valid Fdt path")?;
+
+ let mut node = self
+ .node_mut(&fdt_path)
+ .map_err(|e| anyhow!("Failed to write FDT, {e:?}"))?
+ .ok_or_else(|| anyhow!("Failed to find {fdt_node_path:?} in FDT"))?;
+
+ let mut subnode_names = vec![];
+ let entries =
+ fs::read_dir(&dir_path).with_context(|| format!("Failed to read {dir_path:?}"))?;
+ for entry in entries {
+ let entry =
+ entry.with_context(|| format!("Failed to get an entry in {dir_path:?}"))?;
+ let entry_type =
+ entry.file_type().with_context(|| "Unsupported entry type, {entry:?}")?;
+ let entry_name = entry.file_name(); // binding to keep name below.
+ if !entry_name.is_ascii() {
+ return Err(anyhow!("Unsupported entry name for FDT, {entry:?}"));
+ }
+ // Safe to unwrap because validated as an ascii string above.
+ let name = CString::new(entry_name.as_bytes()).unwrap();
+ if entry_type.is_dir() {
+ stack.push(entry.path());
+ subnode_names.push(name);
+ } else if entry_type.is_file() {
+ let value = fs::read(&entry.path())?;
+
+ node.setprop(&name, &value)
+ .map_err(|e| anyhow!("Failed to set FDT property, {e:?}"))?;
+ } else {
+ return Err(anyhow!(
+ "Failed to handle {entry:?}. FDT only uses file or directory"
+ ));
+ }
+ }
+ // Note: sort() is necessary to prevent FdtError::Exists from add_subnodes().
+ // FDT library may omit address in node name when comparing their name, so sort to add
+ // node without address first.
+ subnode_names.sort();
+ let subnode_names_c_str: Vec<_> = subnode_names.iter().map(|x| x.as_c_str()).collect();
+ node.add_subnodes(&subnode_names_c_str)
+ .map_err(|e| anyhow!("Failed to add node, {e:?}"))?;
+ }
+
+ Ok(())
+ }
+}
diff --git a/virtualizationmanager/fsfdt/src/main.rs b/virtualizationmanager/fsfdt/src/main.rs
new file mode 100644
index 0000000..2fe71e7
--- /dev/null
+++ b/virtualizationmanager/fsfdt/src/main.rs
@@ -0,0 +1,42 @@
+// 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.
+
+//! CLI for converting file system to FDT
+
+use clap::Parser;
+use fsfdt::FsFdt;
+use libfdt::Fdt;
+use std::fs;
+use std::path::PathBuf;
+
+const FDT_MAX_SIZE: usize = 1_000_000_usize;
+
+/// Option parser
+#[derive(Parser, Debug)]
+struct Opt {
+ /// File system path (directory path) to parse from
+ fs_path: PathBuf,
+
+ /// FDT file path for writing
+ fdt_file_path: PathBuf,
+}
+
+fn main() {
+ let opt = Opt::parse();
+
+ let mut data = vec![0_u8; FDT_MAX_SIZE];
+ let fdt = Fdt::from_fs(&opt.fs_path, &mut data).unwrap();
+ fdt.pack().unwrap();
+ fs::write(&opt.fdt_file_path, fdt.as_slice()).unwrap();
+}
diff --git a/virtualizationmanager/src/aidl.rs b/virtualizationmanager/src/aidl.rs
index 2603e77..602c670 100644
--- a/virtualizationmanager/src/aidl.rs
+++ b/virtualizationmanager/src/aidl.rs
@@ -15,13 +15,13 @@
//! Implementation of the AIDL interface of the VirtualizationService.
use crate::{get_calling_pid, get_calling_uid};
-use crate::atom::{
- write_vm_booted_stats, write_vm_creation_stats};
+use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
use crate::composite::make_composite_image;
use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
use crate::debug_config::DebugConfig;
use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
use crate::selinux::{getfilecon, SeContext};
+use crate::reference_dt;
use android_os_permissions_aidl::aidl::android::os::IPermissionController;
use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Certificate::Certificate,
@@ -71,25 +71,23 @@
use disk::QcowFile;
use glob::glob;
use lazy_static::lazy_static;
-use libfdt::Fdt;
use log::{debug, error, info, warn};
-use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
+use microdroid_payload_config::{ApkConfig, OsConfig, Task, TaskType, VmPayloadConfig};
use nix::unistd::pipe;
use rpcbinder::RpcServer;
use rustutils::system_properties;
use semver::VersionReq;
use std::collections::HashSet;
use std::convert::TryInto;
-use std::ffi::{CStr, CString};
+use std::ffi::CStr;
use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
-use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
+use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
use std::iter;
use std::num::{NonZeroU16, NonZeroU32};
use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::os::unix::raw::pid_t;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, Weak};
-use vbmeta::VbMetaImage;
use vmconfig::VmConfig;
use vsock::VsockStream;
use zip::ZipArchive;
@@ -117,9 +115,6 @@
const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
-/// Rough size for storing root digest of vendor hash descriptor into DTBO.
-const EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE: usize = 10000;
-
/// crosvm requires all partitions to be a multiple of 4KiB.
const PARTITION_GRANULARITY_BYTES: u64 = 4096;
@@ -159,6 +154,9 @@
// We will anyway overwrite the file to the v4signature generated from input_fd.
}
+ output
+ .seek(SeekFrom::Start(0))
+ .context("failed to move cursor to start on the idsig output")?;
output.set_len(0).context("failed to set_len on the idsig output")?;
sig.write_into(&mut output).context("failed to write idsig")?;
Ok(())
@@ -243,9 +241,14 @@
.with_context(|| format!("Invalid size: {}", size_bytes))
.or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
- let image = clone_file(image_fd)?;
+ let mut image = clone_file(image_fd)?;
// initialize the file. Any data in the file will be erased.
+ image
+ .seek(SeekFrom::Start(0))
+ .context("failed to move cursor to start")
+ .or_service_specific_exception(-1)?;
image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
+
let mut part = QcowFile::new(image, size_bytes)
.context("Failed to create QCOW2 image")
.or_service_specific_exception(-1)?;
@@ -362,21 +365,7 @@
// Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
- let is_custom = match config {
- VirtualMachineConfig::RawConfig(_) => true,
- VirtualMachineConfig::AppConfig(config) => {
- // Some features are reserved for platform apps only, even when using
- // VirtualMachineAppConfig. Almost all of these features are grouped in the
- // CustomConfig struct:
- // - controlling CPUs;
- // - specifying a config file in the APK; (this one is not part of CustomConfig)
- // - gdbPort is set, meaning that crosvm will start a gdb server;
- // - using anything other than the default kernel;
- // - specifying devices to be assigned.
- config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
- }
- };
- if is_custom {
+ if is_custom_config(config) {
check_use_custom_virtual_machine()?;
}
@@ -387,25 +376,12 @@
check_gdb_allowed(config)?;
}
- let vendor_hashtree_descriptor_root_digest =
- extract_vendor_hashtree_descriptor_root_digest(config)
- .context("Failed to extract root digest of vendor")
- .or_service_specific_exception(-1)?;
- let dtbo_vendor = if let Some(vendor_hashtree_descriptor_root_digest) =
- vendor_hashtree_descriptor_root_digest
- {
- let root_digest_hex = hex::encode(vendor_hashtree_descriptor_root_digest);
- let dtbo_for_vendor_image = temporary_directory.join("dtbo_vendor");
- create_dtbo_for_vendor_image(root_digest_hex.as_bytes(), &dtbo_for_vendor_image)
- .context("Failed to write root digest of vendor")
- .or_service_specific_exception(-1)?;
- let file = File::open(dtbo_for_vendor_image)
- .context("Failed to open dtbo_vendor")
- .or_service_specific_exception(-1)?;
- Some(file)
- } else {
- None
- };
+ let reference_dt = reference_dt::parse_reference_dt(&temporary_directory)
+ .context("Failed to create VM reference DT")
+ .or_service_specific_exception(-1)?;
+ if reference_dt.is_none() {
+ warn!("VM reference DT doesn't exist");
+ }
let debug_level = match config {
VirtualMachineConfig::AppConfig(config) => config.debugLevel,
@@ -522,7 +498,7 @@
.getDtboFile()?
.as_ref()
.try_clone()
- .context("Failed to create File from ParcelFileDescriptor")
+ .context("Failed to create VM DTBO from ParcelFileDescriptor")
.or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
);
(devices, Some(dtbo_file))
@@ -555,7 +531,7 @@
gdb_port,
vfio_devices,
dtbo,
- dtbo_vendor,
+ reference_dt,
};
let instance = Arc::new(
VmInstance::new(
@@ -574,78 +550,33 @@
}
}
-fn extract_vendor_hashtree_descriptor_root_digest(
- config: &VirtualMachineConfig,
-) -> Result<Option<Vec<u8>>> {
- let VirtualMachineConfig::AppConfig(config) = config else {
- return Ok(None);
- };
- let Some(custom_config) = &config.customConfig else {
- return Ok(None);
- };
- let Some(file) = custom_config.vendorImage.as_ref() else {
- return Ok(None);
- };
-
- let file = clone_file(file)?;
- let size = file.metadata().context("Failed to get metadata from microdroid-vendor.img")?.len();
- let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
- .context("Failed to get vbmeta from microdroid-vendor.img")?;
-
- for descriptor in vbmeta.descriptors()?.iter() {
- if let vbmeta::Descriptor::Hashtree(_) = descriptor {
- return Ok(Some(descriptor.to_hashtree()?.root_digest().to_vec()));
+/// Returns whether a VM config represents a "custom" virtual machine, which requires the
+/// USE_CUSTOM_VIRTUAL_MACHINE.
+fn is_custom_config(config: &VirtualMachineConfig) -> bool {
+ match config {
+ // Any raw (non-Microdroid) VM is considered custom.
+ VirtualMachineConfig::RawConfig(_) => true,
+ VirtualMachineConfig::AppConfig(config) => {
+ // Some features are reserved for platform apps only, even when using
+ // VirtualMachineAppConfig. Almost all of these features are grouped in the
+ // CustomConfig struct:
+ // - controlling CPUs;
+ // - gdbPort is set, meaning that crosvm will start a gdb server;
+ // - using anything other than the default kernel;
+ // - specifying devices to be assigned.
+ if config.customConfig.is_some() {
+ true
+ } else {
+ // Additional custom features not included in CustomConfig:
+ // - specifying a config file;
+ // - specifying extra APKs.
+ match &config.payload {
+ Payload::ConfigPath(_) => true,
+ Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
+ }
+ }
}
}
- Err(anyhow!("No root digest is extracted from microdroid-vendor.img"))
-}
-
-fn create_dtbo_for_vendor_image(
- vendor_hashtree_descriptor_root_digest: &[u8],
- dtbo: &PathBuf,
-) -> Result<()> {
- if dtbo.exists() {
- return Err(anyhow!("DTBO file already exists"));
- }
-
- let mut buf = vec![0; EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE];
- let fdt = Fdt::create_empty_tree(buf.as_mut_slice())
- .map_err(|e| anyhow!("Failed to create FDT: {:?}", e))?;
- let mut root = fdt.root_mut().map_err(|e| anyhow!("Failed to get root node: {:?}", e))?;
-
- let fragment_node_name = CString::new("fragment@0")?;
- let mut fragment_node = root
- .add_subnode(fragment_node_name.as_c_str())
- .map_err(|e| anyhow!("Failed to create fragment node: {:?}", e))?;
- let target_path_prop_name = CString::new("target-path")?;
- let target_path = CString::new("/")?;
- fragment_node
- .setprop(target_path_prop_name.as_c_str(), target_path.to_bytes_with_nul())
- .map_err(|e| anyhow!("Failed to set target-path: {:?}", e))?;
- let overlay_node_name = CString::new("__overlay__")?;
- let mut overlay_node = fragment_node
- .add_subnode(overlay_node_name.as_c_str())
- .map_err(|e| anyhow!("Failed to create overlay node: {:?}", e))?;
-
- let avf_node_name = CString::new("avf")?;
- let mut avf_node = overlay_node
- .add_subnode(avf_node_name.as_c_str())
- .map_err(|e| anyhow!("Failed to create avf node: {:?}", e))?;
- let vendor_hashtree_descriptor_root_digest_name =
- CString::new("vendor_hashtree_descriptor_root_digest")?;
- avf_node
- .setprop(
- vendor_hashtree_descriptor_root_digest_name.as_c_str(),
- vendor_hashtree_descriptor_root_digest,
- )
- .map_err(|e| {
- anyhow!("Failed to set avf/vendor_hashtree_descriptor_root_digest: {:?}", e)
- })?;
-
- fdt.pack().map_err(|e| anyhow!("Failed to pack fdt: {:?}", e))?;
- let mut file = File::create(dtbo)?;
- file.write_all(fdt.as_slice())?;
- Ok(file.flush()?)
}
fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
@@ -777,12 +708,28 @@
None
};
- let vm_payload_config = match &config.payload {
+ let vm_payload_config;
+ let extra_apk_files: Vec<_>;
+ match &config.payload {
Payload::ConfigPath(config_path) => {
- load_vm_payload_config_from_file(&apk_file, config_path.as_str())
- .with_context(|| format!("Couldn't read config from {}", config_path))?
+ vm_payload_config =
+ load_vm_payload_config_from_file(&apk_file, config_path.as_str())
+ .with_context(|| format!("Couldn't read config from {}", config_path))?;
+ extra_apk_files = vm_payload_config
+ .extra_apks
+ .iter()
+ .enumerate()
+ .map(|(i, apk)| {
+ File::open(PathBuf::from(&apk.path))
+ .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
+ })
+ .collect::<Result<_>>()?;
}
- Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
+ Payload::PayloadConfig(payload_config) => {
+ vm_payload_config = create_vm_payload_config(payload_config)?;
+ extra_apk_files =
+ payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
+ }
};
// For now, the only supported OS is Microdroid and Microdroid GKI
@@ -830,6 +777,7 @@
temporary_directory,
apk_file,
idsig_file,
+ extra_apk_files,
&vm_payload_config,
&mut vm_config,
)?;
@@ -857,11 +805,17 @@
let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
let name = payload_config.osName.clone();
+
+ // The VM only cares about how many there are, these names are actually ignored.
+ let extra_apk_count = payload_config.extraApks.len();
+ let extra_apks =
+ (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
+
Ok(VmPayloadConfig {
os: OsConfig { name },
task: Some(task),
apexes: vec![],
- extra_apks: vec![],
+ extra_apks,
prefer_staged: false,
export_tombstones: None,
enable_authfs: false,
@@ -1276,6 +1230,16 @@
Ok(())
}
+fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
+ let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
+ let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
+ if !payload_config.extraApks.is_empty() {
+ return Err(anyhow!("multi-tenant feature is disabled"))
+ .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
+ }
+ Ok(())
+}
+
fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
if !cfg!(vendor_modules) {
check_no_vendor_modules(config)?;
@@ -1283,6 +1247,9 @@
if !cfg!(device_assignment) {
check_no_devices(config)?;
}
+ if !cfg!(multi_tenant) {
+ check_no_extra_apks(config)?;
+ }
Ok(())
}
@@ -1545,6 +1512,40 @@
}
#[test]
+ fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
+ use std::io::Read;
+
+ // Pick any APK
+ let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
+ let idsig_empty = tempfile::tempfile().unwrap();
+ let mut idsig_invalid = tempfile::tempfile().unwrap();
+ idsig_invalid.write_all(b"Oops")?;
+
+ // Create new idsig
+ create_or_update_idsig_file(
+ &ParcelFileDescriptor::new(apk.try_clone()?),
+ &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
+ )?;
+ apk.rewind()?;
+
+ // Update idsig_invalid
+ create_or_update_idsig_file(
+ &ParcelFileDescriptor::new(apk.try_clone()?),
+ &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
+ )?;
+
+ // Ensure the 2 idsig files have same size!
+ assert!(
+ idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
+ "idsig files differ in size"
+ );
+ // Ensure the 2 idsig files have same content!
+ for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
+ assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
+ }
+ Ok(())
+ }
+ #[test]
fn test_append_kernel_param_first_param() {
let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
append_kernel_param("foo=1", &mut vm_config);
@@ -1559,65 +1560,6 @@
assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
}
- #[test]
- fn test_create_dtbo_for_vendor_image() -> Result<()> {
- let vendor_hashtree_descriptor_root_digest = String::from("foo");
- let vendor_hashtree_descriptor_root_digest =
- vendor_hashtree_descriptor_root_digest.as_bytes();
-
- let tmp_dir = tempfile::TempDir::new()?;
- let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
-
- create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path)?;
-
- let data = std::fs::read(dtbo_path)?;
- let fdt = Fdt::from_slice(&data).unwrap();
-
- let fragment_node_path = CString::new("/fragment@0")?;
- let fragment_node = fdt.node(fragment_node_path.as_c_str()).unwrap();
- let Some(fragment_node) = fragment_node else {
- bail!("fragment_node shouldn't be None.");
- };
- let target_path_prop_name = CString::new("target-path")?;
- let target_path_from_dtbo =
- fragment_node.getprop(target_path_prop_name.as_c_str()).unwrap();
- let target_path_expected = CString::new("/")?;
- assert_eq!(target_path_from_dtbo, Some(target_path_expected.to_bytes_with_nul()));
-
- let avf_node_path = CString::new("/fragment@0/__overlay__/avf")?;
- let avf_node = fdt.node(avf_node_path.as_c_str()).unwrap();
- let Some(avf_node) = avf_node else {
- bail!("avf_node shouldn't be None.");
- };
- let vendor_hashtree_descriptor_root_digest_name =
- CString::new("vendor_hashtree_descriptor_root_digest")?;
- let digest_from_dtbo =
- avf_node.getprop(vendor_hashtree_descriptor_root_digest_name.as_c_str()).unwrap();
- assert_eq!(digest_from_dtbo, Some(vendor_hashtree_descriptor_root_digest));
-
- tmp_dir.close()?;
- Ok(())
- }
-
- #[test]
- fn test_create_dtbo_for_vendor_image_throws_error_if_already_exists() -> Result<()> {
- let vendor_hashtree_descriptor_root_digest = String::from("foo");
- let vendor_hashtree_descriptor_root_digest =
- vendor_hashtree_descriptor_root_digest.as_bytes();
-
- let tmp_dir = tempfile::TempDir::new()?;
- let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
-
- create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path)?;
-
- let ret_second_trial =
- create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path);
- assert!(ret_second_trial.is_err(), "should fail");
-
- tmp_dir.close()?;
- Ok(())
- }
-
fn test_extract_os_name_from_config_path(
path: &Path,
expected_result: Option<&str>,
diff --git a/virtualizationmanager/src/crosvm.rs b/virtualizationmanager/src/crosvm.rs
index 4b3478e..84c60bd 100644
--- a/virtualizationmanager/src/crosvm.rs
+++ b/virtualizationmanager/src/crosvm.rs
@@ -118,7 +118,7 @@
pub gdb_port: Option<NonZeroU16>,
pub vfio_devices: Vec<VfioDevice>,
pub dtbo: Option<File>,
- pub dtbo_vendor: Option<File>,
+ pub reference_dt: Option<File>,
}
/// A disk image to pass to crosvm for a VM.
@@ -810,8 +810,10 @@
}
if config.host_cpu_topology {
- // TODO(b/266664564): replace with --host-cpu-topology once available
- if let Some(cpus) = get_num_cpus() {
+ if cfg!(virt_cpufreq) {
+ command.arg("--host-cpu-topology");
+ command.arg("--virt-cpufreq");
+ } else if let Some(cpus) = get_num_cpus() {
command.arg("--cpus").arg(cpus.to_string());
} else {
bail!("Could not determine the number of CPUs in the system");
@@ -894,8 +896,10 @@
.arg("--socket")
.arg(add_preserved_fd(&mut preserved_fds, &control_server_socket.as_raw_descriptor()));
- if let Some(dtbo_vendor) = &config.dtbo_vendor {
- command.arg("--device-tree-overlay").arg(add_preserved_fd(&mut preserved_fds, dtbo_vendor));
+ if let Some(reference_dt) = &config.reference_dt {
+ command
+ .arg("--device-tree-overlay")
+ .arg(add_preserved_fd(&mut preserved_fds, reference_dt));
}
append_platform_devices(&mut command, &mut preserved_fds, &config)?;
diff --git a/virtualizationmanager/src/debug_config.rs b/virtualizationmanager/src/debug_config.rs
index 003a7d4..e2b657a 100644
--- a/virtualizationmanager/src/debug_config.rs
+++ b/virtualizationmanager/src/debug_config.rs
@@ -45,7 +45,7 @@
// unwrap() is safe for to_str() because node_path and prop_name were &str.
PathBuf::from(
[
- "/sys/firmware/devicetree/base",
+ "/proc/device-tree",
self.node_path.to_str().unwrap(),
"/",
self.prop_name.to_str().unwrap(),
diff --git a/virtualizationmanager/src/main.rs b/virtualizationmanager/src/main.rs
index f058547..2e542c3 100644
--- a/virtualizationmanager/src/main.rs
+++ b/virtualizationmanager/src/main.rs
@@ -20,6 +20,7 @@
mod crosvm;
mod debug_config;
mod payload;
+mod reference_dt;
mod selinux;
use crate::aidl::{GLOBAL_SERVICE, VirtualizationService};
@@ -27,7 +28,7 @@
use anyhow::{bail, Context, Result};
use binder::{BinderFeatures, ProcessState};
use lazy_static::lazy_static;
-use log::{info, Level};
+use log::{info, LevelFilter};
use rpcbinder::{FileDescriptorTransportMode, RpcServer};
use std::os::unix::io::{FromRawFd, OwnedFd, RawFd};
use clap::Parser;
@@ -107,8 +108,8 @@
android_logger::init_once(
android_logger::Config::default()
.with_tag(LOG_TAG)
- .with_min_level(Level::Info)
- .with_log_id(android_logger::LogId::System),
+ .with_max_level(LevelFilter::Info)
+ .with_log_buffer(android_logger::LogId::System),
);
check_vm_support().unwrap();
diff --git a/virtualizationmanager/src/payload.rs b/virtualizationmanager/src/payload.rs
index c19c103..05626d3 100644
--- a/virtualizationmanager/src/payload.rs
+++ b/virtualizationmanager/src/payload.rs
@@ -194,7 +194,8 @@
let payload_metadata = match &app_config.payload {
Payload::PayloadConfig(payload_config) => PayloadMetadata::Config(PayloadConfig {
payload_binary_name: payload_config.payloadBinaryName.clone(),
- ..Default::default()
+ extra_apk_count: payload_config.extraApks.len().try_into()?,
+ special_fields: Default::default(),
}),
Payload::ConfigPath(config_path) => {
PayloadMetadata::ConfigPath(format!("/mnt/apk/{}", config_path))
@@ -258,10 +259,11 @@
debug_config: &DebugConfig,
apk_file: File,
idsig_file: File,
+ extra_apk_files: Vec<File>,
vm_payload_config: &VmPayloadConfig,
temporary_directory: &Path,
) -> Result<DiskImage> {
- if vm_payload_config.extra_apks.len() != app_config.extraIdsigs.len() {
+ if extra_apk_files.len() != app_config.extraIdsigs.len() {
bail!(
"payload config has {} apks, but app config has {} idsigs",
vm_payload_config.extra_apks.len(),
@@ -309,26 +311,23 @@
});
// we've already checked that extra_apks and extraIdsigs are in the same size.
- let extra_apks = &vm_payload_config.extra_apks;
let extra_idsigs = &app_config.extraIdsigs;
- for (i, (extra_apk, extra_idsig)) in extra_apks.iter().zip(extra_idsigs.iter()).enumerate() {
+ for (i, (extra_apk_file, extra_idsig)) in
+ extra_apk_files.into_iter().zip(extra_idsigs.iter()).enumerate()
+ {
partitions.push(Partition {
- label: format!("extra-apk-{}", i),
- image: Some(ParcelFileDescriptor::new(
- File::open(PathBuf::from(&extra_apk.path)).with_context(|| {
- format!("Failed to open the extra apk #{} {}", i, extra_apk.path)
- })?,
- )),
+ label: format!("extra-apk-{i}"),
+ image: Some(ParcelFileDescriptor::new(extra_apk_file)),
writable: false,
});
partitions.push(Partition {
- label: format!("extra-idsig-{}", i),
+ label: format!("extra-idsig-{i}"),
image: Some(ParcelFileDescriptor::new(
extra_idsig
.as_ref()
.try_clone()
- .with_context(|| format!("Failed to clone the extra idsig #{}", i))?,
+ .with_context(|| format!("Failed to clone the extra idsig #{i}"))?,
)),
writable: false,
});
@@ -459,12 +458,14 @@
Ok(())
}
+#[allow(clippy::too_many_arguments)] // TODO: Fewer arguments
pub fn add_microdroid_payload_images(
config: &VirtualMachineAppConfig,
debug_config: &DebugConfig,
temporary_directory: &Path,
apk_file: File,
idsig_file: File,
+ extra_apk_files: Vec<File>,
vm_payload_config: &VmPayloadConfig,
vm_config: &mut VirtualMachineRawConfig,
) -> Result<()> {
@@ -473,6 +474,7 @@
debug_config,
apk_file,
idsig_file,
+ extra_apk_files,
vm_payload_config,
temporary_directory,
)?);
diff --git a/virtualizationmanager/src/reference_dt.rs b/virtualizationmanager/src/reference_dt.rs
new file mode 100644
index 0000000..797ee3c
--- /dev/null
+++ b/virtualizationmanager/src/reference_dt.rs
@@ -0,0 +1,93 @@
+// 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.
+
+//! Functions for VM reference DT
+
+use anyhow::{anyhow, Result};
+use cstr::cstr;
+use fsfdt::FsFdt;
+use libfdt::Fdt;
+use std::fs;
+use std::fs::File;
+use std::path::Path;
+
+const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
+const VM_REFERENCE_DT_NAME: &str = "vm_reference_dt.dtbo";
+const VM_REFERENCE_DT_MAX_SIZE: usize = 2000;
+
+// Parses to VM reference if exists.
+// TODO(b/318431695): Allow to parse from custom VM reference DT
+pub(crate) fn parse_reference_dt(out_dir: &Path) -> Result<Option<File>> {
+ parse_reference_dt_internal(
+ Path::new(VM_REFERENCE_DT_ON_HOST_PATH),
+ &out_dir.join(VM_REFERENCE_DT_NAME),
+ )
+}
+
+fn parse_reference_dt_internal(dir_path: &Path, fdt_path: &Path) -> Result<Option<File>> {
+ if !dir_path.exists() || fs::read_dir(dir_path)?.next().is_none() {
+ return Ok(None);
+ }
+
+ let mut data = vec![0_u8; VM_REFERENCE_DT_MAX_SIZE];
+
+ let fdt = Fdt::create_empty_tree(&mut data)
+ .map_err(|e| anyhow!("Failed to create an empty DT, {e:?}"))?;
+ let mut root = fdt.root_mut().map_err(|e| anyhow!("Failed to find the DT root, {e:?}"))?;
+ let mut fragment = root
+ .add_subnode(cstr!("fragment@0"))
+ .map_err(|e| anyhow!("Failed to create the fragment@0, {e:?}"))?;
+ fragment
+ .setprop(cstr!("target-path"), b"/\0")
+ .map_err(|e| anyhow!("Failed to set target-path, {e:?}"))?;
+ fragment
+ .add_subnode(cstr!("__overlay__"))
+ .map_err(|e| anyhow!("Failed to create the __overlay__, {e:?}"))?;
+
+ fdt.append(cstr!("/fragment@0/__overlay__"), dir_path)?;
+
+ fdt.pack().map_err(|e| anyhow!("Failed to pack VM reference DT, {e:?}"))?;
+ fs::write(fdt_path, fdt.as_slice())?;
+
+ Ok(Some(File::open(fdt_path)?))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_parse_reference_dt_from_empty_dir() {
+ let empty_dir = tempfile::TempDir::new().unwrap();
+ let test_dir = tempfile::TempDir::new().unwrap();
+
+ let empty_dir_path = empty_dir.path();
+ let fdt_path = test_dir.path().join("test.dtb");
+
+ let fdt_file = parse_reference_dt_internal(empty_dir_path, &fdt_path).unwrap();
+
+ assert!(fdt_file.is_none());
+ }
+
+ #[test]
+ fn test_parse_reference_dt_from_empty_reference() {
+ let fdt_file = parse_reference_dt_internal(
+ Path::new("/this/path/would/not/exists"),
+ Path::new("test.dtb"),
+ )
+ .unwrap();
+
+ assert!(fdt_file.is_none());
+ }
+}
diff --git a/virtualizationservice/Android.bp b/virtualizationservice/Android.bp
index e0bb97f..71d9d4b 100644
--- a/virtualizationservice/Android.bp
+++ b/virtualizationservice/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/virtualizationservice/aidl/Android.bp b/virtualizationservice/aidl/Android.bp
index 8ca375a..7c9c4f7 100644
--- a/virtualizationservice/aidl/Android.bp
+++ b/virtualizationservice/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
index f3f54f3..7ca5b62 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
@@ -28,4 +28,7 @@
* Name of the OS to run the payload. Currently "microdroid" and "microdroid_gki" is supported.
*/
@utf8InCpp String osName = "microdroid";
+
+ /** Any extra APKs. */
+ List<ParcelFileDescriptor> extraApks;
}
diff --git a/virtualizationservice/src/main.rs b/virtualizationservice/src/main.rs
index ea073bf..ad21e89 100644
--- a/virtualizationservice/src/main.rs
+++ b/virtualizationservice/src/main.rs
@@ -27,7 +27,7 @@
use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::BnVirtualizationServiceInternal;
use anyhow::Error;
use binder::{register_lazy_service, BinderFeatures, ProcessState, ThreadState};
-use log::{info, Level};
+use log::{info, LevelFilter};
use std::fs::{create_dir, read_dir};
use std::os::unix::raw::{pid_t, uid_t};
use std::path::Path;
@@ -48,8 +48,8 @@
android_logger::init_once(
Config::default()
.with_tag(LOG_TAG)
- .with_min_level(Level::Info)
- .with_log_id(android_logger::LogId::System)
+ .with_max_level(LevelFilter::Info)
+ .with_log_buffer(android_logger::LogId::System)
.with_filter(
// Reduce logspam by silencing logs from the disk crate which don't provide much
// information to us.
diff --git a/virtualizationservice/vfio_handler/Android.bp b/virtualizationservice/vfio_handler/Android.bp
index 66fc2ee..b9d495b 100644
--- a/virtualizationservice/vfio_handler/Android.bp
+++ b/virtualizationservice/vfio_handler/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/virtualizationservice/vfio_handler/src/main.rs b/virtualizationservice/vfio_handler/src/main.rs
index 1a1cce8..318d134 100644
--- a/virtualizationservice/vfio_handler/src/main.rs
+++ b/virtualizationservice/vfio_handler/src/main.rs
@@ -24,7 +24,7 @@
IVfioHandler,
};
use binder::{register_lazy_service, BinderFeatures, ProcessState};
-use log::{info, Level};
+use log::{info, LevelFilter};
const LOG_TAG: &str = "VfioHandler";
@@ -32,8 +32,8 @@
android_logger::init_once(
Config::default()
.with_tag(LOG_TAG)
- .with_min_level(Level::Info)
- .with_log_id(android_logger::LogId::System),
+ .with_max_level(LevelFilter::Info)
+ .with_log_buffer(android_logger::LogId::System),
);
let service = VfioHandler::init();
diff --git a/vm/Android.bp b/vm/Android.bp
index 04aff5e..ff1b788 100644
--- a/vm/Android.bp
+++ b/vm/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/vm/src/main.rs b/vm/src/main.rs
index 5c07eed..de9291c 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -34,7 +34,7 @@
#[derive(Debug)]
struct Idsigs(Vec<PathBuf>);
-#[derive(Args)]
+#[derive(Args, Default)]
/// Collection of flags that are at VM level and therefore applicable to all subcommands
pub struct CommonConfig {
/// Name of VM
@@ -59,7 +59,7 @@
protected: bool,
}
-#[derive(Args)]
+#[derive(Args, Default)]
/// Collection of flags for debugging
pub struct DebugConfig {
/// Debug level of the VM. Supported values: "full" (default), and "none".
@@ -84,7 +84,7 @@
gdb: Option<NonZeroU16>,
}
-#[derive(Args)]
+#[derive(Args, Default)]
/// Collection of flags that are Microdroid specific
pub struct MicrodroidConfig {
/// Path to the file backing the storage.
@@ -145,7 +145,7 @@
}
}
-#[derive(Args)]
+#[derive(Args, Default)]
/// Flags for the run_app subcommand
pub struct RunAppConfig {
#[command(flatten)]
@@ -175,12 +175,30 @@
#[arg(alias = "payload_path")]
payload_binary_name: Option<String>,
+ /// Paths to extra apk files.
+ #[cfg(multi_tenant)]
+ #[arg(long = "extra-apk")]
+ #[clap(conflicts_with = "config_path")]
+ extra_apks: Vec<PathBuf>,
+
/// Paths to extra idsig files.
#[arg(long = "extra-idsig")]
extra_idsigs: Vec<PathBuf>,
}
-#[derive(Args)]
+impl RunAppConfig {
+ #[cfg(multi_tenant)]
+ fn extra_apks(&self) -> &[PathBuf] {
+ &self.extra_apks
+ }
+
+ #[cfg(not(multi_tenant))]
+ fn extra_apks(&self) -> &[PathBuf] {
+ &[]
+ }
+}
+
+#[derive(Args, Default)]
/// Flags for the run_microdroid subcommand
pub struct RunMicrodroidConfig {
#[command(flatten)]
@@ -199,7 +217,7 @@
work_dir: Option<PathBuf>,
}
-#[derive(Args)]
+#[derive(Args, Default)]
/// Flags for the run subcommand
pub struct RunCustomVmConfig {
#[command(flatten)]
diff --git a/vm/src/run.rs b/vm/src/run.rs
index cfc5454..1d2f48b 100644
--- a/vm/src/run.rs
+++ b/vm/src/run.rs
@@ -48,7 +48,7 @@
let extra_apks = match config.config_path.as_deref() {
Some(path) => parse_extra_apk_list(&config.apk, path)?,
- None => vec![],
+ None => config.extra_apks().to_vec(),
};
if extra_apks.len() != config.extra_idsigs.len() {
@@ -101,8 +101,7 @@
let vendor =
config.microdroid.vendor().as_ref().map(|p| open_parcel_file(p, false)).transpose()?;
- let extra_idsig_files: Result<Vec<File>, _> =
- config.extra_idsigs.iter().map(File::open).collect();
+ let extra_idsig_files: Result<Vec<_>, _> = config.extra_idsigs.iter().map(File::open).collect();
let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
let payload = if let Some(config_path) = config.config_path {
@@ -119,9 +118,14 @@
} else {
"microdroid".to_owned()
};
+
+ let extra_apk_files: Result<Vec<_>, _> = extra_apks.iter().map(File::open).collect();
+ let extra_apk_fds = extra_apk_files?.into_iter().map(ParcelFileDescriptor::new).collect();
+
Payload::PayloadConfig(VirtualMachinePayloadConfig {
payloadBinaryName: payload_binary_name,
osName: os_name,
+ extraApks: extra_apk_fds,
})
} else {
bail!("Either --config-path or --payload-binary-name must be defined")
@@ -208,9 +212,8 @@
apk,
idsig,
instance: instance_img,
- config_path: None,
payload_binary_name: Some("MicrodroidEmptyPayloadJniLib.so".to_owned()),
- extra_idsigs: [].to_vec(),
+ ..Default::default()
};
command_run_app(app_config)
}
@@ -310,11 +313,11 @@
Ok(())
}
-fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> {
+fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<PathBuf>, Error> {
let mut archive = ZipArchive::new(File::open(apk)?)?;
let config_file = archive.by_name(config_path)?;
let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
- Ok(config.extra_apks.into_iter().map(|x| x.path).collect())
+ Ok(config.extra_apks.into_iter().map(|x| x.path.into()).collect())
}
struct Callback {}
diff --git a/vm_payload/src/api.rs b/vm_payload/src/api.rs
index c76f2d3..7978059 100644
--- a/vm_payload/src/api.rs
+++ b/vm_payload/src/api.rs
@@ -24,7 +24,7 @@
Strong, ExceptionCode,
};
use lazy_static::lazy_static;
-use log::{error, info, Level};
+use log::{error, info, LevelFilter};
use rpcbinder::{RpcServer, RpcSession};
use openssl::{ec::EcKey, sha::sha256, ecdsa::EcdsaSig};
use std::convert::Infallible;
@@ -67,7 +67,7 @@
/// Make sure our logging goes to logcat. It is harmless to call this more than once.
fn initialize_logging() {
android_logger::init_once(
- android_logger::Config::default().with_tag("vm_payload").with_min_level(Level::Info),
+ android_logger::Config::default().with_tag("vm_payload").with_max_level(LevelFilter::Info),
);
}
diff --git a/vmbase/example/tests/test.rs b/vmbase/example/tests/test.rs
index 17ff947..2df5a80 100644
--- a/vmbase/example/tests/test.rs
+++ b/vmbase/example/tests/test.rs
@@ -42,7 +42,9 @@
#[test]
fn test_run_example_vm() -> Result<(), Error> {
android_logger::init_once(
- android_logger::Config::default().with_tag("vmbase").with_min_level(log::Level::Debug),
+ android_logger::Config::default()
+ .with_tag("vmbase")
+ .with_max_level(log::LevelFilter::Debug),
);
// Redirect panic messages to logcat.
diff --git a/zipfuse/Android.bp b/zipfuse/Android.bp
index 974d66a..7ee0ef1 100644
--- a/zipfuse/Android.bp
+++ b/zipfuse/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}