Merge "pvmfw: Apply debug policy from config to VM FDT"
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 5a422df..72926ff 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -55,7 +55,7 @@
"path": "packages/modules/Virtualization/encryptedstore"
},
{
- "path": "packages/modules/Virtualization/virtualizationservice"
+ "path": "packages/modules/Virtualization/virtualizationmanager"
},
{
"path": "packages/modules/Virtualization/libs/apexutil"
diff --git a/compos/tests/Android.bp b/compos/tests/Android.bp
index 41958ca..511ecd0 100644
--- a/compos/tests/Android.bp
+++ b/compos/tests/Android.bp
@@ -19,7 +19,7 @@
// java_test_host doesn't have data_native_libs but jni_libs can be used to put
// native modules under ./lib directory.
// This works because host tools have rpath (../lib and ./lib).
- data_native_bins: ["bcc_validator"],
+ data_native_bins: ["hwtrust"],
jni_libs: [
"libcrypto",
"libc++",
diff --git a/compos/tests/java/android/compos/test/ComposTestCase.java b/compos/tests/java/android/compos/test/ComposTestCase.java
index d8504f7..fe1c4f0 100644
--- a/compos/tests/java/android/compos/test/ComposTestCase.java
+++ b/compos/tests/java/android/compos/test/ComposTestCase.java
@@ -186,13 +186,16 @@
new FileInputStreamSource(bcc_file));
// Find the validator binary - note that it's specified as a dependency in our Android.bp.
- File validator = getTestInformation().getDependencyFile("bcc_validator", /*targetFirst=*/
- false);
+ File validator = getTestInformation().getDependencyFile("hwtrust", /*targetFirst=*/ false);
- CommandResult result = new RunUtil().runTimedCmd(10000,
- validator.getAbsolutePath(), "verify-chain", bcc_file.getAbsolutePath());
- assertWithMessage("bcc_validator failed").about(command_results())
- .that(result).isSuccess();
+ CommandResult result =
+ new RunUtil()
+ .runTimedCmd(
+ 10000,
+ validator.getAbsolutePath(),
+ "verify-dice-chain",
+ bcc_file.getAbsolutePath());
+ assertWithMessage("hwtrust failed").about(command_results()).that(result).isSuccess();
}
private CommandResult runOdrefresh(CommandRunner android, String command) throws Exception {
diff --git a/libs/apkverify/src/v3.rs b/libs/apkverify/src/v3.rs
index fcd966b..e1b728d 100644
--- a/libs/apkverify/src/v3.rs
+++ b/libs/apkverify/src/v3.rs
@@ -110,7 +110,7 @@
) -> Result<(Signer, ApkSections<R>)> {
let mut sections = ApkSections::new(apk)?;
let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).context(
- "Fallback to v2 when v3 block not found is not yet implemented. See b/197052981.",
+ "Fallback to v2 when v3 block not found is not yet implemented.", // b/197052981
)?;
let mut supported = block
.read::<Signers>()?
@@ -135,7 +135,7 @@
.iter()
.filter(|sig| sig.signature_algorithm_id.map_or(false, |algo| algo.is_supported()))
.max_by_key(|sig| sig.signature_algorithm_id.unwrap().content_digest_algorithm())
- .context("No supported signatures found")?)
+ .context("No supported APK signatures found; DSA is not supported")?)
}
pub(crate) fn find_digest_by_algorithm(
diff --git a/libs/apkverify/tests/apkverify_test.rs b/libs/apkverify/tests/apkverify_test.rs
index 047538c..baf7c42 100644
--- a/libs/apkverify/tests/apkverify_test.rs
+++ b/libs/apkverify/tests/apkverify_test.rs
@@ -44,7 +44,7 @@
for key_name in KEY_NAMES_DSA.iter() {
let res = verify(format!("tests/data/v3-only-with-dsa-sha256-{}.apk", key_name));
assert!(res.is_err(), "DSA algorithm is not supported for verification. See b/197052981.");
- assert_contains(&res.unwrap_err().to_string(), "No supported signatures found");
+ assert_contains(&res.unwrap_err().to_string(), "No supported APK signatures found");
}
}
@@ -151,7 +151,7 @@
fn test_verify_v3_no_supported_sig_algs() {
let res = verify("tests/data/v3-only-no-supported-sig-algs.apk");
assert!(res.is_err());
- assert_contains(&res.unwrap_err().to_string(), "No supported signatures found");
+ assert_contains(&res.unwrap_err().to_string(), "No supported APK signatures found");
}
#[test]
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index f48611b..24a12f7 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -77,6 +77,7 @@
"/sys/firmware/devicetree/base/virtualization/guest/debug-microdroid,no-verified-boot";
const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
+const TOMBSTONE_TRANSMIT_DONE_PROP: &str = "tombstone_transmit.init_done";
const DEBUGGABLE_PROP: &str = "ro.boot.microdroid.debuggable";
// SYNC WITH virtualizationservice/src/crosvm.rs
@@ -435,6 +436,10 @@
register_vm_payload_service(allow_restricted_apis, service.clone(), dice_context)?;
+ if config.export_tombstones {
+ wait_for_tombstone_transmit_done()?;
+ }
+
// Wait for encryptedstore to finish mounting the storage (if enabled) before setting
// microdroid_manager.init_done. Reason is init stops uneventd after that.
// Encryptedstore, however requires ueventd
@@ -723,6 +728,11 @@
wait_for_property_true(APEX_CONFIG_DONE_PROP).context("Failed waiting for apex config done")
}
+fn wait_for_tombstone_transmit_done() -> Result<()> {
+ wait_for_property_true(TOMBSTONE_TRANSMIT_DONE_PROP)
+ .context("Failed waiting for tombstone transmit done")
+}
+
fn wait_for_property_true(property_name: &str) -> Result<()> {
let mut prop = PropertyWatcher::new(property_name)?;
loop {
diff --git a/pvmfw/TEST_MAPPING b/pvmfw/TEST_MAPPING
index 8a2d352..5e58ebb 100644
--- a/pvmfw/TEST_MAPPING
+++ b/pvmfw/TEST_MAPPING
@@ -1,7 +1,7 @@
{
"avf-presubmit" : [
{
- "name" : "libpvmfw_avb.test"
+ "name" : "libpvmfw_avb.integration_test"
}
]
}
\ No newline at end of file
diff --git a/pvmfw/avb/Android.bp b/pvmfw/avb/Android.bp
index d3a5e4e..837f747 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -25,19 +25,26 @@
}
rust_test {
- name: "libpvmfw_avb.test",
- defaults: ["libpvmfw_avb_nostd_defaults"],
+ name: "libpvmfw_avb.integration_test",
+ crate_name: "pvmfw_avb_test",
+ srcs: ["tests/*.rs"],
test_suites: ["general-tests"],
data: [
":avb_testkey_rsa2048_pub_bin",
":avb_testkey_rsa4096_pub_bin",
":microdroid_kernel_signed",
":microdroid_initrd_normal",
+ ":microdroid_initrd_debuggable",
":test_image_with_one_hashdesc",
+ ":test_image_with_non_initrd_hashdesc",
+ ":test_image_with_prop_desc",
":unsigned_test_image",
],
+ prefer_rlib: true,
rustlibs: [
"libanyhow",
+ "libavb_bindgen",
+ "libpvmfw_avb_nostd",
],
enabled: false,
arch: {
@@ -59,6 +66,38 @@
cmd: "$(location avbtool) generate_test_image --image_size 16384 --output $(out)",
}
+avb_gen_vbmeta_image {
+ name: "test_non_initrd_hashdesc",
+ src: ":unsigned_test_image",
+ partition_name: "non_initrd11",
+ salt: "2222",
+}
+
+avb_add_hash_footer {
+ name: "test_image_with_non_initrd_hashdesc",
+ src: ":unsigned_test_image",
+ partition_name: "boot",
+ private_key: ":pvmfw_sign_key",
+ salt: "1111",
+ include_descriptors_from_images: [
+ ":test_non_initrd_hashdesc",
+ ],
+}
+
+avb_add_hash_footer {
+ name: "test_image_with_prop_desc",
+ src: ":unsigned_test_image",
+ partition_name: "boot",
+ private_key: ":pvmfw_sign_key",
+ salt: "1111",
+ props: [
+ {
+ name: "mock_prop",
+ value: "3333",
+ },
+ ],
+}
+
avb_add_hash_footer {
name: "test_image_with_one_hashdesc",
src: ":unsigned_test_image",
diff --git a/pvmfw/avb/src/error.rs b/pvmfw/avb/src/error.rs
index 8b06150..674e5a7 100644
--- a/pvmfw/avb/src/error.rs
+++ b/pvmfw/avb/src/error.rs
@@ -12,9 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! This module contains the error thrown by the payload verification API.
+//! This module contains the error thrown by the payload verification API
+//! and other errors used in the library.
-use avb_bindgen::AvbSlotVerifyResult;
+use avb_bindgen::{AvbIOResult, AvbSlotVerifyResult};
use core::fmt;
@@ -85,3 +86,44 @@
}
}
}
+
+#[derive(Debug)]
+pub(crate) enum AvbIOError {
+ /// AVB_IO_RESULT_ERROR_OOM,
+ #[allow(dead_code)]
+ Oom,
+ /// AVB_IO_RESULT_ERROR_IO,
+ #[allow(dead_code)]
+ Io,
+ /// AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
+ NoSuchPartition,
+ /// AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION,
+ RangeOutsidePartition,
+ /// AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
+ NoSuchValue,
+ /// AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
+ InvalidValueSize,
+ /// AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
+ #[allow(dead_code)]
+ InsufficientSpace,
+}
+
+impl From<AvbIOError> for AvbIOResult {
+ fn from(error: AvbIOError) -> Self {
+ match error {
+ AvbIOError::Oom => AvbIOResult::AVB_IO_RESULT_ERROR_OOM,
+ AvbIOError::Io => AvbIOResult::AVB_IO_RESULT_ERROR_IO,
+ AvbIOError::NoSuchPartition => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
+ AvbIOError::RangeOutsidePartition => {
+ AvbIOResult::AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION
+ }
+ AvbIOError::NoSuchValue => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
+ AvbIOError::InvalidValueSize => AvbIOResult::AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
+ AvbIOError::InsufficientSpace => AvbIOResult::AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
+ }
+ }
+}
+
+pub(crate) fn to_avb_io_result(result: Result<(), AvbIOError>) -> AvbIOResult {
+ result.map_or_else(|e| e.into(), |_| AvbIOResult::AVB_IO_RESULT_OK)
+}
diff --git a/pvmfw/avb/src/lib.rs b/pvmfw/avb/src/lib.rs
index 6a5b16d..f0ee4ed 100644
--- a/pvmfw/avb/src/lib.rs
+++ b/pvmfw/avb/src/lib.rs
@@ -19,7 +19,9 @@
#![feature(mixed_integer_ops)]
mod error;
+mod partition;
+mod utils;
mod verify;
pub use error::AvbSlotVerifyError;
-pub use verify::verify_payload;
+pub use verify::{verify_payload, DebugLevel};
diff --git a/pvmfw/avb/src/partition.rs b/pvmfw/avb/src/partition.rs
new file mode 100644
index 0000000..82d89f8
--- /dev/null
+++ b/pvmfw/avb/src/partition.rs
@@ -0,0 +1,86 @@
+// 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.
+
+//! Struct and functions relating to well-known partition names.
+
+use crate::error::AvbIOError;
+use crate::utils::is_not_null;
+use core::ffi::{c_char, CStr};
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum PartitionName {
+ Kernel,
+ InitrdNormal,
+ InitrdDebug,
+}
+
+impl PartitionName {
+ const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
+ const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
+ const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
+
+ pub(crate) fn as_cstr(&self) -> &CStr {
+ CStr::from_bytes_with_nul(self.as_bytes()).unwrap()
+ }
+
+ fn as_non_null_terminated_bytes(&self) -> &[u8] {
+ let partition_name = self.as_bytes();
+ &partition_name[..partition_name.len() - 1]
+ }
+
+ fn as_bytes(&self) -> &[u8] {
+ match self {
+ Self::Kernel => Self::KERNEL_PARTITION_NAME,
+ Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
+ Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
+ }
+ }
+}
+
+impl TryFrom<*const c_char> for PartitionName {
+ type Error = AvbIOError;
+
+ fn try_from(partition_name: *const c_char) -> Result<Self, Self::Error> {
+ is_not_null(partition_name)?;
+ // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
+ let partition_name = unsafe { CStr::from_ptr(partition_name) };
+ partition_name.try_into()
+ }
+}
+
+impl TryFrom<&CStr> for PartitionName {
+ type Error = AvbIOError;
+
+ fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
+ match partition_name.to_bytes_with_nul() {
+ Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
+ Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
+ Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
+ _ => Err(AvbIOError::NoSuchPartition),
+ }
+ }
+}
+
+impl TryFrom<&[u8]> for PartitionName {
+ type Error = AvbIOError;
+
+ fn try_from(non_null_terminated_name: &[u8]) -> Result<Self, Self::Error> {
+ match non_null_terminated_name {
+ x if x == Self::Kernel.as_non_null_terminated_bytes() => Ok(Self::Kernel),
+ x if x == Self::InitrdNormal.as_non_null_terminated_bytes() => Ok(Self::InitrdNormal),
+ x if x == Self::InitrdDebug.as_non_null_terminated_bytes() => Ok(Self::InitrdDebug),
+ _ => Err(AvbIOError::NoSuchPartition),
+ }
+ }
+}
diff --git a/pvmfw/avb/src/utils.rs b/pvmfw/avb/src/utils.rs
new file mode 100644
index 0000000..bb27497
--- /dev/null
+++ b/pvmfw/avb/src/utils.rs
@@ -0,0 +1,53 @@
+// 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 crate::error::AvbIOError;
+use core::ptr::NonNull;
+
+pub(crate) fn write<T>(ptr: *mut T, value: T) -> Result<(), AvbIOError> {
+ let ptr = to_nonnull(ptr)?;
+ // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
+ unsafe {
+ *ptr.as_ptr() = value;
+ }
+ Ok(())
+}
+
+pub(crate) fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
+ let ptr = to_nonnull(ptr)?;
+ // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
+ unsafe { Ok(ptr.as_ref()) }
+}
+
+pub(crate) fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
+ NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
+}
+
+pub(crate) fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
+ if ptr.is_null() {
+ Err(AvbIOError::NoSuchValue)
+ } else {
+ Ok(())
+ }
+}
+
+pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize, AvbIOError> {
+ num.try_into().map_err(|_| AvbIOError::InvalidValueSize)
+}
+
+pub(crate) fn usize_checked_add(x: usize, y: usize) -> Result<usize, AvbIOError> {
+ x.checked_add(y).ok_or(AvbIOError::InvalidValueSize)
+}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index fb18626..b39bb5a 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -14,71 +14,41 @@
//! This module handles the pvmfw payload verification.
-use crate::error::{slot_verify_result_to_verify_payload_result, AvbSlotVerifyError};
-use avb_bindgen::{avb_slot_verify, AvbHashtreeErrorMode, AvbIOResult, AvbOps, AvbSlotVerifyFlags};
+use crate::error::{
+ slot_verify_result_to_verify_payload_result, to_avb_io_result, AvbIOError, AvbSlotVerifyError,
+};
+use crate::partition::PartitionName;
+use crate::utils::{as_ref, is_not_null, to_nonnull, to_usize, usize_checked_add, write};
+use avb_bindgen::{
+ avb_descriptor_foreach, avb_hash_descriptor_validate_and_byteswap, avb_slot_verify,
+ avb_slot_verify_data_free, AvbDescriptor, AvbHashDescriptor, AvbHashtreeErrorMode, AvbIOResult,
+ AvbOps, AvbSlotVerifyData, AvbSlotVerifyFlags, AvbVBMetaData,
+};
use core::{
ffi::{c_char, c_void, CStr},
- ptr::{self, NonNull},
- slice,
+ mem::{size_of, MaybeUninit},
+ ptr, slice,
};
-static NULL_BYTE: &[u8] = b"\0";
+const NULL_BYTE: &[u8] = b"\0";
-enum AvbIOError {
- /// AVB_IO_RESULT_ERROR_OOM,
- #[allow(dead_code)]
- Oom,
- /// AVB_IO_RESULT_ERROR_IO,
- #[allow(dead_code)]
- Io,
- /// AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
- NoSuchPartition,
- /// AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION,
- RangeOutsidePartition,
- /// AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
- NoSuchValue,
- /// AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
- InvalidValueSize,
- /// AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
- #[allow(dead_code)]
- InsufficientSpace,
-}
-
-impl From<AvbIOError> for AvbIOResult {
- fn from(error: AvbIOError) -> Self {
- match error {
- AvbIOError::Oom => AvbIOResult::AVB_IO_RESULT_ERROR_OOM,
- AvbIOError::Io => AvbIOResult::AVB_IO_RESULT_ERROR_IO,
- AvbIOError::NoSuchPartition => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
- AvbIOError::RangeOutsidePartition => {
- AvbIOResult::AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION
- }
- AvbIOError::NoSuchValue => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
- AvbIOError::InvalidValueSize => AvbIOResult::AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
- AvbIOError::InsufficientSpace => AvbIOResult::AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
- }
- }
-}
-
-fn to_avb_io_result(result: Result<(), AvbIOError>) -> AvbIOResult {
- result.map_or_else(|e| e.into(), |_| AvbIOResult::AVB_IO_RESULT_OK)
+/// This enum corresponds to the `DebugLevel` in `VirtualMachineConfig`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum DebugLevel {
+ /// Not debuggable at all.
+ None,
+ /// Fully debuggable.
+ Full,
}
extern "C" fn read_is_device_unlocked(
_ops: *mut AvbOps,
out_is_unlocked: *mut bool,
) -> AvbIOResult {
- if let Err(e) = is_not_null(out_is_unlocked) {
- return e.into();
- }
- // SAFETY: It is safe as the raw pointer `out_is_unlocked` is a valid pointer.
- unsafe {
- *out_is_unlocked = false;
- }
- AvbIOResult::AVB_IO_RESULT_OK
+ to_avb_io_result(write(out_is_unlocked, false))
}
-unsafe extern "C" fn get_preloaded_partition(
+extern "C" fn get_preloaded_partition(
ops: *mut AvbOps,
partition: *const c_char,
num_bytes: usize,
@@ -103,18 +73,8 @@
) -> Result<(), AvbIOError> {
let ops = as_ref(ops)?;
let partition = ops.as_ref().get_partition(partition)?;
- let out_pointer = to_nonnull(out_pointer)?;
- // SAFETY: It is safe as the raw pointer `out_pointer` is a nonnull pointer.
- unsafe {
- *out_pointer.as_ptr() = partition.as_ptr() as _;
- }
- let out_num_bytes_preloaded = to_nonnull(out_num_bytes_preloaded)?;
- // SAFETY: The raw pointer `out_num_bytes_preloaded` was created to point to a valid a `usize`
- // and we checked it is nonnull.
- unsafe {
- *out_num_bytes_preloaded.as_ptr() = partition.len().min(num_bytes);
- }
- Ok(())
+ write(out_pointer, partition.as_ptr() as *mut u8)?;
+ write(out_num_bytes_preloaded, partition.len().min(num_bytes))
}
extern "C" fn read_from_partition(
@@ -150,13 +110,7 @@
// is created to point to the `num_bytes` of bytes in memory.
let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
copy_data_to_dst(partition, offset, buffer_slice)?;
- let out_num_read = to_nonnull(out_num_read)?;
- // SAFETY: The raw pointer `out_num_read` was created to point to a valid a `usize`
- // and we checked it is nonnull.
- unsafe {
- *out_num_read.as_ptr() = buffer_slice.len();
- }
- Ok(())
+ write(out_num_read, buffer_slice.len())
}
fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
@@ -189,13 +143,7 @@
let partition = ops.as_ref().get_partition(partition)?;
let partition_size =
u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
- let out_size_num_bytes = to_nonnull(out_size_num_bytes)?;
- // SAFETY: The raw pointer `out_size_num_bytes` was created to point to a valid a `u64`
- // and we checked it is nonnull.
- unsafe {
- *out_size_num_bytes.as_ptr() = partition_size;
- }
- Ok(())
+ write(out_size_num_bytes, partition_size)
}
extern "C" fn read_rollback_index(
@@ -218,38 +166,31 @@
AvbIOResult::AVB_IO_RESULT_OK
}
-extern "C" fn validate_public_key_for_partition(
+extern "C" fn validate_vbmeta_public_key(
ops: *mut AvbOps,
- partition: *const c_char,
public_key_data: *const u8,
public_key_length: usize,
public_key_metadata: *const u8,
public_key_metadata_length: usize,
out_is_trusted: *mut bool,
- out_rollback_index_location: *mut u32,
) -> AvbIOResult {
- to_avb_io_result(try_validate_public_key_for_partition(
+ to_avb_io_result(try_validate_vbmeta_public_key(
ops,
- partition,
public_key_data,
public_key_length,
public_key_metadata,
public_key_metadata_length,
out_is_trusted,
- out_rollback_index_location,
))
}
-#[allow(clippy::too_many_arguments)]
-fn try_validate_public_key_for_partition(
+fn try_validate_vbmeta_public_key(
ops: *mut AvbOps,
- partition: *const c_char,
public_key_data: *const u8,
public_key_length: usize,
_public_key_metadata: *const u8,
_public_key_metadata_length: usize,
out_is_trusted: *mut bool,
- _out_rollback_index_location: *mut u32,
) -> Result<(), AvbIOError> {
is_not_null(public_key_data)?;
// SAFETY: It is safe to create a slice with the given pointer and length as
@@ -257,68 +198,123 @@
// `public_key_length`.
let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
let ops = as_ref(ops)?;
- // Verifies the public key for the known partitions only.
- ops.as_ref().get_partition(partition)?;
let trusted_public_key = ops.as_ref().trusted_public_key;
- let out_is_trusted = to_nonnull(out_is_trusted)?;
- // SAFETY: It is safe as the raw pointer `out_is_trusted` is a nonnull pointer.
- unsafe {
- *out_is_trusted.as_ptr() = public_key == trusted_public_key;
+ write(out_is_trusted, public_key == trusted_public_key)
+}
+
+extern "C" fn search_initrd_hash_descriptor(
+ descriptor: *const AvbDescriptor,
+ user_data: *mut c_void,
+) -> bool {
+ try_search_initrd_hash_descriptor(descriptor, user_data).is_ok()
+}
+
+fn try_search_initrd_hash_descriptor(
+ descriptor: *const AvbDescriptor,
+ user_data: *mut c_void,
+) -> Result<(), AvbIOError> {
+ let hash_desc = AvbHashDescriptorRef::try_from(descriptor)?;
+ if matches!(
+ hash_desc.partition_name()?.try_into(),
+ Ok(PartitionName::InitrdDebug) | Ok(PartitionName::InitrdNormal),
+ ) {
+ write(user_data as *mut bool, true)?;
}
Ok(())
}
-fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
- let ptr = to_nonnull(ptr)?;
- // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
- unsafe { Ok(ptr.as_ref()) }
+/// `hash_desc` only contains the metadata like fields length and flags of the descriptor.
+/// The data itself is contained in `ptr`.
+struct AvbHashDescriptorRef {
+ hash_desc: AvbHashDescriptor,
+ ptr: *const AvbDescriptor,
}
-fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
- NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
-}
-
-fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
- if ptr.is_null() {
- Err(AvbIOError::NoSuchValue)
- } else {
- Ok(())
- }
-}
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-enum PartitionName {
- Kernel,
- InitrdNormal,
- InitrdDebug,
-}
-
-impl PartitionName {
- const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
- const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
- const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
-
- fn as_cstr(&self) -> &CStr {
- let partition_name = match self {
- Self::Kernel => Self::KERNEL_PARTITION_NAME,
- Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
- Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
- };
- CStr::from_bytes_with_nul(partition_name).unwrap()
- }
-}
-
-impl TryFrom<&CStr> for PartitionName {
+impl TryFrom<*const AvbDescriptor> for AvbHashDescriptorRef {
type Error = AvbIOError;
- fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
- match partition_name.to_bytes_with_nul() {
- Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
- Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
- Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
- _ => Err(AvbIOError::NoSuchPartition),
+ fn try_from(descriptor: *const AvbDescriptor) -> Result<Self, Self::Error> {
+ is_not_null(descriptor)?;
+ // SAFETY: It is safe as the raw pointer `descriptor` is a nonnull pointer and
+ // we have validated that it is of hash descriptor type.
+ let hash_desc = unsafe {
+ let mut desc = MaybeUninit::uninit();
+ if !avb_hash_descriptor_validate_and_byteswap(
+ descriptor as *const AvbHashDescriptor,
+ desc.as_mut_ptr(),
+ ) {
+ return Err(AvbIOError::Io);
+ }
+ desc.assume_init()
+ };
+ Ok(Self { hash_desc, ptr: descriptor })
+ }
+}
+
+impl AvbHashDescriptorRef {
+ fn check_is_in_range(&self, index: usize) -> Result<(), AvbIOError> {
+ let parent_desc = self.hash_desc.parent_descriptor;
+ let total_len = usize_checked_add(
+ size_of::<AvbDescriptor>(),
+ to_usize(parent_desc.num_bytes_following)?,
+ )?;
+ if index <= total_len {
+ Ok(())
+ } else {
+ Err(AvbIOError::Io)
}
}
+
+ /// Returns the non null-terminated partition name.
+ fn partition_name(&self) -> Result<&[u8], AvbIOError> {
+ let partition_name_offset = size_of::<AvbHashDescriptor>();
+ let partition_name_len = to_usize(self.hash_desc.partition_name_len)?;
+ self.check_is_in_range(usize_checked_add(partition_name_offset, partition_name_len)?)?;
+ let desc = self.ptr as *const u8;
+ // SAFETY: The descriptor has been validated as nonnull and the partition name is
+ // contained within the image.
+ unsafe { Ok(slice::from_raw_parts(desc.add(partition_name_offset), partition_name_len)) }
+ }
+}
+
+struct AvbSlotVerifyDataWrap(*mut AvbSlotVerifyData);
+
+impl TryFrom<*mut AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
+ type Error = AvbSlotVerifyError;
+
+ fn try_from(data: *mut AvbSlotVerifyData) -> Result<Self, Self::Error> {
+ is_not_null(data).map_err(|_| AvbSlotVerifyError::Io)?;
+ Ok(Self(data))
+ }
+}
+
+impl Drop for AvbSlotVerifyDataWrap {
+ fn drop(&mut self) {
+ // SAFETY: This is safe because `self.0` is checked nonnull when the
+ // instance is created. We can free this pointer when the instance is
+ // no longer needed.
+ unsafe {
+ avb_slot_verify_data_free(self.0);
+ }
+ }
+}
+
+impl AsRef<AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
+ fn as_ref(&self) -> &AvbSlotVerifyData {
+ // This is safe because `self.0` is checked nonnull when the instance is created.
+ as_ref(self.0).unwrap()
+ }
+}
+
+impl AvbSlotVerifyDataWrap {
+ fn vbmeta_images(&self) -> Result<&[AvbVBMetaData], AvbSlotVerifyError> {
+ let data = self.as_ref();
+ is_not_null(data.vbmeta_images).map_err(|_| AvbSlotVerifyError::Io)?;
+ // SAFETY: It is safe as the raw pointer `data.vbmeta_images` is a nonnull pointer.
+ let vbmeta_images =
+ unsafe { slice::from_raw_parts(data.vbmeta_images, data.num_vbmeta_images) };
+ Ok(vbmeta_images)
+ }
}
struct Payload<'a> {
@@ -339,12 +335,7 @@
}
impl<'a> Payload<'a> {
- const MAX_NUM_OF_HASH_DESCRIPTORS: usize = 3;
-
fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
- is_not_null(partition_name)?;
- // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
- let partition_name = unsafe { CStr::from_ptr(partition_name) };
match partition_name.try_into()? {
PartitionName::Kernel => Ok(self.kernel),
PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
@@ -353,16 +344,11 @@
}
}
- fn verify_partitions(&mut self, partition_names: &[&CStr]) -> Result<(), AvbSlotVerifyError> {
- if partition_names.len() > Self::MAX_NUM_OF_HASH_DESCRIPTORS {
- return Err(AvbSlotVerifyError::InvalidArgument);
- }
- let mut requested_partitions = [ptr::null(); Self::MAX_NUM_OF_HASH_DESCRIPTORS + 1];
- partition_names
- .iter()
- .enumerate()
- .for_each(|(i, name)| requested_partitions[i] = name.as_ptr());
-
+ fn verify_partition(
+ &mut self,
+ partition_name: &CStr,
+ ) -> Result<AvbSlotVerifyDataWrap, AvbSlotVerifyError> {
+ let requested_partitions = [partition_name.as_ptr(), ptr::null()];
let mut avb_ops = AvbOps {
user_data: self as *mut _ as *mut c_void,
ab_ops: ptr::null_mut(),
@@ -370,7 +356,7 @@
read_from_partition: Some(read_from_partition),
get_preloaded_partition: Some(get_preloaded_partition),
write_to_partition: None,
- validate_vbmeta_public_key: None,
+ validate_vbmeta_public_key: Some(validate_vbmeta_public_key),
read_rollback_index: Some(read_rollback_index),
write_rollback_index: None,
read_is_device_unlocked: Some(read_is_device_unlocked),
@@ -378,10 +364,10 @@
get_size_of_partition: Some(get_size_of_partition),
read_persistent_value: None,
write_persistent_value: None,
- validate_public_key_for_partition: Some(validate_public_key_for_partition),
+ validate_public_key_for_partition: None,
};
let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
- let out_data = ptr::null_mut();
+ let mut out_data = MaybeUninit::uninit();
// SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
// `requested_partitions` and `ab_suffix`) passed to the method are all valid and
// initialized. The last argument `out_data` is allowed to be null so that nothing
@@ -391,12 +377,48 @@
&mut avb_ops,
requested_partitions.as_ptr(),
ab_suffix.as_ptr(),
- AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
+ AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NONE,
AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
- out_data,
+ out_data.as_mut_ptr(),
)
};
- slot_verify_result_to_verify_payload_result(result)
+ slot_verify_result_to_verify_payload_result(result)?;
+ // SAFETY: This is safe because `out_data` has been properly initialized after
+ // calling `avb_slot_verify` and it returns OK.
+ let out_data = unsafe { out_data.assume_init() };
+ out_data.try_into()
+ }
+}
+
+fn verify_vbmeta_has_no_initrd_descriptor(
+ vbmeta_image: &AvbVBMetaData,
+) -> Result<(), AvbSlotVerifyError> {
+ is_not_null(vbmeta_image.vbmeta_data).map_err(|_| AvbSlotVerifyError::Io)?;
+ let mut has_unexpected_descriptor = false;
+ // SAFETY: It is safe as the raw pointer `vbmeta_image.vbmeta_data` is a nonnull pointer.
+ if !unsafe {
+ avb_descriptor_foreach(
+ vbmeta_image.vbmeta_data,
+ vbmeta_image.vbmeta_size,
+ Some(search_initrd_hash_descriptor),
+ &mut has_unexpected_descriptor as *mut _ as *mut c_void,
+ )
+ } {
+ return Err(AvbSlotVerifyError::InvalidMetadata);
+ }
+ if has_unexpected_descriptor {
+ Err(AvbSlotVerifyError::InvalidMetadata)
+ } else {
+ Ok(())
+ }
+}
+
+fn verify_vbmeta_is_from_kernel_partition(
+ vbmeta_image: &AvbVBMetaData,
+) -> Result<(), AvbSlotVerifyError> {
+ match (vbmeta_image.partition_name as *const c_char).try_into() {
+ Ok(PartitionName::Kernel) => Ok(()),
+ _ => Err(AvbSlotVerifyError::InvalidMetadata),
}
}
@@ -405,134 +427,29 @@
kernel: &[u8],
initrd: Option<&[u8]>,
trusted_public_key: &[u8],
-) -> Result<(), AvbSlotVerifyError> {
+) -> Result<DebugLevel, AvbSlotVerifyError> {
let mut payload = Payload { kernel, initrd, trusted_public_key };
- let requested_partitions = [PartitionName::Kernel.as_cstr()];
- payload.verify_partitions(&requested_partitions)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use anyhow::Result;
- use avb_bindgen::AvbFooter;
- use std::{fs, mem::size_of};
-
- const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
- const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
- const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
- const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
-
- const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
- const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
- const RANDOM_FOOTER_POS: usize = 30;
-
- /// This test uses the Microdroid payload compiled on the fly to check that
- /// the latest payload can be verified successfully.
- #[test]
- fn latest_valid_payload_passes_verification() -> Result<()> {
- let kernel = load_latest_signed_kernel()?;
- let initrd_normal = fs::read(INITRD_NORMAL_IMG_PATH)?;
- let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
-
- assert_eq!(Ok(()), verify_payload(&kernel, Some(&initrd_normal[..]), &public_key));
- Ok(())
+ let kernel_verify_result = payload.verify_partition(PartitionName::Kernel.as_cstr())?;
+ let vbmeta_images = kernel_verify_result.vbmeta_images()?;
+ if vbmeta_images.len() != 1 {
+ // There can only be one VBMeta.
+ return Err(AvbSlotVerifyError::InvalidMetadata);
}
-
- #[test]
- fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
- let kernel = fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?;
- let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
-
- assert_eq!(Ok(()), verify_payload(&kernel, None, &public_key));
- Ok(())
+ let vbmeta_image = vbmeta_images[0];
+ verify_vbmeta_is_from_kernel_partition(&vbmeta_image)?;
+ if payload.initrd.is_none() {
+ verify_vbmeta_has_no_initrd_descriptor(&vbmeta_image)?;
+ return Ok(DebugLevel::None);
}
+ // TODO(b/256148034): Check the vbmeta doesn't have hash descriptors other than
+ // boot, initrd_normal, initrd_debug.
- // TODO(b/256148034): Test that kernel with two hashdesc and no initrd fails verification.
- // e.g. payload_expecting_initrd_fails_verification_with_no_initrd
-
- #[test]
- fn payload_with_empty_public_key_fails_verification() -> Result<()> {
- assert_payload_verification_fails(
- &load_latest_signed_kernel()?,
- &load_latest_initrd_normal()?,
- /*trusted_public_key=*/ &[0u8; 0],
- AvbSlotVerifyError::PublicKeyRejected,
- )
- }
-
- #[test]
- fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
- assert_payload_verification_fails(
- &load_latest_signed_kernel()?,
- &load_latest_initrd_normal()?,
- /*trusted_public_key=*/ &[0u8; 512],
- AvbSlotVerifyError::PublicKeyRejected,
- )
- }
-
- #[test]
- fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
- assert_payload_verification_fails(
- &load_latest_signed_kernel()?,
- &load_latest_initrd_normal()?,
- &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
- AvbSlotVerifyError::PublicKeyRejected,
- )
- }
-
- #[test]
- fn unsigned_kernel_fails_verification() -> Result<()> {
- assert_payload_verification_fails(
- &fs::read(UNSIGNED_TEST_IMG_PATH)?,
- &load_latest_initrd_normal()?,
- &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
- AvbSlotVerifyError::Io,
- )
- }
-
- #[test]
- fn tampered_kernel_fails_verification() -> Result<()> {
- let mut kernel = load_latest_signed_kernel()?;
- kernel[1] = !kernel[1]; // Flip the bits
-
- assert_payload_verification_fails(
- &kernel,
- &load_latest_initrd_normal()?,
- &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
- AvbSlotVerifyError::Verification,
- )
- }
-
- #[test]
- fn tampered_kernel_footer_fails_verification() -> Result<()> {
- let mut kernel = load_latest_signed_kernel()?;
- let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
- kernel[avb_footer_index] = !kernel[avb_footer_index];
-
- assert_payload_verification_fails(
- &kernel,
- &load_latest_initrd_normal()?,
- &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
- AvbSlotVerifyError::InvalidMetadata,
- )
- }
-
- fn assert_payload_verification_fails(
- kernel: &[u8],
- initrd: &[u8],
- trusted_public_key: &[u8],
- expected_error: AvbSlotVerifyError,
- ) -> Result<()> {
- assert_eq!(Err(expected_error), verify_payload(kernel, Some(initrd), trusted_public_key));
- Ok(())
- }
-
- fn load_latest_signed_kernel() -> Result<Vec<u8>> {
- Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
- }
-
- fn load_latest_initrd_normal() -> Result<Vec<u8>> {
- Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
- }
+ let debug_level = if payload.verify_partition(PartitionName::InitrdNormal.as_cstr()).is_ok() {
+ DebugLevel::None
+ } else if payload.verify_partition(PartitionName::InitrdDebug.as_cstr()).is_ok() {
+ DebugLevel::Full
+ } else {
+ return Err(AvbSlotVerifyError::Verification);
+ };
+ Ok(debug_level)
}
diff --git a/pvmfw/avb/tests/api_test.rs b/pvmfw/avb/tests/api_test.rs
new file mode 100644
index 0000000..41ead59
--- /dev/null
+++ b/pvmfw/avb/tests/api_test.rs
@@ -0,0 +1,283 @@
+/*
+ * Copyright (C) 2022 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.
+ */
+
+mod utils;
+
+use anyhow::Result;
+use avb_bindgen::{AvbFooter, AvbVBMetaImageHeader};
+use pvmfw_avb::{AvbSlotVerifyError, DebugLevel};
+use std::{fs, mem::size_of, ptr};
+use utils::*;
+
+const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
+const TEST_IMG_WITH_PROP_DESC_PATH: &str = "test_image_with_prop_desc.img";
+const TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH: &str = "test_image_with_non_initrd_hashdesc.img";
+const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
+
+const RANDOM_FOOTER_POS: usize = 30;
+
+/// This test uses the Microdroid payload compiled on the fly to check that
+/// the latest payload can be verified successfully.
+#[test]
+fn latest_normal_payload_passes_verification() -> Result<()> {
+ assert_payload_verification_with_initrd_eq(
+ &load_latest_signed_kernel()?,
+ &load_latest_initrd_normal()?,
+ &load_trusted_public_key()?,
+ Ok(DebugLevel::None),
+ )
+}
+
+#[test]
+fn latest_debug_payload_passes_verification() -> Result<()> {
+ assert_payload_verification_with_initrd_eq(
+ &load_latest_signed_kernel()?,
+ &load_latest_initrd_debug()?,
+ &load_trusted_public_key()?,
+ Ok(DebugLevel::Full),
+ )
+}
+
+#[test]
+fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
+ assert_payload_verification_eq(
+ &fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?,
+ /*initrd=*/ None,
+ &load_trusted_public_key()?,
+ Ok(DebugLevel::None),
+ )
+}
+
+#[test]
+fn payload_with_non_initrd_descriptor_passes_verification_with_no_initrd() -> Result<()> {
+ assert_payload_verification_eq(
+ &fs::read(TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH)?,
+ /*initrd=*/ None,
+ &load_trusted_public_key()?,
+ Ok(DebugLevel::None),
+ )
+}
+
+#[test]
+fn payload_with_prop_descriptor_fails_verification_with_no_initrd() -> Result<()> {
+ assert_payload_verification_eq(
+ &fs::read(TEST_IMG_WITH_PROP_DESC_PATH)?,
+ /*initrd=*/ None,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::InvalidMetadata),
+ )
+}
+
+#[test]
+fn payload_expecting_initrd_fails_verification_with_no_initrd() -> Result<()> {
+ assert_payload_verification_eq(
+ &load_latest_signed_kernel()?,
+ /*initrd=*/ None,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::InvalidMetadata),
+ )
+}
+
+#[test]
+fn payload_with_empty_public_key_fails_verification() -> Result<()> {
+ assert_payload_verification_with_initrd_eq(
+ &load_latest_signed_kernel()?,
+ &load_latest_initrd_normal()?,
+ /*trusted_public_key=*/ &[0u8; 0],
+ Err(AvbSlotVerifyError::PublicKeyRejected),
+ )
+}
+
+#[test]
+fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
+ assert_payload_verification_with_initrd_eq(
+ &load_latest_signed_kernel()?,
+ &load_latest_initrd_normal()?,
+ /*trusted_public_key=*/ &[0u8; 512],
+ Err(AvbSlotVerifyError::PublicKeyRejected),
+ )
+}
+
+#[test]
+fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
+ assert_payload_verification_with_initrd_eq(
+ &load_latest_signed_kernel()?,
+ &load_latest_initrd_normal()?,
+ &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
+ Err(AvbSlotVerifyError::PublicKeyRejected),
+ )
+}
+
+#[test]
+fn payload_with_an_invalid_initrd_fails_verification() -> Result<()> {
+ assert_payload_verification_with_initrd_eq(
+ &load_latest_signed_kernel()?,
+ /*initrd=*/ &fs::read(UNSIGNED_TEST_IMG_PATH)?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::Verification),
+ )
+}
+
+#[test]
+fn unsigned_kernel_fails_verification() -> Result<()> {
+ assert_payload_verification_with_initrd_eq(
+ &fs::read(UNSIGNED_TEST_IMG_PATH)?,
+ &load_latest_initrd_normal()?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::Io),
+ )
+}
+
+#[test]
+fn tampered_kernel_fails_verification() -> Result<()> {
+ let mut kernel = load_latest_signed_kernel()?;
+ kernel[1] = !kernel[1]; // Flip the bits
+
+ assert_payload_verification_with_initrd_eq(
+ &kernel,
+ &load_latest_initrd_normal()?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::Verification),
+ )
+}
+
+#[test]
+fn kernel_footer_with_vbmeta_offset_overwritten_fails_verification() -> Result<()> {
+ // Arrange.
+ let mut kernel = load_latest_signed_kernel()?;
+ let total_len = kernel.len() as u64;
+ let footer = extract_avb_footer(&kernel)?;
+ assert!(footer.vbmeta_offset < total_len);
+ let vbmeta_offset_addr = ptr::addr_of!(footer.vbmeta_offset) as *const u8;
+ // SAFETY: It is safe as both raw pointers `vbmeta_offset_addr` and `footer` are not null.
+ let vbmeta_offset_start =
+ unsafe { vbmeta_offset_addr.offset_from(ptr::addr_of!(footer) as *const u8) };
+ let footer_start = kernel.len() - size_of::<AvbFooter>();
+ let vbmeta_offset_start = footer_start + usize::try_from(vbmeta_offset_start)?;
+
+ let wrong_offsets = [total_len, u64::MAX];
+ for &wrong_offset in wrong_offsets.iter() {
+ // Act.
+ kernel[vbmeta_offset_start..(vbmeta_offset_start + size_of::<u64>())]
+ .copy_from_slice(&wrong_offset.to_be_bytes());
+
+ // Assert.
+ let footer = extract_avb_footer(&kernel)?;
+ assert_eq!(wrong_offset, footer.vbmeta_offset as u64);
+ assert_payload_verification_with_initrd_eq(
+ &kernel,
+ &load_latest_initrd_normal()?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::Io),
+ )?;
+ }
+ Ok(())
+}
+
+#[test]
+fn tampered_kernel_footer_fails_verification() -> Result<()> {
+ let mut kernel = load_latest_signed_kernel()?;
+ let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
+ kernel[avb_footer_index] = !kernel[avb_footer_index];
+
+ assert_payload_verification_with_initrd_eq(
+ &kernel,
+ &load_latest_initrd_normal()?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::InvalidMetadata),
+ )
+}
+
+#[test]
+fn tampered_vbmeta_fails_verification() -> Result<()> {
+ let mut kernel = load_latest_signed_kernel()?;
+ let footer = extract_avb_footer(&kernel)?;
+ let vbmeta_index: usize = (footer.vbmeta_offset + 1).try_into()?;
+
+ kernel[vbmeta_index] = !kernel[vbmeta_index]; // Flip the bits
+
+ assert_payload_verification_with_initrd_eq(
+ &kernel,
+ &load_latest_initrd_normal()?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::InvalidMetadata),
+ )
+}
+
+#[test]
+fn vbmeta_with_public_key_overwritten_fails_verification() -> Result<()> {
+ let mut kernel = load_latest_signed_kernel()?;
+ let footer = extract_avb_footer(&kernel)?;
+ let vbmeta_header = extract_vbmeta_header(&kernel, &footer)?;
+ let public_key_offset = footer.vbmeta_offset as usize
+ + size_of::<AvbVBMetaImageHeader>()
+ + vbmeta_header.authentication_data_block_size as usize
+ + vbmeta_header.public_key_offset as usize;
+ let public_key_size: usize = vbmeta_header.public_key_size.try_into()?;
+ let empty_public_key = vec![0u8; public_key_size];
+
+ kernel[public_key_offset..(public_key_offset + public_key_size)]
+ .copy_from_slice(&empty_public_key);
+
+ assert_payload_verification_with_initrd_eq(
+ &kernel,
+ &load_latest_initrd_normal()?,
+ &empty_public_key,
+ Err(AvbSlotVerifyError::Verification),
+ )?;
+ assert_payload_verification_with_initrd_eq(
+ &kernel,
+ &load_latest_initrd_normal()?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::Verification),
+ )
+}
+
+#[test]
+fn vbmeta_with_verification_flag_disabled_fails_verification() -> Result<()> {
+ // From external/avb/libavb/avb_vbmeta_image.h
+ const AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED: u32 = 2;
+
+ // Arrange.
+ let mut kernel = load_latest_signed_kernel()?;
+ let footer = extract_avb_footer(&kernel)?;
+ let vbmeta_header = extract_vbmeta_header(&kernel, &footer)?;
+ assert_eq!(
+ 0, vbmeta_header.flags as u32,
+ "The disable flag should not be set in the latest kernel."
+ );
+ let flags_addr = ptr::addr_of!(vbmeta_header.flags) as *const u8;
+ // SAFETY: It is safe as both raw pointers `flags_addr` and `vbmeta_header` are not null.
+ let flags_offset = unsafe { flags_addr.offset_from(ptr::addr_of!(vbmeta_header) as *const u8) };
+ let flags_offset = usize::try_from(footer.vbmeta_offset)? + usize::try_from(flags_offset)?;
+
+ // Act.
+ kernel[flags_offset..(flags_offset + size_of::<u32>())]
+ .copy_from_slice(&AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED.to_be_bytes());
+
+ // Assert.
+ let vbmeta_header = extract_vbmeta_header(&kernel, &footer)?;
+ assert_eq!(
+ AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED, vbmeta_header.flags as u32,
+ "VBMeta verification flag should be disabled now."
+ );
+ assert_payload_verification_with_initrd_eq(
+ &kernel,
+ &load_latest_initrd_normal()?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::Verification),
+ )
+}
diff --git a/pvmfw/avb/tests/utils.rs b/pvmfw/avb/tests/utils.rs
new file mode 100644
index 0000000..0d9657e
--- /dev/null
+++ b/pvmfw/avb/tests/utils.rs
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 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.
+ */
+
+//! Utility methods used by API tests.
+
+use anyhow::Result;
+use avb_bindgen::{
+ avb_footer_validate_and_byteswap, avb_vbmeta_image_header_to_host_byte_order, AvbFooter,
+ AvbVBMetaImageHeader,
+};
+use pvmfw_avb::{verify_payload, AvbSlotVerifyError, DebugLevel};
+use std::{
+ fs,
+ mem::{size_of, transmute, MaybeUninit},
+};
+
+const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
+const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
+const INITRD_DEBUG_IMG_PATH: &str = "microdroid_initrd_debuggable.img";
+const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
+
+pub const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
+
+pub fn assert_payload_verification_with_initrd_eq(
+ kernel: &[u8],
+ initrd: &[u8],
+ trusted_public_key: &[u8],
+ expected_result: Result<DebugLevel, AvbSlotVerifyError>,
+) -> Result<()> {
+ assert_payload_verification_eq(kernel, Some(initrd), trusted_public_key, expected_result)
+}
+
+pub fn assert_payload_verification_eq(
+ kernel: &[u8],
+ initrd: Option<&[u8]>,
+ trusted_public_key: &[u8],
+ expected_result: Result<DebugLevel, AvbSlotVerifyError>,
+) -> Result<()> {
+ assert_eq!(expected_result, verify_payload(kernel, initrd, trusted_public_key));
+ Ok(())
+}
+
+pub fn load_latest_signed_kernel() -> Result<Vec<u8>> {
+ Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
+}
+
+pub fn load_latest_initrd_normal() -> Result<Vec<u8>> {
+ Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
+}
+
+pub fn load_latest_initrd_debug() -> Result<Vec<u8>> {
+ Ok(fs::read(INITRD_DEBUG_IMG_PATH)?)
+}
+
+pub fn load_trusted_public_key() -> Result<Vec<u8>> {
+ Ok(fs::read(PUBLIC_KEY_RSA4096_PATH)?)
+}
+
+pub fn extract_avb_footer(kernel: &[u8]) -> Result<AvbFooter> {
+ let footer_start = kernel.len() - size_of::<AvbFooter>();
+ // SAFETY: The slice is the same size as the struct which only contains simple data types.
+ let mut footer = unsafe {
+ transmute::<[u8; size_of::<AvbFooter>()], AvbFooter>(kernel[footer_start..].try_into()?)
+ };
+ // SAFETY: The function updates the struct in-place.
+ unsafe {
+ avb_footer_validate_and_byteswap(&footer, &mut footer);
+ }
+ Ok(footer)
+}
+
+pub fn extract_vbmeta_header(kernel: &[u8], footer: &AvbFooter) -> Result<AvbVBMetaImageHeader> {
+ let vbmeta_offset: usize = footer.vbmeta_offset.try_into()?;
+ let vbmeta_size: usize = footer.vbmeta_size.try_into()?;
+ let vbmeta_src = &kernel[vbmeta_offset..(vbmeta_offset + vbmeta_size)];
+ // SAFETY: The latest kernel has a valid VBMeta header at the position specified in footer.
+ let vbmeta_header = unsafe {
+ let mut header = MaybeUninit::uninit();
+ let src = vbmeta_src.as_ptr() as *const _ as *const AvbVBMetaImageHeader;
+ avb_vbmeta_image_header_to_host_byte_order(src, header.as_mut_ptr());
+ header.assume_init()
+ };
+ Ok(vbmeta_header)
+}
diff --git a/pvmfw/src/heap.rs b/pvmfw/src/heap.rs
index e412f69..acc903a 100644
--- a/pvmfw/src/heap.rs
+++ b/pvmfw/src/heap.rs
@@ -30,7 +30,7 @@
#[global_allocator]
static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();
-static mut HEAP: [u8; 65536] = [0; 65536];
+static mut HEAP: [u8; 131072] = [0; 131072];
pub unsafe fn init() {
HEAP_ALLOCATOR.lock().init(HEAP.as_mut_ptr() as usize, HEAP.len());
diff --git a/pvmfw/src/main.rs b/pvmfw/src/main.rs
index d0fdd5a..8633595 100644
--- a/pvmfw/src/main.rs
+++ b/pvmfw/src/main.rs
@@ -33,8 +33,8 @@
mod memory;
mod mmio_guard;
mod mmu;
-mod pci;
mod smccc;
+mod virtio;
use alloc::boxed::Box;
@@ -46,7 +46,7 @@
helpers::flush,
helpers::GUEST_PAGE_SIZE,
memory::MemoryTracker,
- pci::{find_virtio_devices, map_mmio},
+ virtio::pci::{find_virtio_devices, map_mmio},
};
use ::dice::bcc;
use fdtpci::{PciError, PciInfo};
diff --git a/pvmfw/src/memory.rs b/pvmfw/src/memory.rs
index 5e4874f..604aa80 100644
--- a/pvmfw/src/memory.rs
+++ b/pvmfw/src/memory.rs
@@ -14,16 +14,23 @@
//! Low-level allocation and tracking of main memory.
-use crate::helpers::{self, align_down, page_4kb_of, SIZE_4KB};
+#![deny(unsafe_op_in_unsafe_fn)]
+
+use crate::helpers::{self, align_down, align_up, page_4kb_of, SIZE_4KB};
use crate::hvc::{hyp_meminfo, mem_share, mem_unshare};
use crate::mmio_guard;
use crate::mmu;
use crate::smccc;
+use alloc::alloc::alloc_zeroed;
+use alloc::alloc::dealloc;
+use alloc::alloc::handle_alloc_error;
+use core::alloc::Layout;
use core::cmp::max;
use core::cmp::min;
use core::fmt;
use core::num::NonZeroUsize;
use core::ops::Range;
+use core::ptr::NonNull;
use core::result;
use log::error;
use tinyvec::ArrayVec;
@@ -272,9 +279,7 @@
/// Gives the KVM host read, write and execute permissions on the given memory range. If the range
/// is not aligned with the memory protection granule then it will be extended on either end to
/// align.
-#[allow(unused)]
-pub fn share_range(range: &MemoryRange) -> smccc::Result<()> {
- let granule = hyp_meminfo()? as usize;
+fn share_range(range: &MemoryRange, granule: usize) -> smccc::Result<()> {
for base in (align_down(range.start, granule)
.expect("Memory protection granule was not a power of two")..range.end)
.step_by(granule)
@@ -287,9 +292,7 @@
/// Removes permission from the KVM host to access the given memory range which was previously
/// shared. If the range is not aligned with the memory protection granule then it will be extended
/// on either end to align.
-#[allow(unused)]
-pub fn unshare_range(range: &MemoryRange) -> smccc::Result<()> {
- let granule = hyp_meminfo()? as usize;
+fn unshare_range(range: &MemoryRange, granule: usize) -> smccc::Result<()> {
for base in (align_down(range.start, granule)
.expect("Memory protection granule was not a power of two")..range.end)
.step_by(granule)
@@ -299,7 +302,78 @@
Ok(())
}
+/// Allocates a memory range of at least the given size from the global allocator, and shares it
+/// with the host. Returns a pointer to the buffer.
+///
+/// It will be aligned to the memory sharing granule size supported by the hypervisor.
+pub fn alloc_shared(size: usize) -> smccc::Result<NonNull<u8>> {
+ let layout = shared_buffer_layout(size)?;
+ let granule = layout.align();
+
+ // Safe because `shared_buffer_layout` panics if the size is 0, so the layout must have a
+ // non-zero size.
+ let buffer = unsafe { alloc_zeroed(layout) };
+
+ // TODO: Use let-else once we have Rust 1.65 in AOSP.
+ let buffer = if let Some(buffer) = NonNull::new(buffer) {
+ buffer
+ } else {
+ handle_alloc_error(layout);
+ };
+
+ let vaddr = buffer.as_ptr() as usize;
+ let paddr = virt_to_phys(vaddr);
+ // If share_range fails then we will leak the allocation, but that seems better than having it
+ // be reused while maybe still partially shared with the host.
+ share_range(&(paddr..paddr + layout.size()), granule)?;
+
+ Ok(buffer)
+}
+
+/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
+///
+/// The size passed in must be the size passed to the original `alloc_shared` call.
+///
+/// # Safety
+///
+/// The memory must have been allocated by `alloc_shared` with the same size, and not yet
+/// deallocated.
+pub unsafe fn dealloc_shared(vaddr: usize, size: usize) -> smccc::Result<()> {
+ let layout = shared_buffer_layout(size)?;
+ let granule = layout.align();
+
+ let paddr = virt_to_phys(vaddr);
+ unshare_range(&(paddr..paddr + layout.size()), granule)?;
+ // Safe because the memory was allocated by `alloc_shared` above using the same allocator, and
+ // the layout is the same as was used then.
+ unsafe { dealloc(vaddr as *mut u8, layout) };
+
+ Ok(())
+}
+
+/// Returns the layout to use for allocating a buffer of at least the given size shared with the
+/// host.
+///
+/// It will be aligned to the memory sharing granule size supported by the hypervisor.
+///
+/// Panics if `size` is 0.
+fn shared_buffer_layout(size: usize) -> smccc::Result<Layout> {
+ assert_ne!(size, 0);
+ let granule = hyp_meminfo()? as usize;
+ let allocated_size =
+ align_up(size, granule).expect("Memory protection granule was not a power of two");
+ Ok(Layout::from_size_align(allocated_size, granule).unwrap())
+}
+
/// Returns an iterator which yields the base address of each 4 KiB page within the given range.
fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> {
(page_4kb_of(range.start)..range.end).step_by(SIZE_4KB)
}
+
+/// Returns the intermediate physical address corresponding to the given virtual address.
+///
+/// As we use identity mapping for everything, this is just the identity function, but it's useful
+/// to use it to be explicit about where we are converting from virtual to physical address.
+pub fn virt_to_phys(vaddr: usize) -> usize {
+ vaddr
+}
diff --git a/pvmfw/src/virtio.rs b/pvmfw/src/virtio.rs
new file mode 100644
index 0000000..df916bc
--- /dev/null
+++ b/pvmfw/src/virtio.rs
@@ -0,0 +1,18 @@
+// Copyright 2022, 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.
+
+//! Modules for working with VirtIO devices.
+
+mod hal;
+pub mod pci;
diff --git a/pvmfw/src/virtio/hal.rs b/pvmfw/src/virtio/hal.rs
new file mode 100644
index 0000000..c1c8ae6
--- /dev/null
+++ b/pvmfw/src/virtio/hal.rs
@@ -0,0 +1,71 @@
+use crate::memory::{alloc_shared, dealloc_shared, virt_to_phys};
+use core::ptr::{copy_nonoverlapping, NonNull};
+use log::debug;
+use virtio_drivers::{BufferDirection, Hal, PhysAddr, VirtAddr, PAGE_SIZE};
+
+pub struct HalImpl;
+
+impl Hal for HalImpl {
+ fn dma_alloc(pages: usize) -> PhysAddr {
+ debug!("dma_alloc: pages={}", pages);
+ let size = pages * PAGE_SIZE;
+ let vaddr = alloc_shared(size)
+ .expect("Failed to allocate and share VirtIO DMA range with host")
+ .as_ptr() as VirtAddr;
+ virt_to_phys(vaddr)
+ }
+
+ fn dma_dealloc(paddr: PhysAddr, pages: usize) -> i32 {
+ debug!("dma_dealloc: paddr={:#x}, pages={}", paddr, pages);
+ let vaddr = Self::phys_to_virt(paddr);
+ let size = pages * PAGE_SIZE;
+ // Safe because the memory was allocated by `dma_alloc` above using the same allocator, and
+ // the layout is the same as was used then.
+ unsafe {
+ dealloc_shared(vaddr, size).expect("Failed to unshare VirtIO DMA range with host");
+ }
+ 0
+ }
+
+ fn phys_to_virt(paddr: PhysAddr) -> VirtAddr {
+ paddr
+ }
+
+ fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr {
+ let size = buffer.len();
+
+ // TODO: Copy to a pre-shared region rather than allocating and sharing each time.
+ // Allocate a range of pages, copy the buffer if necessary, and share the new range instead.
+ let copy =
+ alloc_shared(size).expect("Failed to allocate and share VirtIO buffer with host");
+ if direction == BufferDirection::DriverToDevice {
+ unsafe {
+ copy_nonoverlapping(buffer.as_ptr() as *mut u8, copy.as_ptr(), size);
+ }
+ }
+ virt_to_phys(copy.as_ptr() as VirtAddr)
+ }
+
+ fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection) {
+ let vaddr = Self::phys_to_virt(paddr);
+ let size = buffer.len();
+ if direction == BufferDirection::DeviceToDriver {
+ debug!(
+ "Copying VirtIO buffer back from {:#x} to {:#x}.",
+ paddr,
+ buffer.as_ptr() as *mut u8 as usize
+ );
+ unsafe {
+ copy_nonoverlapping(vaddr as *const u8, buffer.as_ptr() as *mut u8, size);
+ }
+ }
+
+ // Unshare and deallocate the shared copy of the buffer.
+ debug!("Unsharing VirtIO buffer {:#x}", paddr);
+ // Safe because the memory was allocated by `share` using `alloc_shared`, and the size is
+ // the same as was used then.
+ unsafe {
+ dealloc_shared(vaddr, size).expect("Failed to unshare VirtIO buffer with host");
+ }
+ }
+}
diff --git a/pvmfw/src/pci.rs b/pvmfw/src/virtio/pci.rs
similarity index 66%
rename from pvmfw/src/pci.rs
rename to pvmfw/src/virtio/pci.rs
index 2b81772..f9d36c6 100644
--- a/pvmfw/src/pci.rs
+++ b/pvmfw/src/virtio/pci.rs
@@ -14,10 +14,17 @@
//! Functions to scan the PCI bus for VirtIO devices.
+use super::hal::HalImpl;
use crate::{entry::RebootReason, memory::MemoryTracker};
use fdtpci::{PciError, PciInfo};
-use log::{debug, error};
-use virtio_drivers::transport::pci::{bus::PciRoot, virtio_device_type};
+use log::{debug, error, info};
+use virtio_drivers::{
+ device::blk::VirtIOBlk,
+ transport::{
+ pci::{bus::PciRoot, virtio_device_type, PciTransport},
+ DeviceType, Transport,
+ },
+};
/// Maps the CAM and BAR range in the page table and MMIO guard.
pub fn map_mmio(pci_info: &PciInfo, memory: &mut MemoryTracker) -> Result<(), RebootReason> {
@@ -46,6 +53,19 @@
);
if let Some(virtio_type) = virtio_device_type(&info) {
debug!(" VirtIO {:?}", virtio_type);
+ let mut transport = PciTransport::new::<HalImpl>(pci_root, device_function).unwrap();
+ info!(
+ "Detected virtio PCI device with device type {:?}, features {:#018x}",
+ transport.device_type(),
+ transport.read_device_features(),
+ );
+ if virtio_type == DeviceType::Block {
+ let mut blk =
+ VirtIOBlk::<HalImpl, _>::new(transport).expect("failed to create blk driver");
+ info!("Found {} KiB block device.", blk.capacity() * 512 / 1024);
+ let mut data = [0; 512];
+ blk.read_block(0, &mut data).expect("Failed to read block device");
+ }
}
}
diff --git a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
index e8a36ce..f1da43a 100644
--- a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
+++ b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
@@ -140,12 +140,6 @@
}
}
- protected enum EncryptedStoreOperation {
- NONE,
- READ,
- WRITE,
- }
-
public abstract static class VmEventListener implements VirtualMachineCallback {
private ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
private OptionalLong mVcpuStartedNanoTime = OptionalLong.empty();
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 2ee33e6..87129bb 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -75,6 +75,7 @@
import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@@ -96,6 +97,8 @@
private static final int BOOT_COMPLETE_TIMEOUT = 30000; // 30 seconds
+ private static final Pattern sCIDPattern = Pattern.compile("with CID (\\d+)");
+
private static class VmInfo {
final Process mProcess;
final String mCid;
@@ -387,16 +390,23 @@
return new VmInfo(process, extractCidFrom(pis));
}
+ private static Optional<String> tryExtractCidFrom(String str) {
+ Matcher matcher = sCIDPattern.matcher(str);
+ if (matcher.find()) {
+ return Optional.of(matcher.group(1));
+ }
+ return Optional.empty();
+ }
+
private static String extractCidFrom(InputStream input) throws IOException {
String cid = null;
- Pattern pattern = Pattern.compile("with CID (\\d+)");
String line;
try (BufferedReader out = new BufferedReader(new InputStreamReader(input))) {
while ((line = out.readLine()) != null) {
CLog.i("VM output: " + line);
- Matcher matcher = pattern.matcher(line);
- if (matcher.find()) {
- cid = matcher.group(1);
+ Optional<String> result = tryExtractCidFrom(line);
+ if (result.isPresent()) {
+ cid = result.get();
break;
}
}
@@ -518,7 +528,7 @@
"-m",
"1",
"-e",
- "'virtualizationservice::crosvm.*exited with status exit status:'");
+ "'virtualizationmanager::crosvm.*exited with status exit status:'");
// Check that tombstone is received (from host logcat)
String ramdumpRegex =
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 5c3be5f..e1a2e40 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -50,6 +50,7 @@
import com.android.microdroid.test.device.MicrodroidDeviceTestBase;
import com.android.microdroid.testservice.ITestService;
+import com.google.common.base.Strings;
import com.google.common.truth.BooleanSubject;
import org.junit.After;
@@ -76,6 +77,8 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalLong;
@@ -132,7 +135,16 @@
.build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
- TestResults testResults = runVmTestService(vm);
+ TestResults testResults =
+ runVmTestService(
+ vm,
+ (ts, tr) -> {
+ tr.mAddInteger = ts.addInteger(123, 456);
+ tr.mAppRunProp = ts.readProperty("debug.microdroid.app.run");
+ tr.mSublibRunProp = ts.readProperty("debug.microdroid.app.sublib.run");
+ tr.mApkContentsPath = ts.getApkContentsPath();
+ tr.mEncryptedStoragePath = ts.getEncryptedStoragePath();
+ });
assertThat(testResults.mException).isNull();
assertThat(testResults.mAddInteger).isEqualTo(123 + 456);
assertThat(testResults.mAppRunProp).isEqualTo("true");
@@ -157,8 +169,14 @@
.build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
- TestResults testResults = runVmTestService(vm);
+ TestResults testResults =
+ runVmTestService(
+ vm,
+ (ts, tr) -> {
+ tr.mAddInteger = ts.addInteger(37, 73);
+ });
assertThat(testResults.mException).isNull();
+ assertThat(testResults.mAddInteger).isEqualTo(37 + 73);
}
@Test
@@ -590,7 +608,8 @@
VirtualMachine vm =
forceCreateNewVirtualMachine("test_vm_config_requires_permission", config);
- SecurityException e = assertThrows(SecurityException.class, () -> runVmTestService(vm));
+ SecurityException e =
+ assertThrows(SecurityException.class, () -> runVmTestService(vm, (ts, tr) -> {}));
assertThat(e).hasMessageThat()
.contains("android.permission.USE_CUSTOM_VIRTUAL_MACHINE permission");
}
@@ -639,8 +658,14 @@
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_explicit_apk_path", config);
- TestResults testResults = runVmTestService(vm);
+ TestResults testResults =
+ runVmTestService(
+ vm,
+ (ts, tr) -> {
+ tr.mApkContentsPath = ts.getApkContentsPath();
+ });
assertThat(testResults.mException).isNull();
+ assertThat(testResults.mApkContentsPath).isEqualTo("/mnt/apk");
}
@Test
@@ -668,7 +693,13 @@
.build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_extra_apk", config);
- TestResults testResults = runVmTestService(vm);
+ TestResults testResults =
+ runVmTestService(
+ vm,
+ (ts, tr) -> {
+ tr.mExtraApkTestProp =
+ ts.readProperty("debug.microdroid.test.extra_apk");
+ });
assertThat(testResults.mExtraApkTestProp).isEqualTo("PASS");
}
@@ -1142,13 +1173,21 @@
newVmConfigBuilder()
.setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_FULL);
- if (encryptedStoreEnabled) builder = builder.setEncryptedStorageKib(4096);
+ if (encryptedStoreEnabled) {
+ builder.setEncryptedStorageKib(4096);
+ }
VirtualMachineConfig config = builder.build();
String vmNameOrig = "test_vm_orig";
String vmNameImport = "test_vm_import";
VirtualMachine vmOrig = forceCreateNewVirtualMachine(vmNameOrig, config);
// Run something to make the instance.img different with the initialized one.
- TestResults origTestResults = runVmTestService(vmOrig);
+ TestResults origTestResults =
+ runVmTestService(
+ vmOrig,
+ (ts, tr) -> {
+ tr.mAddInteger = ts.addInteger(123, 456);
+ tr.mEncryptedStoragePath = ts.getEncryptedStoragePath();
+ });
assertThat(origTestResults.mException).isNull();
assertThat(origTestResults.mAddInteger).isEqualTo(123 + 456);
VirtualMachineDescriptor descriptor = vmOrig.toDescriptor();
@@ -1169,7 +1208,13 @@
assertThat(vmImport).isNotEqualTo(vmOrig);
vmm.delete(vmNameOrig);
assertThat(vmImport).isEqualTo(vmm.get(vmNameImport));
- TestResults testResults = runVmTestService(vmImport);
+ TestResults testResults =
+ runVmTestService(
+ vmImport,
+ (ts, tr) -> {
+ tr.mAddInteger = ts.addInteger(123, 456);
+ tr.mEncryptedStoragePath = ts.getEncryptedStoragePath();
+ });
assertThat(testResults.mException).isNull();
assertThat(testResults.mAddInteger).isEqualTo(123 + 456);
return testResults;
@@ -1189,7 +1234,12 @@
.build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
- TestResults testResults = runVmTestService(vm);
+ TestResults testResults =
+ runVmTestService(
+ vm,
+ (ts, tr) -> {
+ tr.mEncryptedStoragePath = ts.getEncryptedStoragePath();
+ });
assertThat(testResults.mEncryptedStoragePath).isEqualTo("/mnt/encryptedstore");
}
@@ -1206,7 +1256,12 @@
.build();
final VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_caps", vmConfig);
- final TestResults testResults = runVmTestService(vm);
+ final TestResults testResults =
+ runVmTestService(
+ vm,
+ (ts, tr) -> {
+ tr.mEffectiveCapabilities = ts.getEffectiveCapabilities();
+ });
assertThat(testResults.mException).isNull();
assertThat(testResults.mEffectiveCapabilities).isEmpty();
@@ -1225,12 +1280,24 @@
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_a", config);
- TestResults testResults = runVmTestService(vm, EncryptedStoreOperation.WRITE);
+ TestResults testResults =
+ runVmTestService(
+ vm,
+ (ts, tr) -> {
+ ts.writeToFile(
+ /* content= */ EXAMPLE_STRING,
+ /* path= */ "/mnt/encryptedstore/test_file");
+ });
assertThat(testResults.mException).isNull();
// Re-run the same VM & verify the file persisted. Note, the previous `runVmTestService`
// stopped the VM
- testResults = runVmTestService(vm, EncryptedStoreOperation.READ);
+ testResults =
+ runVmTestService(
+ vm,
+ (ts, tr) -> {
+ tr.mFileContent = ts.readFromFile("/mnt/encryptedstore/test_file");
+ });
assertThat(testResults.mException).isNull();
assertThat(testResults.mFileContent).isEqualTo(EXAMPLE_STRING);
}
@@ -1260,7 +1327,7 @@
}
@Test
- public void outputsShouldBeExplicitlyForwarded() throws Exception {
+ public void outputShouldBeExplicitlyCaptured() throws Exception {
assumeSupportedKernel();
final VirtualMachineConfig vmConfig =
@@ -1282,6 +1349,57 @@
}
}
+ private boolean checkVmOutputIsRedirectedToLogcat(boolean debuggable) throws Exception {
+ String time =
+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
+ final VirtualMachineConfig vmConfig =
+ new VirtualMachineConfig.Builder(ApplicationProvider.getApplicationContext())
+ .setProtectedVm(mProtectedVm)
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
+ .setDebugLevel(debuggable ? DEBUG_LEVEL_FULL : DEBUG_LEVEL_NONE)
+ .setVmOutputCaptured(false)
+ .build();
+ final VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_logcat", vmConfig);
+
+ VmEventListener listener =
+ new VmEventListener() {
+ @Override
+ public void onPayloadStarted(VirtualMachine vm) {
+ forceStop(vm);
+ }
+ };
+ listener.runToFinish(TAG, vm);
+
+ // only check logs printed after this test
+ Process logcatProcess =
+ new ProcessBuilder()
+ .command(
+ "logcat",
+ "-e",
+ "virtualizationmanager::aidl: Console.*executing main task",
+ "-t",
+ time)
+ .start();
+ logcatProcess.waitFor();
+ BufferedReader reader =
+ new BufferedReader(new InputStreamReader(logcatProcess.getInputStream()));
+ return !Strings.isNullOrEmpty(reader.readLine());
+ }
+
+ @Test
+ public void outputIsRedirectedToLogcatIfNotCaptured() throws Exception {
+ assumeSupportedKernel();
+
+ assertThat(checkVmOutputIsRedirectedToLogcat(true)).isTrue();
+ }
+
+ @Test
+ public void outputIsNotRedirectedToLogcatIfNotDebuggable() throws Exception {
+ assumeSupportedKernel();
+
+ assertThat(checkVmOutputIsRedirectedToLogcat(false)).isFalse();
+ }
+
private void assertFileContentsAreEqualInTwoVms(String fileName, String vmName1, String vmName2)
throws IOException {
File file1 = getVmFile(vmName1, fileName);
@@ -1340,67 +1458,6 @@
String mFileContent;
}
- private TestResults runVmTestService(VirtualMachine vm) throws Exception {
- return runVmTestService(vm, EncryptedStoreOperation.NONE);
- }
-
- private TestResults runVmTestService(VirtualMachine vm, EncryptedStoreOperation mode)
- throws Exception {
- CompletableFuture<Boolean> payloadStarted = new CompletableFuture<>();
- CompletableFuture<Boolean> payloadReady = new CompletableFuture<>();
- TestResults testResults = new TestResults();
- VmEventListener listener =
- new VmEventListener() {
- private void testVMService(VirtualMachine vm) {
- try {
- ITestService testService =
- ITestService.Stub.asInterface(
- vm.connectToVsockServer(ITestService.SERVICE_PORT));
- testResults.mAddInteger = testService.addInteger(123, 456);
- testResults.mAppRunProp =
- testService.readProperty("debug.microdroid.app.run");
- testResults.mSublibRunProp =
- testService.readProperty("debug.microdroid.app.sublib.run");
- testResults.mExtraApkTestProp =
- testService.readProperty("debug.microdroid.test.extra_apk");
- testResults.mApkContentsPath = testService.getApkContentsPath();
- testResults.mEncryptedStoragePath =
- testService.getEncryptedStoragePath();
- testResults.mEffectiveCapabilities =
- testService.getEffectiveCapabilities();
- if (mode == EncryptedStoreOperation.WRITE) {
- testService.writeToFile(
- /*content*/ EXAMPLE_STRING,
- /*path*/ "/mnt/encryptedstore/test_file");
- } else if (mode == EncryptedStoreOperation.READ) {
- testResults.mFileContent =
- testService.readFromFile("/mnt/encryptedstore/test_file");
- }
- } catch (Exception e) {
- testResults.mException = e;
- }
- }
-
- @Override
- public void onPayloadReady(VirtualMachine vm) {
- Log.i(TAG, "onPayloadReady");
- payloadReady.complete(true);
- testVMService(vm);
- forceStop(vm);
- }
-
- @Override
- public void onPayloadStarted(VirtualMachine vm) {
- Log.i(TAG, "onPayloadStarted");
- payloadStarted.complete(true);
- }
- };
- listener.runToFinish(TAG, vm);
- assertThat(payloadStarted.getNow(false)).isTrue();
- assertThat(payloadReady.getNow(false)).isTrue();
- return testResults;
- }
-
private TestResults runVmTestService(VirtualMachine vm, RunTestsAgainstTestService testsToRun)
throws Exception {
CompletableFuture<Boolean> payloadStarted = new CompletableFuture<>();
diff --git a/virtualizationmanager/Android.bp b/virtualizationmanager/Android.bp
new file mode 100644
index 0000000..a436cea
--- /dev/null
+++ b/virtualizationmanager/Android.bp
@@ -0,0 +1,82 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_defaults {
+ name: "virtualizationmanager_defaults",
+ crate_name: "virtualizationmanager",
+ edition: "2021",
+ // Only build on targets which crosvm builds on.
+ enabled: false,
+ target: {
+ android64: {
+ compile_multilib: "64",
+ enabled: true,
+ },
+ linux_bionic_arm64: {
+ enabled: true,
+ },
+ },
+ prefer_rlib: true,
+ rustlibs: [
+ "android.system.virtualizationcommon-rust",
+ "android.system.virtualizationservice-rust",
+ "android.system.virtualizationservice_internal-rust",
+ "android.system.virtualmachineservice-rust",
+ "android.os.permissions_aidl-rust",
+ "libandroid_logger",
+ "libanyhow",
+ "libapkverify",
+ "libbase_rust",
+ "libbinder_rs",
+ "libclap",
+ "libcommand_fds",
+ "libdisk",
+ "liblazy_static",
+ "liblibc",
+ "liblog_rust",
+ "libmicrodroid_metadata",
+ "libmicrodroid_payload_config",
+ "libnested_virt",
+ "libnix",
+ "libonce_cell",
+ "libregex",
+ "librpcbinder_rs",
+ "librustutils",
+ "libsemver",
+ "libselinux_bindgen",
+ "libserde",
+ "libserde_json",
+ "libserde_xml_rs",
+ "libshared_child",
+ "libstatslog_virtualization_rust",
+ "libtombstoned_client_rust",
+ "libvm_control",
+ "libvmconfig",
+ "libzip",
+ "libvsock",
+ // TODO(b/202115393) stabilize the interface
+ "packagemanager_aidl-rust",
+ ],
+ shared_libs: [
+ "libbinder_rpc_unstable",
+ "libselinux",
+ ],
+}
+
+rust_binary {
+ name: "virtmgr",
+ defaults: ["virtualizationmanager_defaults"],
+ srcs: ["src/main.rs"],
+ apex_available: ["com.android.virt"],
+}
+
+rust_test {
+ name: "virtualizationmanager_device_test",
+ srcs: ["src/main.rs"],
+ defaults: ["virtualizationmanager_defaults"],
+ rustlibs: [
+ "libtempfile",
+ ],
+ test_suites: ["general-tests"],
+}
diff --git a/virtualizationmanager/TEST_MAPPING b/virtualizationmanager/TEST_MAPPING
new file mode 100644
index 0000000..a680f6d
--- /dev/null
+++ b/virtualizationmanager/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "avf-presubmit": [
+ {
+ "name": "virtualizationmanager_device_test"
+ }
+ ]
+}
diff --git a/virtualizationmanager/src/aidl.rs b/virtualizationmanager/src/aidl.rs
new file mode 100644
index 0000000..c827c2e
--- /dev/null
+++ b/virtualizationmanager/src/aidl.rs
@@ -0,0 +1,1178 @@
+// Copyright 2021, 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.
+
+//! 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::composite::make_composite_image;
+use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
+use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
+use crate::selinux::{getfilecon, SeContext};
+use android_os_permissions_aidl::aidl::android::os::IPermissionController;
+use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
+ DeathReason::DeathReason,
+ ErrorCode::ErrorCode,
+};
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
+ DiskImage::DiskImage,
+ IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
+ IVirtualMachineCallback::IVirtualMachineCallback,
+ IVirtualizationService::IVirtualizationService,
+ MemoryTrimLevel::MemoryTrimLevel,
+ Partition::Partition,
+ PartitionType::PartitionType,
+ VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
+ VirtualMachineConfig::VirtualMachineConfig,
+ VirtualMachineDebugInfo::VirtualMachineDebugInfo,
+ VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
+ VirtualMachineRawConfig::VirtualMachineRawConfig,
+ VirtualMachineState::VirtualMachineState,
+};
+use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
+use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
+ BnVirtualMachineService, IVirtualMachineService,
+};
+use anyhow::{bail, Context, Result};
+use apkverify::{HashAlgorithm, V4Signature};
+use binder::{
+ self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
+ Status, StatusCode, Strong,
+};
+use disk::QcowFile;
+use lazy_static::lazy_static;
+use log::{debug, error, info, warn};
+use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
+use nix::unistd::pipe;
+use rpcbinder::RpcServer;
+use semver::VersionReq;
+use std::convert::TryInto;
+use std::ffi::CStr;
+use std::fs::{read_dir, remove_file, File, OpenOptions};
+use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
+use std::num::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 vmconfig::VmConfig;
+use vsock::VsockStream;
+use zip::ZipArchive;
+
+/// The unique ID of a VM used (together with a port number) for vsock communication.
+pub type Cid = u32;
+
+pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
+
+/// The size of zero.img.
+/// Gaps in composite disk images are filled with a shared zero.img.
+const ZERO_FILLER_SIZE: u64 = 4096;
+
+/// Magic string for the instance image
+const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
+
+/// Version of the instance image format
+const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
+
+const MICRODROID_OS_NAME: &str = "microdroid";
+
+const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
+
+lazy_static! {
+ pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
+ wait_for_interface(BINDER_SERVICE_IDENTIFIER)
+ .expect("Could not connect to VirtualizationServiceInternal");
+}
+
+fn create_or_update_idsig_file(
+ input_fd: &ParcelFileDescriptor,
+ idsig_fd: &ParcelFileDescriptor,
+) -> Result<()> {
+ let mut input = clone_file(input_fd)?;
+ let metadata = input.metadata().context("failed to get input metadata")?;
+ if !metadata.is_file() {
+ bail!("input is not a regular file");
+ }
+ let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
+ .context("failed to create idsig")?;
+
+ let mut output = clone_file(idsig_fd)?;
+ output.set_len(0).context("failed to set_len on the idsig output")?;
+ sig.write_into(&mut output).context("failed to write idsig")?;
+ Ok(())
+}
+
+pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
+ for dir_entry in read_dir(path)? {
+ remove_file(dir_entry?.path())?;
+ }
+ Ok(())
+}
+
+/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
+#[derive(Debug, Default)]
+pub struct VirtualizationService {
+ state: Arc<Mutex<State>>,
+}
+
+impl Interface for VirtualizationService {
+ fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
+ check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
+ let state = &mut *self.state.lock().unwrap();
+ let vms = state.vms();
+ writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
+ for vm in vms {
+ writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
+ writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
+ .or(Err(StatusCode::UNKNOWN_ERROR))?;
+ writeln!(file, "\tPayload state {:?}", vm.payload_state())
+ .or(Err(StatusCode::UNKNOWN_ERROR))?;
+ writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
+ writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
+ .or(Err(StatusCode::UNKNOWN_ERROR))?;
+ writeln!(file, "\trequester_uid: {}", vm.requester_uid)
+ .or(Err(StatusCode::UNKNOWN_ERROR))?;
+ writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
+ .or(Err(StatusCode::UNKNOWN_ERROR))?;
+ }
+ Ok(())
+ }
+}
+
+impl IVirtualizationService for VirtualizationService {
+ /// Creates (but does not start) a new VM with the given configuration, assigning it the next
+ /// available CID.
+ ///
+ /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
+ fn createVm(
+ &self,
+ config: &VirtualMachineConfig,
+ console_fd: Option<&ParcelFileDescriptor>,
+ log_fd: Option<&ParcelFileDescriptor>,
+ ) -> binder::Result<Strong<dyn IVirtualMachine>> {
+ let mut is_protected = false;
+ let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
+ write_vm_creation_stats(config, is_protected, &ret);
+ ret
+ }
+
+ /// Initialise an empty partition image of the given size to be used as a writable partition.
+ fn initializeWritablePartition(
+ &self,
+ image_fd: &ParcelFileDescriptor,
+ size: i64,
+ partition_type: PartitionType,
+ ) -> binder::Result<()> {
+ check_manage_access()?;
+ let size = size.try_into().map_err(|e| {
+ Status::new_exception_str(
+ ExceptionCode::ILLEGAL_ARGUMENT,
+ Some(format!("Invalid size {}: {:?}", size, e)),
+ )
+ })?;
+ let image = clone_file(image_fd)?;
+ // initialize the file. Any data in the file will be erased.
+ image.set_len(0).map_err(|e| {
+ Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Failed to reset a file: {:?}", e)),
+ )
+ })?;
+ let mut part = QcowFile::new(image, size).map_err(|e| {
+ Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Failed to create QCOW2 image: {:?}", e)),
+ )
+ })?;
+
+ match partition_type {
+ PartitionType::RAW => Ok(()),
+ PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
+ PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
+ _ => Err(Error::new(
+ ErrorKind::Unsupported,
+ format!("Unsupported partition type {:?}", partition_type),
+ )),
+ }
+ .map_err(|e| {
+ Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
+ )
+ })?;
+
+ Ok(())
+ }
+
+ /// Creates or update the idsig file by digesting the input APK file.
+ fn createOrUpdateIdsigFile(
+ &self,
+ input_fd: &ParcelFileDescriptor,
+ idsig_fd: &ParcelFileDescriptor,
+ ) -> binder::Result<()> {
+ // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
+ // idsig_fd is different from APK digest in input_fd
+
+ check_manage_access()?;
+
+ create_or_update_idsig_file(input_fd, idsig_fd)
+ .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
+ Ok(())
+ }
+
+ /// Get a list of all currently running VMs. This method is only intended for debug purposes,
+ /// and as such is only permitted from the shell user.
+ fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
+ // Delegate to the global service, including checking the debug permission.
+ GLOBAL_SERVICE.debugListVms()
+ }
+}
+
+impl VirtualizationService {
+ pub fn init() -> VirtualizationService {
+ VirtualizationService::default()
+ }
+
+ fn create_vm_context(
+ &self,
+ requester_debug_pid: pid_t,
+ ) -> binder::Result<(VmContext, Cid, PathBuf)> {
+ const NUM_ATTEMPTS: usize = 5;
+
+ for _ in 0..NUM_ATTEMPTS {
+ let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid as i32)?;
+ let cid = vm_context.getCid()? as Cid;
+ let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
+ let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
+
+ // Start VM service listening for connections from the new CID on port=CID.
+ let port = cid;
+ match RpcServer::new_vsock(service, cid, port) {
+ Ok(vm_server) => {
+ vm_server.start();
+ return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
+ }
+ Err(err) => {
+ warn!("Could not start RpcServer on port {}: {}", port, err);
+ }
+ }
+ }
+ Err(Status::new_service_specific_error_str(
+ -1,
+ Some("Too many attempts to create VM context failed."),
+ ))
+ }
+
+ fn create_vm_internal(
+ &self,
+ config: &VirtualMachineConfig,
+ console_fd: Option<&ParcelFileDescriptor>,
+ log_fd: Option<&ParcelFileDescriptor>,
+ is_protected: &mut bool,
+ ) -> binder::Result<Strong<dyn IVirtualMachine>> {
+ let requester_uid = get_calling_uid();
+ let requester_debug_pid = get_calling_pid();
+
+ // 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:
+ // - controlling CPUs;
+ // - specifying a config file in the APK.
+ !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
+ }
+ };
+ if is_custom {
+ check_use_custom_virtual_machine()?;
+ }
+
+ let state = &mut *self.state.lock().unwrap();
+ let console_fd =
+ clone_or_prepare_logger_fd(config, console_fd, format!("Console({})", cid))?;
+ let log_fd = clone_or_prepare_logger_fd(config, log_fd, format!("Log({})", cid))?;
+
+ // Counter to generate unique IDs for temporary image files.
+ let mut next_temporary_image_id = 0;
+ // Files which are referred to from composite images. These must be mapped to the crosvm
+ // child process, and not closed before it is started.
+ let mut indirect_files = vec![];
+
+ let (is_app_config, config) = match config {
+ VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
+ VirtualMachineConfig::AppConfig(config) => {
+ let config = load_app_config(config, &temporary_directory).map_err(|e| {
+ *is_protected = config.protectedVm;
+ let message = format!("Failed to load app config: {:?}", e);
+ error!("{}", message);
+ Status::new_service_specific_error_str(-1, Some(message))
+ })?;
+ (true, BorrowedOrOwned::Owned(config))
+ }
+ };
+ let config = config.as_ref();
+ *is_protected = config.protectedVm;
+
+ // Check if partition images are labeled incorrectly. This is to prevent random images
+ // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
+ // being loaded in a pVM. This applies to everything in the raw config, and everything but
+ // the non-executable, generated partitions in the app config.
+ config
+ .disks
+ .iter()
+ .flat_map(|disk| disk.partitions.iter())
+ .filter(|partition| {
+ if is_app_config {
+ !is_safe_app_partition(&partition.label)
+ } else {
+ true // all partitions are checked
+ }
+ })
+ .try_for_each(check_label_for_partition)
+ .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
+
+ let kernel = maybe_clone_file(&config.kernel)?;
+ let initrd = maybe_clone_file(&config.initrd)?;
+
+ // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
+ if config.protectedVm {
+ check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
+ Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
+ })?;
+ }
+
+ let zero_filler_path = temporary_directory.join("zero.img");
+ write_zero_filler(&zero_filler_path).map_err(|e| {
+ error!("Failed to make composite image: {:?}", e);
+ Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Failed to make composite image: {:?}", e)),
+ )
+ })?;
+
+ // Assemble disk images if needed.
+ let disks = config
+ .disks
+ .iter()
+ .map(|disk| {
+ assemble_disk_image(
+ disk,
+ &zero_filler_path,
+ &temporary_directory,
+ &mut next_temporary_image_id,
+ &mut indirect_files,
+ )
+ })
+ .collect::<Result<Vec<DiskFile>, _>>()?;
+
+ // Creating this ramdump file unconditionally is not harmful as ramdump will be created
+ // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
+ // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
+ // will be sent back to the client (i.e. the VM owner) for readout.
+ let ramdump_path = temporary_directory.join("ramdump");
+ let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
+ error!("Failed to prepare ramdump file: {:?}", e);
+ Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Failed to prepare ramdump file: {:?}", e)),
+ )
+ })?;
+
+ // Actually start the VM.
+ let crosvm_config = CrosvmConfig {
+ cid,
+ name: config.name.clone(),
+ bootloader: maybe_clone_file(&config.bootloader)?,
+ kernel,
+ initrd,
+ disks,
+ params: config.params.to_owned(),
+ protected: *is_protected,
+ memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
+ cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
+ task_profiles: config.taskProfiles.clone(),
+ console_fd,
+ log_fd,
+ ramdump: Some(ramdump),
+ indirect_files,
+ platform_version: parse_platform_version_req(&config.platformVersion)?,
+ detect_hangup: is_app_config,
+ };
+ let instance = Arc::new(
+ VmInstance::new(
+ crosvm_config,
+ temporary_directory,
+ requester_uid,
+ requester_debug_pid,
+ vm_context,
+ )
+ .map_err(|e| {
+ error!("Failed to create VM with config {:?}: {:?}", config, e);
+ Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Failed to create VM: {:?}", e)),
+ )
+ })?,
+ );
+ state.add_vm(Arc::downgrade(&instance));
+ Ok(VirtualMachine::create(instance))
+ }
+}
+
+fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
+ let file = OpenOptions::new()
+ .create_new(true)
+ .read(true)
+ .write(true)
+ .open(zero_filler_path)
+ .with_context(|| "Failed to create zero.img")?;
+ file.set_len(ZERO_FILLER_SIZE)?;
+ Ok(())
+}
+
+fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
+ part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
+ part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
+ part.flush()
+}
+
+fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
+ part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
+ part.flush()
+}
+
+fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
+ File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
+}
+
+/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
+///
+/// This may involve assembling a composite disk from a set of partition images.
+fn assemble_disk_image(
+ disk: &DiskImage,
+ zero_filler_path: &Path,
+ temporary_directory: &Path,
+ next_temporary_image_id: &mut u64,
+ indirect_files: &mut Vec<File>,
+) -> Result<DiskFile, Status> {
+ let image = if !disk.partitions.is_empty() {
+ if disk.image.is_some() {
+ warn!("DiskImage {:?} contains both image and partitions.", disk);
+ return Err(Status::new_exception_str(
+ ExceptionCode::ILLEGAL_ARGUMENT,
+ Some("DiskImage contains both image and partitions."),
+ ));
+ }
+
+ let composite_image_filenames =
+ make_composite_image_filenames(temporary_directory, next_temporary_image_id);
+ let (image, partition_files) = make_composite_image(
+ &disk.partitions,
+ zero_filler_path,
+ &composite_image_filenames.composite,
+ &composite_image_filenames.header,
+ &composite_image_filenames.footer,
+ )
+ .map_err(|e| {
+ error!("Failed to make composite image with config {:?}: {:?}", disk, e);
+ Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Failed to make composite image: {:?}", e)),
+ )
+ })?;
+
+ // Pass the file descriptors for the various partition files to crosvm when it
+ // is run.
+ indirect_files.extend(partition_files);
+
+ image
+ } else if let Some(image) = &disk.image {
+ clone_file(image)?
+ } else {
+ warn!("DiskImage {:?} didn't contain image or partitions.", disk);
+ return Err(Status::new_exception_str(
+ ExceptionCode::ILLEGAL_ARGUMENT,
+ Some("DiskImage didn't contain image or partitions."),
+ ));
+ };
+
+ Ok(DiskFile { image, writable: disk.writable })
+}
+
+fn load_app_config(
+ config: &VirtualMachineAppConfig,
+ temporary_directory: &Path,
+) -> Result<VirtualMachineRawConfig> {
+ let apk_file = clone_file(config.apk.as_ref().unwrap())?;
+ let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
+ let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
+
+ let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
+ Some(clone_file(file)?)
+ } else {
+ None
+ };
+
+ let vm_payload_config = 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))?
+ }
+ Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
+ };
+
+ // For now, the only supported OS is Microdroid
+ let os_name = vm_payload_config.os.name.as_str();
+ if os_name != MICRODROID_OS_NAME {
+ bail!("Unknown OS \"{}\"", os_name);
+ }
+
+ // It is safe to construct a filename based on the os_name because we've already checked that it
+ // is one of the allowed values.
+ let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
+ let vm_config_file = File::open(vm_config_path)?;
+ let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
+
+ if config.memoryMib > 0 {
+ vm_config.memoryMib = config.memoryMib;
+ }
+
+ vm_config.name = config.name.clone();
+ vm_config.protectedVm = config.protectedVm;
+ vm_config.numCpus = config.numCpus;
+ vm_config.taskProfiles = config.taskProfiles.clone();
+
+ // Microdroid takes additional init ramdisk & (optionally) storage image
+ add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
+
+ // Include Microdroid payload disk (contains apks, idsigs) in vm config
+ add_microdroid_payload_images(
+ config,
+ temporary_directory,
+ apk_file,
+ idsig_file,
+ &vm_payload_config,
+ &mut vm_config,
+ )?;
+
+ Ok(vm_config)
+}
+
+fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
+ let mut apk_zip = ZipArchive::new(apk_file)?;
+ let config_file = apk_zip.by_name(config_path)?;
+ Ok(serde_json::from_reader(config_file)?)
+}
+
+fn create_vm_payload_config(
+ payload_config: &VirtualMachinePayloadConfig,
+) -> Result<VmPayloadConfig> {
+ // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
+ // parameters we've been given. Microdroid will do something equivalent inside the VM using the
+ // payload config that we send it via the metadata file.
+
+ let payload_binary_name = &payload_config.payloadBinaryName;
+ if payload_binary_name.contains('/') {
+ bail!("Payload binary name must not specify a path: {payload_binary_name}");
+ }
+
+ let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
+ Ok(VmPayloadConfig {
+ os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
+ task: Some(task),
+ apexes: vec![],
+ extra_apks: vec![],
+ prefer_staged: false,
+ export_tombstones: false,
+ enable_authfs: false,
+ })
+}
+
+/// Generates a unique filename to use for a composite disk image.
+fn make_composite_image_filenames(
+ temporary_directory: &Path,
+ next_temporary_image_id: &mut u64,
+) -> CompositeImageFilenames {
+ let id = *next_temporary_image_id;
+ *next_temporary_image_id += 1;
+ CompositeImageFilenames {
+ composite: temporary_directory.join(format!("composite-{}.img", id)),
+ header: temporary_directory.join(format!("composite-{}-header.img", id)),
+ footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
+ }
+}
+
+/// Filenames for a composite disk image, including header and footer partitions.
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct CompositeImageFilenames {
+ /// The composite disk image itself.
+ composite: PathBuf,
+ /// The header partition image.
+ header: PathBuf,
+ /// The footer partition image.
+ footer: PathBuf,
+}
+
+/// Checks whether the caller has a specific permission
+fn check_permission(perm: &str) -> binder::Result<()> {
+ let calling_pid = get_calling_pid();
+ let calling_uid = get_calling_uid();
+ // Root can do anything
+ if calling_uid == 0 {
+ return Ok(());
+ }
+ let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
+ binder::get_interface("permission")?;
+ if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
+ Ok(())
+ } else {
+ Err(Status::new_exception_str(
+ ExceptionCode::SECURITY,
+ Some(format!("does not have the {} permission", perm)),
+ ))
+ }
+}
+
+/// Check whether the caller of the current Binder method is allowed to manage VMs
+fn check_manage_access() -> binder::Result<()> {
+ check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
+}
+
+/// Check whether the caller of the current Binder method is allowed to create custom VMs
+fn check_use_custom_virtual_machine() -> binder::Result<()> {
+ check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
+}
+
+/// Return whether a partition is exempt from selinux label checks, because we know that it does
+/// not contain code and is likely to be generated in an app-writable directory.
+fn is_safe_app_partition(label: &str) -> bool {
+ // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
+ label == "vm-instance"
+ || label == "encryptedstore"
+ || label == "microdroid-apk-idsig"
+ || label == "payload-metadata"
+ || label.starts_with("extra-idsig-")
+}
+
+/// Check that a file SELinux label is acceptable.
+///
+/// We only want to allow code in a VM to be sourced from places that apps, and the
+/// system, do not have write access to.
+///
+/// Note that sepolicy must also grant read access for these types to both virtualization
+/// service and crosvm.
+///
+/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
+/// user devices (W^X).
+fn check_label_is_allowed(context: &SeContext) -> Result<()> {
+ match context.selinux_type()? {
+ | "system_file" // immutable dm-verity protected partition
+ | "apk_data_file" // APKs of an installed app
+ | "staging_data_file" // updated/staged APEX images
+ | "shell_data_file" // test files created via adb shell
+ => Ok(()),
+ _ => bail!("Label {} is not allowed", context),
+ }
+}
+
+fn check_label_for_partition(partition: &Partition) -> Result<()> {
+ let file = partition.image.as_ref().unwrap().as_ref();
+ check_label_is_allowed(&getfilecon(file)?)
+ .with_context(|| format!("Partition {} invalid", &partition.label))
+}
+
+fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
+ if let Some(f) = kernel {
+ check_label_for_file(f, "kernel")?;
+ }
+ if let Some(f) = initrd {
+ check_label_for_file(f, "initrd")?;
+ }
+ Ok(())
+}
+fn check_label_for_file(file: &File, name: &str) -> Result<()> {
+ check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
+}
+
+/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
+#[derive(Debug)]
+struct VirtualMachine {
+ instance: Arc<VmInstance>,
+}
+
+impl VirtualMachine {
+ fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
+ BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
+ }
+}
+
+impl Interface for VirtualMachine {}
+
+impl IVirtualMachine for VirtualMachine {
+ fn getCid(&self) -> binder::Result<i32> {
+ // Don't check permission. The owner of the VM might have passed this binder object to
+ // others.
+ Ok(self.instance.cid as i32)
+ }
+
+ fn getState(&self) -> binder::Result<VirtualMachineState> {
+ // Don't check permission. The owner of the VM might have passed this binder object to
+ // others.
+ Ok(get_state(&self.instance))
+ }
+
+ fn registerCallback(
+ &self,
+ callback: &Strong<dyn IVirtualMachineCallback>,
+ ) -> binder::Result<()> {
+ // Don't check permission. The owner of the VM might have passed this binder object to
+ // others.
+ //
+ // TODO: Should this give an error if the VM is already dead?
+ self.instance.callbacks.add(callback.clone());
+ Ok(())
+ }
+
+ fn start(&self) -> binder::Result<()> {
+ self.instance.start().map_err(|e| {
+ error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
+ Status::new_service_specific_error_str(-1, Some(e.to_string()))
+ })
+ }
+
+ fn stop(&self) -> binder::Result<()> {
+ self.instance.kill().map_err(|e| {
+ error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
+ Status::new_service_specific_error_str(-1, Some(e.to_string()))
+ })
+ }
+
+ fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
+ self.instance.trim_memory(level).map_err(|e| {
+ error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
+ Status::new_service_specific_error_str(-1, Some(e.to_string()))
+ })
+ }
+
+ fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
+ if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
+ return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
+ }
+ let port = port as u32;
+ if port < 1024 {
+ return Err(Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Can't connect to privileged port {port}")),
+ ));
+ }
+ let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
+ Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
+ })?;
+ Ok(vsock_stream_to_pfd(stream))
+ }
+}
+
+impl Drop for VirtualMachine {
+ fn drop(&mut self) {
+ debug!("Dropping {:?}", self);
+ if let Err(e) = self.instance.kill() {
+ debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
+ }
+ }
+}
+
+/// A set of Binders to be called back in response to various events on the VM, such as when it
+/// dies.
+#[derive(Debug, Default)]
+pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
+
+impl VirtualMachineCallbacks {
+ /// Call all registered callbacks to notify that the payload has started.
+ pub fn notify_payload_started(&self, cid: Cid) {
+ let callbacks = &*self.0.lock().unwrap();
+ for callback in callbacks {
+ if let Err(e) = callback.onPayloadStarted(cid as i32) {
+ error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
+ }
+ }
+ }
+
+ /// Call all registered callbacks to notify that the payload is ready to serve.
+ pub fn notify_payload_ready(&self, cid: Cid) {
+ let callbacks = &*self.0.lock().unwrap();
+ for callback in callbacks {
+ if let Err(e) = callback.onPayloadReady(cid as i32) {
+ error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
+ }
+ }
+ }
+
+ /// Call all registered callbacks to notify that the payload has finished.
+ pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
+ let callbacks = &*self.0.lock().unwrap();
+ for callback in callbacks {
+ if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
+ error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
+ }
+ }
+ }
+
+ /// Call all registered callbacks to say that the VM encountered an error.
+ pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
+ let callbacks = &*self.0.lock().unwrap();
+ for callback in callbacks {
+ if let Err(e) = callback.onError(cid as i32, error_code, message) {
+ error!("Error notifying error event from VM CID {}: {:?}", cid, e);
+ }
+ }
+ }
+
+ /// Call all registered callbacks to say that the VM has died.
+ pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
+ let callbacks = &*self.0.lock().unwrap();
+ for callback in callbacks {
+ if let Err(e) = callback.onDied(cid as i32, reason) {
+ error!("Error notifying exit of VM CID {}: {:?}", cid, e);
+ }
+ }
+ }
+
+ /// Add a new callback to the set.
+ fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
+ self.0.lock().unwrap().push(callback);
+ }
+}
+
+/// The mutable state of the VirtualizationService. There should only be one instance of this
+/// struct.
+#[derive(Debug, Default)]
+struct State {
+ /// The VMs which have been started. When VMs are started a weak reference is added to this list
+ /// while a strong reference is returned to the caller over Binder. Once all copies of the
+ /// Binder client are dropped the weak reference here will become invalid, and will be removed
+ /// from the list opportunistically the next time `add_vm` is called.
+ vms: Vec<Weak<VmInstance>>,
+}
+
+impl State {
+ /// Get a list of VMs which still have Binder references to them.
+ fn vms(&self) -> Vec<Arc<VmInstance>> {
+ // Attempt to upgrade the weak pointers to strong pointers.
+ self.vms.iter().filter_map(Weak::upgrade).collect()
+ }
+
+ /// Add a new VM to the list.
+ fn add_vm(&mut self, vm: Weak<VmInstance>) {
+ // Garbage collect any entries from the stored list which no longer exist.
+ self.vms.retain(|vm| vm.strong_count() > 0);
+
+ // Actually add the new VM.
+ self.vms.push(vm);
+ }
+
+ /// Get a VM that corresponds to the given cid
+ fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
+ self.vms().into_iter().find(|vm| vm.cid == cid)
+ }
+}
+
+/// Gets the `VirtualMachineState` of the given `VmInstance`.
+fn get_state(instance: &VmInstance) -> VirtualMachineState {
+ match &*instance.vm_state.lock().unwrap() {
+ VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
+ VmState::Running { .. } => match instance.payload_state() {
+ PayloadState::Starting => VirtualMachineState::STARTING,
+ PayloadState::Started => VirtualMachineState::STARTED,
+ PayloadState::Ready => VirtualMachineState::READY,
+ PayloadState::Finished => VirtualMachineState::FINISHED,
+ PayloadState::Hangup => VirtualMachineState::DEAD,
+ },
+ VmState::Dead => VirtualMachineState::DEAD,
+ VmState::Failed => VirtualMachineState::DEAD,
+ }
+}
+
+/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
+pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
+ file.as_ref().try_clone().map_err(|e| {
+ Status::new_exception_str(
+ ExceptionCode::BAD_PARCELABLE,
+ Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
+ )
+ })
+}
+
+/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
+fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
+ file.as_ref().map(clone_file).transpose()
+}
+
+/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
+fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
+ // SAFETY: ownership is transferred from stream to f
+ let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
+ ParcelFileDescriptor::new(f)
+}
+
+/// Parses the platform version requirement string.
+fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
+ VersionReq::parse(s).map_err(|e| {
+ Status::new_exception_str(
+ ExceptionCode::BAD_PARCELABLE,
+ Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
+ )
+ })
+}
+
+fn is_debuggable(config: &VirtualMachineConfig) -> bool {
+ match config {
+ VirtualMachineConfig::AppConfig(config) => config.debugLevel != DebugLevel::NONE,
+ _ => false,
+ }
+}
+
+fn clone_or_prepare_logger_fd(
+ config: &VirtualMachineConfig,
+ fd: Option<&ParcelFileDescriptor>,
+ tag: String,
+) -> Result<Option<File>, Status> {
+ if let Some(fd) = fd {
+ return Ok(Some(clone_file(fd)?));
+ }
+
+ if !is_debuggable(config) {
+ return Ok(None);
+ }
+
+ let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
+ Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
+ })?;
+
+ // SAFETY: We are the sole owners of these fds as they were just created.
+ let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
+ let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
+
+ std::thread::spawn(move || loop {
+ let mut buf = vec![];
+ match reader.read_until(b'\n', &mut buf) {
+ Ok(0) => {
+ // EOF
+ return;
+ }
+ Ok(size) => {
+ if buf[size - 1] == b'\n' {
+ buf.pop();
+ }
+ info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
+ }
+ Err(e) => {
+ error!("Could not read console pipe: {:?}", e);
+ return;
+ }
+ };
+ });
+
+ Ok(Some(write_fd))
+}
+
+/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
+/// it doesn't require that T implements Clone.
+enum BorrowedOrOwned<'a, T> {
+ Borrowed(&'a T),
+ Owned(T),
+}
+
+impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
+ fn as_ref(&self) -> &T {
+ match self {
+ Self::Borrowed(b) => b,
+ Self::Owned(o) => o,
+ }
+ }
+}
+
+/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
+#[derive(Debug, Default)]
+struct VirtualMachineService {
+ state: Arc<Mutex<State>>,
+ cid: Cid,
+}
+
+impl Interface for VirtualMachineService {}
+
+impl IVirtualMachineService for VirtualMachineService {
+ fn notifyPayloadStarted(&self) -> binder::Result<()> {
+ let cid = self.cid;
+ if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
+ info!("VM with CID {} started payload", cid);
+ vm.update_payload_state(PayloadState::Started).map_err(|e| {
+ Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
+ })?;
+ vm.callbacks.notify_payload_started(cid);
+
+ let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
+ write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
+ Ok(())
+ } else {
+ error!("notifyPayloadStarted is called from an unknown CID {}", cid);
+ Err(Status::new_service_specific_error_str(
+ -1,
+ Some(format!("cannot find a VM with CID {}", cid)),
+ ))
+ }
+ }
+
+ fn notifyPayloadReady(&self) -> binder::Result<()> {
+ let cid = self.cid;
+ if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
+ info!("VM with CID {} reported payload is ready", cid);
+ vm.update_payload_state(PayloadState::Ready).map_err(|e| {
+ Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
+ })?;
+ vm.callbacks.notify_payload_ready(cid);
+ Ok(())
+ } else {
+ error!("notifyPayloadReady is called from an unknown CID {}", cid);
+ Err(Status::new_service_specific_error_str(
+ -1,
+ Some(format!("cannot find a VM with CID {}", cid)),
+ ))
+ }
+ }
+
+ fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
+ let cid = self.cid;
+ if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
+ info!("VM with CID {} finished payload", cid);
+ vm.update_payload_state(PayloadState::Finished).map_err(|e| {
+ Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
+ })?;
+ vm.callbacks.notify_payload_finished(cid, exit_code);
+ Ok(())
+ } else {
+ error!("notifyPayloadFinished is called from an unknown CID {}", cid);
+ Err(Status::new_service_specific_error_str(
+ -1,
+ Some(format!("cannot find a VM with CID {}", cid)),
+ ))
+ }
+ }
+
+ fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
+ let cid = self.cid;
+ if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
+ info!("VM with CID {} encountered an error", cid);
+ vm.update_payload_state(PayloadState::Finished).map_err(|e| {
+ Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
+ })?;
+ vm.callbacks.notify_error(cid, error_code, message);
+ Ok(())
+ } else {
+ error!("notifyError is called from an unknown CID {}", cid);
+ Err(Status::new_service_specific_error_str(
+ -1,
+ Some(format!("cannot find a VM with CID {}", cid)),
+ ))
+ }
+ }
+}
+
+impl VirtualMachineService {
+ fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
+ BnVirtualMachineService::new_binder(
+ VirtualMachineService { state, cid },
+ BinderFeatures::default(),
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_is_allowed_label_for_partition() -> Result<()> {
+ let expected_results = vec![
+ ("u:object_r:system_file:s0", true),
+ ("u:object_r:apk_data_file:s0", true),
+ ("u:object_r:app_data_file:s0", false),
+ ("u:object_r:app_data_file:s0:c512,c768", false),
+ ("u:object_r:privapp_data_file:s0:c512,c768", false),
+ ("invalid", false),
+ ("user:role:apk_data_file:severity:categories", true),
+ ("user:role:apk_data_file:severity:categories:extraneous", false),
+ ];
+
+ for (label, expected_valid) in expected_results {
+ let context = SeContext::new(label)?;
+ let result = check_label_is_allowed(&context);
+ if expected_valid {
+ assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
+ } else if result.is_ok() {
+ bail!("Expected label {} to be disallowed", label);
+ }
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
+ let apk = tempfile::tempfile().unwrap();
+ let idsig = tempfile::tempfile().unwrap();
+
+ let ret = create_or_update_idsig_file(
+ &ParcelFileDescriptor::new(apk),
+ &ParcelFileDescriptor::new(idsig),
+ );
+ assert!(ret.is_err(), "should fail");
+ Ok(())
+ }
+
+ #[test]
+ fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
+ let tmp_dir = tempfile::TempDir::new().unwrap();
+ let apk = File::open(tmp_dir.path()).unwrap();
+ let idsig = tempfile::tempfile().unwrap();
+
+ let ret = create_or_update_idsig_file(
+ &ParcelFileDescriptor::new(apk),
+ &ParcelFileDescriptor::new(idsig),
+ );
+ assert!(ret.is_err(), "should fail");
+ Ok(())
+ }
+
+ /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
+ /// on ext4 filesystem is passed.
+ /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
+ /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
+ /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
+ #[test]
+ fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
+ // APEXes are backed by the ext4.
+ let apk = File::open("/apex/com.android.virt/").unwrap();
+ let idsig = tempfile::tempfile().unwrap();
+
+ let ret = create_or_update_idsig_file(
+ &ParcelFileDescriptor::new(apk),
+ &ParcelFileDescriptor::new(idsig),
+ );
+ assert!(ret.is_err(), "should fail");
+ Ok(())
+ }
+}
diff --git a/virtualizationmanager/src/atom.rs b/virtualizationmanager/src/atom.rs
new file mode 100644
index 0000000..c33f262
--- /dev/null
+++ b/virtualizationmanager/src/atom.rs
@@ -0,0 +1,186 @@
+// Copyright 2022, 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 creating and collecting atoms.
+
+use crate::aidl::{clone_file, GLOBAL_SERVICE};
+use crate::crosvm::VmMetric;
+use crate::get_calling_uid;
+use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
+ IVirtualMachine::IVirtualMachine,
+ VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
+ VirtualMachineConfig::VirtualMachineConfig,
+};
+use android_system_virtualizationservice::binder::{Status, Strong};
+use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
+ AtomVmBooted::AtomVmBooted,
+ AtomVmCreationRequested::AtomVmCreationRequested,
+ AtomVmExited::AtomVmExited,
+};
+use anyhow::{anyhow, Result};
+use binder::ParcelFileDescriptor;
+use log::warn;
+use microdroid_payload_config::VmPayloadConfig;
+use statslog_virtualization_rust::vm_creation_requested;
+use std::thread;
+use std::time::{Duration, SystemTime};
+use zip::ZipArchive;
+
+fn get_apex_list(config: &VirtualMachineAppConfig) -> String {
+ match &config.payload {
+ Payload::PayloadConfig(_) => String::new(),
+ Payload::ConfigPath(config_path) => {
+ let vm_payload_config = get_vm_payload_config(&config.apk, config_path);
+ if let Ok(vm_payload_config) = vm_payload_config {
+ vm_payload_config
+ .apexes
+ .iter()
+ .map(|x| x.name.clone())
+ .collect::<Vec<String>>()
+ .join(":")
+ } else {
+ "INFO: Can't get VmPayloadConfig".to_owned()
+ }
+ }
+ }
+}
+
+fn get_vm_payload_config(
+ apk_fd: &Option<ParcelFileDescriptor>,
+ config_path: &str,
+) -> Result<VmPayloadConfig> {
+ let apk = apk_fd.as_ref().ok_or_else(|| anyhow!("APK is none"))?;
+ let apk_file = clone_file(apk)?;
+ let mut apk_zip = ZipArchive::new(&apk_file)?;
+ let config_file = apk_zip.by_name(config_path)?;
+ let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
+ Ok(vm_payload_config)
+}
+
+fn get_duration(vm_start_timestamp: Option<SystemTime>) -> Duration {
+ match vm_start_timestamp {
+ Some(vm_start_timestamp) => vm_start_timestamp.elapsed().unwrap_or_default(),
+ None => Duration::default(),
+ }
+}
+
+/// Write the stats of VMCreation to statsd
+pub fn write_vm_creation_stats(
+ config: &VirtualMachineConfig,
+ is_protected: bool,
+ ret: &binder::Result<Strong<dyn IVirtualMachine>>,
+) {
+ let creation_succeeded;
+ let binder_exception_code;
+ match ret {
+ Ok(_) => {
+ creation_succeeded = true;
+ binder_exception_code = Status::ok().exception_code() as i32;
+ }
+ Err(ref e) => {
+ creation_succeeded = false;
+ binder_exception_code = e.exception_code() as i32;
+ }
+ }
+ let (vm_identifier, config_type, num_cpus, memory_mib, apexes) = match config {
+ VirtualMachineConfig::AppConfig(config) => (
+ config.name.clone(),
+ vm_creation_requested::ConfigType::VirtualMachineAppConfig,
+ config.numCpus,
+ config.memoryMib,
+ get_apex_list(config),
+ ),
+ VirtualMachineConfig::RawConfig(config) => (
+ config.name.clone(),
+ vm_creation_requested::ConfigType::VirtualMachineRawConfig,
+ config.numCpus,
+ config.memoryMib,
+ String::new(),
+ ),
+ };
+
+ let atom = AtomVmCreationRequested {
+ uid: get_calling_uid() as i32,
+ vmIdentifier: vm_identifier,
+ isProtected: is_protected,
+ creationSucceeded: creation_succeeded,
+ binderExceptionCode: binder_exception_code,
+ configType: config_type as i32,
+ numCpus: num_cpus,
+ memoryMib: memory_mib,
+ apexes,
+ };
+
+ thread::spawn(move || {
+ GLOBAL_SERVICE.atomVmCreationRequested(&atom).unwrap_or_else(|e| {
+ warn!("Failed to write VmCreationRequested atom: {e}");
+ });
+ });
+}
+
+/// Write the stats of VM boot to statsd
+/// The function creates a separate thread which waits fro statsd to start to push atom
+pub fn write_vm_booted_stats(
+ uid: i32,
+ vm_identifier: &str,
+ vm_start_timestamp: Option<SystemTime>,
+) {
+ let vm_identifier = vm_identifier.to_owned();
+ let duration = get_duration(vm_start_timestamp);
+
+ let atom = AtomVmBooted {
+ uid,
+ vmIdentifier: vm_identifier,
+ elapsedTimeMillis: duration.as_millis() as i64,
+ };
+
+ thread::spawn(move || {
+ GLOBAL_SERVICE.atomVmBooted(&atom).unwrap_or_else(|e| {
+ warn!("Failed to write VmCreationRequested atom: {e}");
+ });
+ });
+}
+
+/// Write the stats of VM exit to statsd
+/// The function creates a separate thread which waits fro statsd to start to push atom
+pub fn write_vm_exited_stats(
+ uid: i32,
+ vm_identifier: &str,
+ reason: DeathReason,
+ exit_signal: Option<i32>,
+ vm_metric: &VmMetric,
+) {
+ let vm_identifier = vm_identifier.to_owned();
+ let elapsed_time_millis = get_duration(vm_metric.start_timestamp).as_millis() as i64;
+ let guest_time_millis = vm_metric.cpu_guest_time.unwrap_or_default();
+ let rss = vm_metric.rss.unwrap_or_default();
+
+ let atom = AtomVmExited {
+ uid,
+ vmIdentifier: vm_identifier,
+ elapsedTimeMillis: elapsed_time_millis,
+ deathReason: reason,
+ guestTimeMillis: guest_time_millis,
+ rssVmKb: rss.vm,
+ rssCrosvmKb: rss.crosvm,
+ exitSignal: exit_signal.unwrap_or_default(),
+ };
+
+ thread::spawn(move || {
+ GLOBAL_SERVICE.atomVmExited(&atom).unwrap_or_else(|e| {
+ warn!("Failed to write VmExited atom: {e}");
+ });
+ });
+}
diff --git a/virtualizationservice/src/composite.rs b/virtualizationmanager/src/composite.rs
similarity index 100%
rename from virtualizationservice/src/composite.rs
rename to virtualizationmanager/src/composite.rs
diff --git a/virtualizationservice/src/crosvm.rs b/virtualizationmanager/src/crosvm.rs
similarity index 100%
rename from virtualizationservice/src/crosvm.rs
rename to virtualizationmanager/src/crosvm.rs
diff --git a/virtualizationservice/src/virtmgr.rs b/virtualizationmanager/src/main.rs
similarity index 100%
rename from virtualizationservice/src/virtmgr.rs
rename to virtualizationmanager/src/main.rs
diff --git a/virtualizationservice/src/payload.rs b/virtualizationmanager/src/payload.rs
similarity index 100%
rename from virtualizationservice/src/payload.rs
rename to virtualizationmanager/src/payload.rs
diff --git a/virtualizationservice/src/selinux.rs b/virtualizationmanager/src/selinux.rs
similarity index 100%
rename from virtualizationservice/src/selinux.rs
rename to virtualizationmanager/src/selinux.rs
diff --git a/virtualizationservice/Android.bp b/virtualizationservice/Android.bp
index d0dde42..f7202da 100644
--- a/virtualizationservice/Android.bp
+++ b/virtualizationservice/Android.bp
@@ -2,10 +2,11 @@
default_applicable_licenses: ["Android-Apache-2.0"],
}
-rust_defaults {
- name: "virtualizationservice_defaults",
+rust_binary {
+ name: "virtualizationservice",
crate_name: "virtualizationservice",
edition: "2021",
+ srcs: ["src/main.rs"],
// Only build on targets which crosvm builds on.
enabled: false,
target: {
@@ -26,66 +27,14 @@
"android.os.permissions_aidl-rust",
"libandroid_logger",
"libanyhow",
- "libapkverify",
- "libbase_rust",
"libbinder_rs",
- "libcommand_fds",
- "libdisk",
- "liblazy_static",
"liblibc",
"liblog_rust",
- "libmicrodroid_metadata",
- "libmicrodroid_payload_config",
- "libnested_virt",
"libnix",
- "libonce_cell",
- "libregex",
- "librpcbinder_rs",
"librustutils",
- "libsemver",
- "libselinux_bindgen",
- "libserde",
- "libserde_json",
- "libserde_xml_rs",
- "libshared_child",
"libstatslog_virtualization_rust",
"libtombstoned_client_rust",
- "libvm_control",
- "libvmconfig",
- "libzip",
"libvsock",
- // TODO(b/202115393) stabilize the interface
- "packagemanager_aidl-rust",
- ],
- shared_libs: [
- "libbinder_rpc_unstable",
- "libselinux",
- ],
-}
-
-rust_binary {
- name: "virtualizationservice",
- defaults: ["virtualizationservice_defaults"],
- srcs: ["src/main.rs"],
- apex_available: ["com.android.virt"],
-}
-
-rust_binary {
- name: "virtmgr",
- defaults: ["virtualizationservice_defaults"],
- srcs: ["src/virtmgr.rs"],
- rustlibs: [
- "libclap",
],
apex_available: ["com.android.virt"],
}
-
-rust_test {
- name: "virtualizationservice_device_test",
- srcs: ["src/main.rs"],
- defaults: ["virtualizationservice_defaults"],
- rustlibs: [
- "libtempfile",
- ],
- test_suites: ["general-tests"],
-}
diff --git a/virtualizationservice/TEST_MAPPING b/virtualizationservice/TEST_MAPPING
deleted file mode 100644
index 8388ff2..0000000
--- a/virtualizationservice/TEST_MAPPING
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "avf-presubmit": [
- {
- "name": "virtualizationservice_device_test"
- }
- ]
-}
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 374b90f..43b7616 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -15,33 +15,9 @@
//! Implementation of the AIDL interface of the VirtualizationService.
use crate::{get_calling_pid, get_calling_uid};
-use crate::atom::{
- forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_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::payload::{add_microdroid_payload_images, add_microdroid_system_images};
-use crate::selinux::{getfilecon, SeContext};
+use crate::atom::{forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom};
use android_os_permissions_aidl::aidl::android::os::IPermissionController;
-use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
- DeathReason::DeathReason,
- ErrorCode::ErrorCode,
-};
-use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
- DiskImage::DiskImage,
- IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
- IVirtualMachineCallback::IVirtualMachineCallback,
- IVirtualizationService::IVirtualizationService,
- MemoryTrimLevel::MemoryTrimLevel,
- Partition::Partition,
- PartitionType::PartitionType,
- VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
- VirtualMachineConfig::VirtualMachineConfig,
- VirtualMachineDebugInfo::VirtualMachineDebugInfo,
- VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
- VirtualMachineRawConfig::VirtualMachineRawConfig,
- VirtualMachineState::VirtualMachineState,
-};
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
AtomVmBooted::AtomVmBooted,
AtomVmCreationRequested::AtomVmCreationRequested,
@@ -49,38 +25,21 @@
IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
IVirtualizationServiceInternal::IVirtualizationServiceInternal,
};
-use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
- BnVirtualMachineService, IVirtualMachineService, VM_TOMBSTONES_SERVICE_PORT,
-};
+use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::VM_TOMBSTONES_SERVICE_PORT;
use anyhow::{anyhow, bail, Context, Result};
-use apkverify::{HashAlgorithm, V4Signature};
-use binder::{
- self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard,
- ParcelFileDescriptor, Status, StatusCode, Strong,
-};
-use disk::QcowFile;
-use lazy_static::lazy_static;
+use binder::{self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, Status, Strong};
use libc::VMADDR_CID_HOST;
-use log::{debug, error, info, warn};
-use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
-use rpcbinder::RpcServer;
+use log::{error, info, warn};
use rustutils::system_properties;
-use semver::VersionReq;
use std::collections::HashMap;
-use std::convert::TryInto;
-use std::ffi::CStr;
-use std::fs::{create_dir, read_dir, remove_dir, remove_file, set_permissions, File, OpenOptions, Permissions};
-use std::io::{Error, ErrorKind, Read, Write};
-use std::num::NonZeroU32;
+use std::fs::{create_dir, read_dir, remove_dir, remove_file, set_permissions, Permissions};
+use std::io::{Read, Write};
use std::os::unix::fs::PermissionsExt;
-use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::os::unix::raw::{pid_t, uid_t};
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
use std::sync::{Arc, Mutex, Weak};
use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
-use vmconfig::VmConfig;
use vsock::{VsockListener, VsockStream};
-use zip::ZipArchive;
use nix::unistd::{chown, Uid};
/// The unique ID of a VM used (together with a port number) for vsock communication.
@@ -98,50 +57,12 @@
const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
-/// The size of zero.img.
-/// Gaps in composite disk images are filled with a shared zero.img.
-const ZERO_FILLER_SIZE: u64 = 4096;
-
-/// Magic string for the instance image
-const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
-
-/// Version of the instance image format
-const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
-
const CHUNK_RECV_MAX_LEN: usize = 1024;
-const MICRODROID_OS_NAME: &str = "microdroid";
-
-const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
-
-lazy_static! {
- pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
- wait_for_interface(BINDER_SERVICE_IDENTIFIER)
- .expect("Could not connect to VirtualizationServiceInternal");
-}
-
fn is_valid_guest_cid(cid: Cid) -> bool {
(GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
}
-fn create_or_update_idsig_file(
- input_fd: &ParcelFileDescriptor,
- idsig_fd: &ParcelFileDescriptor,
-) -> Result<()> {
- let mut input = clone_file(input_fd)?;
- let metadata = input.metadata().context("failed to get input metadata")?;
- if !metadata.is_file() {
- bail!("input is not a regular file");
- }
- let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
- .context("failed to create idsig")?;
-
- let mut output = clone_file(idsig_fd)?;
- output.set_len(0).context("failed to set_len on the idsig output")?;
- sig.write_into(&mut output).context("failed to write idsig")?;
- Ok(())
-}
-
/// Singleton service for allocating globally-unique VM resources, such as the CID, and running
/// singleton servers, like tombstone receiver.
#[derive(Debug, Default)]
@@ -150,9 +71,6 @@
}
impl VirtualizationServiceInternal {
- // TODO(b/245727626): Remove after the source files for virtualizationservice
- // and virtmgr binaries are split from each other.
- #[allow(dead_code)]
pub fn init() -> VirtualizationServiceInternal {
let service = VirtualizationServiceInternal::default();
@@ -193,6 +111,8 @@
&self,
requester_debug_pid: i32,
) -> binder::Result<Strong<dyn IGlobalVmContext>> {
+ check_manage_access()?;
+
let requester_uid = get_calling_uid();
let requester_debug_pid = requester_debug_pid as pid_t;
let state = &mut *self.state.lock().unwrap();
@@ -217,6 +137,8 @@
}
fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
+ check_debug_access()?;
+
let state = &mut *self.state.lock().unwrap();
let cids = state
.held_contexts
@@ -385,125 +307,6 @@
}
}
-/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
-#[derive(Debug, Default)]
-pub struct VirtualizationService {
- state: Arc<Mutex<State>>,
-}
-
-impl Interface for VirtualizationService {
- fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
- check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
- let state = &mut *self.state.lock().unwrap();
- let vms = state.vms();
- writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
- for vm in vms {
- writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
- writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
- .or(Err(StatusCode::UNKNOWN_ERROR))?;
- writeln!(file, "\tPayload state {:?}", vm.payload_state())
- .or(Err(StatusCode::UNKNOWN_ERROR))?;
- writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
- writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
- .or(Err(StatusCode::UNKNOWN_ERROR))?;
- writeln!(file, "\trequester_uid: {}", vm.requester_uid)
- .or(Err(StatusCode::UNKNOWN_ERROR))?;
- writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
- .or(Err(StatusCode::UNKNOWN_ERROR))?;
- }
- Ok(())
- }
-}
-
-impl IVirtualizationService for VirtualizationService {
- /// Creates (but does not start) a new VM with the given configuration, assigning it the next
- /// available CID.
- ///
- /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
- fn createVm(
- &self,
- config: &VirtualMachineConfig,
- console_fd: Option<&ParcelFileDescriptor>,
- log_fd: Option<&ParcelFileDescriptor>,
- ) -> binder::Result<Strong<dyn IVirtualMachine>> {
- let mut is_protected = false;
- let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
- write_vm_creation_stats(config, is_protected, &ret);
- ret
- }
-
- /// Initialise an empty partition image of the given size to be used as a writable partition.
- fn initializeWritablePartition(
- &self,
- image_fd: &ParcelFileDescriptor,
- size: i64,
- partition_type: PartitionType,
- ) -> binder::Result<()> {
- check_manage_access()?;
- let size = size.try_into().map_err(|e| {
- Status::new_exception_str(
- ExceptionCode::ILLEGAL_ARGUMENT,
- Some(format!("Invalid size {}: {:?}", size, e)),
- )
- })?;
- let image = clone_file(image_fd)?;
- // initialize the file. Any data in the file will be erased.
- image.set_len(0).map_err(|e| {
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to reset a file: {:?}", e)),
- )
- })?;
- let mut part = QcowFile::new(image, size).map_err(|e| {
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to create QCOW2 image: {:?}", e)),
- )
- })?;
-
- match partition_type {
- PartitionType::RAW => Ok(()),
- PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
- PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
- _ => Err(Error::new(
- ErrorKind::Unsupported,
- format!("Unsupported partition type {:?}", partition_type),
- )),
- }
- .map_err(|e| {
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
- )
- })?;
-
- Ok(())
- }
-
- /// Creates or update the idsig file by digesting the input APK file.
- fn createOrUpdateIdsigFile(
- &self,
- input_fd: &ParcelFileDescriptor,
- idsig_fd: &ParcelFileDescriptor,
- ) -> binder::Result<()> {
- // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
- // idsig_fd is different from APK digest in input_fd
-
- check_manage_access()?;
-
- create_or_update_idsig_file(input_fd, idsig_fd)
- .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
- Ok(())
- }
-
- /// Get a list of all currently running VMs. This method is only intended for debug purposes,
- /// and as such is only permitted from the shell user.
- fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
- check_debug_access()?;
- GLOBAL_SERVICE.debugListVms()
- }
-}
-
fn handle_stream_connection_tombstoned() -> Result<()> {
// Should not listen for tombstones on a guest VM's port.
assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
@@ -554,398 +357,6 @@
Ok(())
}
-impl VirtualizationService {
- // TODO(b/245727626): Remove after the source files for virtualizationservice
- // and virtmgr binaries are split from each other.
- #[allow(dead_code)]
- pub fn init() -> VirtualizationService {
- VirtualizationService::default()
- }
-
- fn create_vm_context(&self, requester_debug_pid: pid_t) -> Result<(VmContext, Cid, PathBuf)> {
- const NUM_ATTEMPTS: usize = 5;
-
- for _ in 0..NUM_ATTEMPTS {
- let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid as i32)?;
- let cid = vm_context.getCid()? as Cid;
- let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
- let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
-
- // Start VM service listening for connections from the new CID on port=CID.
- let port = cid;
- match RpcServer::new_vsock(service, cid, port) {
- Ok(vm_server) => {
- vm_server.start();
- return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
- }
- Err(err) => {
- warn!("Could not start RpcServer on port {}: {}", port, err);
- }
- }
- }
- bail!("Too many attempts to create VM context failed.");
- }
-
- fn create_vm_internal(
- &self,
- config: &VirtualMachineConfig,
- console_fd: Option<&ParcelFileDescriptor>,
- log_fd: Option<&ParcelFileDescriptor>,
- is_protected: &mut bool,
- ) -> binder::Result<Strong<dyn IVirtualMachine>> {
- check_manage_access()?;
-
- let is_custom = match config {
- VirtualMachineConfig::RawConfig(_) => true,
- VirtualMachineConfig::AppConfig(config) => {
- // Some features are reserved for platform apps only, even when using
- // VirtualMachineAppConfig:
- // - controlling CPUs;
- // - specifying a config file in the APK.
- !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
- }
- };
- if is_custom {
- check_use_custom_virtual_machine()?;
- }
-
- let requester_uid = get_calling_uid();
- let requester_debug_pid = get_calling_pid();
-
- let (vm_context, cid, temporary_directory) =
- self.create_vm_context(requester_debug_pid).map_err(|e| {
- error!("Failed to create VmContext: {:?}", e);
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to create VmContext: {:?}", e)),
- )
- })?;
-
- let state = &mut *self.state.lock().unwrap();
- let console_fd = console_fd.map(clone_file).transpose()?;
- let log_fd = log_fd.map(clone_file).transpose()?;
-
- // Counter to generate unique IDs for temporary image files.
- let mut next_temporary_image_id = 0;
- // Files which are referred to from composite images. These must be mapped to the crosvm
- // child process, and not closed before it is started.
- let mut indirect_files = vec![];
-
- let (is_app_config, config) = match config {
- VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
- VirtualMachineConfig::AppConfig(config) => {
- let config = load_app_config(config, &temporary_directory).map_err(|e| {
- *is_protected = config.protectedVm;
- let message = format!("Failed to load app config: {:?}", e);
- error!("{}", message);
- Status::new_service_specific_error_str(-1, Some(message))
- })?;
- (true, BorrowedOrOwned::Owned(config))
- }
- };
- let config = config.as_ref();
- *is_protected = config.protectedVm;
-
- // Check if partition images are labeled incorrectly. This is to prevent random images
- // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
- // being loaded in a pVM. This applies to everything in the raw config, and everything but
- // the non-executable, generated partitions in the app config.
- config
- .disks
- .iter()
- .flat_map(|disk| disk.partitions.iter())
- .filter(|partition| {
- if is_app_config {
- !is_safe_app_partition(&partition.label)
- } else {
- true // all partitions are checked
- }
- })
- .try_for_each(check_label_for_partition)
- .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
-
- let kernel = maybe_clone_file(&config.kernel)?;
- let initrd = maybe_clone_file(&config.initrd)?;
-
- // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
- if config.protectedVm {
- check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
- Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
- })?;
- }
-
- let zero_filler_path = temporary_directory.join("zero.img");
- write_zero_filler(&zero_filler_path).map_err(|e| {
- error!("Failed to make composite image: {:?}", e);
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to make composite image: {:?}", e)),
- )
- })?;
-
- // Assemble disk images if needed.
- let disks = config
- .disks
- .iter()
- .map(|disk| {
- assemble_disk_image(
- disk,
- &zero_filler_path,
- &temporary_directory,
- &mut next_temporary_image_id,
- &mut indirect_files,
- )
- })
- .collect::<Result<Vec<DiskFile>, _>>()?;
-
- // Creating this ramdump file unconditionally is not harmful as ramdump will be created
- // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
- // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
- // will be sent back to the client (i.e. the VM owner) for readout.
- let ramdump_path = temporary_directory.join("ramdump");
- let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
- error!("Failed to prepare ramdump file: {:?}", e);
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to prepare ramdump file: {:?}", e)),
- )
- })?;
-
- // Actually start the VM.
- let crosvm_config = CrosvmConfig {
- cid,
- name: config.name.clone(),
- bootloader: maybe_clone_file(&config.bootloader)?,
- kernel,
- initrd,
- disks,
- params: config.params.to_owned(),
- protected: *is_protected,
- memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
- cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
- task_profiles: config.taskProfiles.clone(),
- console_fd,
- log_fd,
- ramdump: Some(ramdump),
- indirect_files,
- platform_version: parse_platform_version_req(&config.platformVersion)?,
- detect_hangup: is_app_config,
- };
- let instance = Arc::new(
- VmInstance::new(
- crosvm_config,
- temporary_directory,
- requester_uid,
- requester_debug_pid,
- vm_context,
- )
- .map_err(|e| {
- error!("Failed to create VM with config {:?}: {:?}", config, e);
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to create VM: {:?}", e)),
- )
- })?,
- );
- state.add_vm(Arc::downgrade(&instance));
- Ok(VirtualMachine::create(instance))
- }
-}
-
-fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
- let file = OpenOptions::new()
- .create_new(true)
- .read(true)
- .write(true)
- .open(zero_filler_path)
- .with_context(|| "Failed to create zero.img")?;
- file.set_len(ZERO_FILLER_SIZE)?;
- Ok(())
-}
-
-fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
- part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
- part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
- part.flush()
-}
-
-fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
- part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
- part.flush()
-}
-
-fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
- File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
-}
-
-/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
-///
-/// This may involve assembling a composite disk from a set of partition images.
-fn assemble_disk_image(
- disk: &DiskImage,
- zero_filler_path: &Path,
- temporary_directory: &Path,
- next_temporary_image_id: &mut u64,
- indirect_files: &mut Vec<File>,
-) -> Result<DiskFile, Status> {
- let image = if !disk.partitions.is_empty() {
- if disk.image.is_some() {
- warn!("DiskImage {:?} contains both image and partitions.", disk);
- return Err(Status::new_exception_str(
- ExceptionCode::ILLEGAL_ARGUMENT,
- Some("DiskImage contains both image and partitions."),
- ));
- }
-
- let composite_image_filenames =
- make_composite_image_filenames(temporary_directory, next_temporary_image_id);
- let (image, partition_files) = make_composite_image(
- &disk.partitions,
- zero_filler_path,
- &composite_image_filenames.composite,
- &composite_image_filenames.header,
- &composite_image_filenames.footer,
- )
- .map_err(|e| {
- error!("Failed to make composite image with config {:?}: {:?}", disk, e);
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to make composite image: {:?}", e)),
- )
- })?;
-
- // Pass the file descriptors for the various partition files to crosvm when it
- // is run.
- indirect_files.extend(partition_files);
-
- image
- } else if let Some(image) = &disk.image {
- clone_file(image)?
- } else {
- warn!("DiskImage {:?} didn't contain image or partitions.", disk);
- return Err(Status::new_exception_str(
- ExceptionCode::ILLEGAL_ARGUMENT,
- Some("DiskImage didn't contain image or partitions."),
- ));
- };
-
- Ok(DiskFile { image, writable: disk.writable })
-}
-
-fn load_app_config(
- config: &VirtualMachineAppConfig,
- temporary_directory: &Path,
-) -> Result<VirtualMachineRawConfig> {
- let apk_file = clone_file(config.apk.as_ref().unwrap())?;
- let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
- let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
-
- let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
- Some(clone_file(file)?)
- } else {
- None
- };
-
- let vm_payload_config = 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))?
- }
- Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
- };
-
- // For now, the only supported OS is Microdroid
- let os_name = vm_payload_config.os.name.as_str();
- if os_name != MICRODROID_OS_NAME {
- bail!("Unknown OS \"{}\"", os_name);
- }
-
- // It is safe to construct a filename based on the os_name because we've already checked that it
- // is one of the allowed values.
- let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
- let vm_config_file = File::open(vm_config_path)?;
- let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
-
- if config.memoryMib > 0 {
- vm_config.memoryMib = config.memoryMib;
- }
-
- vm_config.name = config.name.clone();
- vm_config.protectedVm = config.protectedVm;
- vm_config.numCpus = config.numCpus;
- vm_config.taskProfiles = config.taskProfiles.clone();
-
- // Microdroid takes additional init ramdisk & (optionally) storage image
- add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
-
- // Include Microdroid payload disk (contains apks, idsigs) in vm config
- add_microdroid_payload_images(
- config,
- temporary_directory,
- apk_file,
- idsig_file,
- &vm_payload_config,
- &mut vm_config,
- )?;
-
- Ok(vm_config)
-}
-
-fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
- let mut apk_zip = ZipArchive::new(apk_file)?;
- let config_file = apk_zip.by_name(config_path)?;
- Ok(serde_json::from_reader(config_file)?)
-}
-
-fn create_vm_payload_config(
- payload_config: &VirtualMachinePayloadConfig,
-) -> Result<VmPayloadConfig> {
- // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
- // parameters we've been given. Microdroid will do something equivalent inside the VM using the
- // payload config that we send it via the metadata file.
-
- let payload_binary_name = &payload_config.payloadBinaryName;
- if payload_binary_name.contains('/') {
- bail!("Payload binary name must not specify a path: {payload_binary_name}");
- }
-
- let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
- Ok(VmPayloadConfig {
- os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
- task: Some(task),
- apexes: vec![],
- extra_apks: vec![],
- prefer_staged: false,
- export_tombstones: false,
- enable_authfs: false,
- })
-}
-
-/// Generates a unique filename to use for a composite disk image.
-fn make_composite_image_filenames(
- temporary_directory: &Path,
- next_temporary_image_id: &mut u64,
-) -> CompositeImageFilenames {
- let id = *next_temporary_image_id;
- *next_temporary_image_id += 1;
- CompositeImageFilenames {
- composite: temporary_directory.join(format!("composite-{}.img", id)),
- header: temporary_directory.join(format!("composite-{}-header.img", id)),
- footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
- }
-}
-
-/// Filenames for a composite disk image, including header and footer partitions.
-#[derive(Clone, Debug, Eq, PartialEq)]
-struct CompositeImageFilenames {
- /// The composite disk image itself.
- composite: PathBuf,
- /// The header partition image.
- header: PathBuf,
- /// The footer partition image.
- footer: PathBuf,
-}
-
/// Checks whether the caller has a specific permission
fn check_permission(perm: &str) -> binder::Result<()> {
let calling_pid = get_calling_pid();
@@ -975,476 +386,3 @@
fn check_manage_access() -> binder::Result<()> {
check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
}
-
-/// Check whether the caller of the current Binder method is allowed to create custom VMs
-fn check_use_custom_virtual_machine() -> binder::Result<()> {
- check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
-}
-
-/// Return whether a partition is exempt from selinux label checks, because we know that it does
-/// not contain code and is likely to be generated in an app-writable directory.
-fn is_safe_app_partition(label: &str) -> bool {
- // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
- label == "vm-instance"
- || label == "encryptedstore"
- || label == "microdroid-apk-idsig"
- || label == "payload-metadata"
- || label.starts_with("extra-idsig-")
-}
-
-/// Check that a file SELinux label is acceptable.
-///
-/// We only want to allow code in a VM to be sourced from places that apps, and the
-/// system, do not have write access to.
-///
-/// Note that sepolicy must also grant read access for these types to both virtualization
-/// service and crosvm.
-///
-/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
-/// user devices (W^X).
-fn check_label_is_allowed(context: &SeContext) -> Result<()> {
- match context.selinux_type()? {
- | "system_file" // immutable dm-verity protected partition
- | "apk_data_file" // APKs of an installed app
- | "staging_data_file" // updated/staged APEX images
- | "shell_data_file" // test files created via adb shell
- => Ok(()),
- _ => bail!("Label {} is not allowed", context),
- }
-}
-
-fn check_label_for_partition(partition: &Partition) -> Result<()> {
- let file = partition.image.as_ref().unwrap().as_ref();
- check_label_is_allowed(&getfilecon(file)?)
- .with_context(|| format!("Partition {} invalid", &partition.label))
-}
-
-fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
- if let Some(f) = kernel {
- check_label_for_file(f, "kernel")?;
- }
- if let Some(f) = initrd {
- check_label_for_file(f, "initrd")?;
- }
- Ok(())
-}
-fn check_label_for_file(file: &File, name: &str) -> Result<()> {
- check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
-}
-
-/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
-#[derive(Debug)]
-struct VirtualMachine {
- instance: Arc<VmInstance>,
-}
-
-impl VirtualMachine {
- fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
- BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
- }
-}
-
-impl Interface for VirtualMachine {}
-
-impl IVirtualMachine for VirtualMachine {
- fn getCid(&self) -> binder::Result<i32> {
- // Don't check permission. The owner of the VM might have passed this binder object to
- // others.
- Ok(self.instance.cid as i32)
- }
-
- fn getState(&self) -> binder::Result<VirtualMachineState> {
- // Don't check permission. The owner of the VM might have passed this binder object to
- // others.
- Ok(get_state(&self.instance))
- }
-
- fn registerCallback(
- &self,
- callback: &Strong<dyn IVirtualMachineCallback>,
- ) -> binder::Result<()> {
- // Don't check permission. The owner of the VM might have passed this binder object to
- // others.
- //
- // TODO: Should this give an error if the VM is already dead?
- self.instance.callbacks.add(callback.clone());
- Ok(())
- }
-
- fn start(&self) -> binder::Result<()> {
- self.instance.start().map_err(|e| {
- error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
- Status::new_service_specific_error_str(-1, Some(e.to_string()))
- })
- }
-
- fn stop(&self) -> binder::Result<()> {
- self.instance.kill().map_err(|e| {
- error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
- Status::new_service_specific_error_str(-1, Some(e.to_string()))
- })
- }
-
- fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
- self.instance.trim_memory(level).map_err(|e| {
- error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
- Status::new_service_specific_error_str(-1, Some(e.to_string()))
- })
- }
-
- fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
- if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
- return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
- }
- let port = port as u32;
- if port < 1024 {
- return Err(Status::new_service_specific_error_str(
- -1,
- Some(format!("Can't connect to privileged port {port}")),
- ));
- }
- let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
- Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
- })?;
- Ok(vsock_stream_to_pfd(stream))
- }
-}
-
-impl Drop for VirtualMachine {
- fn drop(&mut self) {
- debug!("Dropping {:?}", self);
- if let Err(e) = self.instance.kill() {
- debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
- }
- }
-}
-
-/// A set of Binders to be called back in response to various events on the VM, such as when it
-/// dies.
-#[derive(Debug, Default)]
-pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
-
-impl VirtualMachineCallbacks {
- /// Call all registered callbacks to notify that the payload has started.
- pub fn notify_payload_started(&self, cid: Cid) {
- let callbacks = &*self.0.lock().unwrap();
- for callback in callbacks {
- if let Err(e) = callback.onPayloadStarted(cid as i32) {
- error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
- }
- }
- }
-
- /// Call all registered callbacks to notify that the payload is ready to serve.
- pub fn notify_payload_ready(&self, cid: Cid) {
- let callbacks = &*self.0.lock().unwrap();
- for callback in callbacks {
- if let Err(e) = callback.onPayloadReady(cid as i32) {
- error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
- }
- }
- }
-
- /// Call all registered callbacks to notify that the payload has finished.
- pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
- let callbacks = &*self.0.lock().unwrap();
- for callback in callbacks {
- if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
- error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
- }
- }
- }
-
- /// Call all registered callbacks to say that the VM encountered an error.
- pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
- let callbacks = &*self.0.lock().unwrap();
- for callback in callbacks {
- if let Err(e) = callback.onError(cid as i32, error_code, message) {
- error!("Error notifying error event from VM CID {}: {:?}", cid, e);
- }
- }
- }
-
- /// Call all registered callbacks to say that the VM has died.
- pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
- let callbacks = &*self.0.lock().unwrap();
- for callback in callbacks {
- if let Err(e) = callback.onDied(cid as i32, reason) {
- error!("Error notifying exit of VM CID {}: {:?}", cid, e);
- }
- }
- }
-
- /// Add a new callback to the set.
- fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
- self.0.lock().unwrap().push(callback);
- }
-}
-
-/// The mutable state of the VirtualizationService. There should only be one instance of this
-/// struct.
-#[derive(Debug, Default)]
-struct State {
- /// The VMs which have been started. When VMs are started a weak reference is added to this list
- /// while a strong reference is returned to the caller over Binder. Once all copies of the
- /// Binder client are dropped the weak reference here will become invalid, and will be removed
- /// from the list opportunistically the next time `add_vm` is called.
- vms: Vec<Weak<VmInstance>>,
-}
-
-impl State {
- /// Get a list of VMs which still have Binder references to them.
- fn vms(&self) -> Vec<Arc<VmInstance>> {
- // Attempt to upgrade the weak pointers to strong pointers.
- self.vms.iter().filter_map(Weak::upgrade).collect()
- }
-
- /// Add a new VM to the list.
- fn add_vm(&mut self, vm: Weak<VmInstance>) {
- // Garbage collect any entries from the stored list which no longer exist.
- self.vms.retain(|vm| vm.strong_count() > 0);
-
- // Actually add the new VM.
- self.vms.push(vm);
- }
-
- /// Get a VM that corresponds to the given cid
- fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
- self.vms().into_iter().find(|vm| vm.cid == cid)
- }
-}
-
-/// Gets the `VirtualMachineState` of the given `VmInstance`.
-fn get_state(instance: &VmInstance) -> VirtualMachineState {
- match &*instance.vm_state.lock().unwrap() {
- VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
- VmState::Running { .. } => match instance.payload_state() {
- PayloadState::Starting => VirtualMachineState::STARTING,
- PayloadState::Started => VirtualMachineState::STARTED,
- PayloadState::Ready => VirtualMachineState::READY,
- PayloadState::Finished => VirtualMachineState::FINISHED,
- PayloadState::Hangup => VirtualMachineState::DEAD,
- },
- VmState::Dead => VirtualMachineState::DEAD,
- VmState::Failed => VirtualMachineState::DEAD,
- }
-}
-
-/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
-pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
- file.as_ref().try_clone().map_err(|e| {
- Status::new_exception_str(
- ExceptionCode::BAD_PARCELABLE,
- Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
- )
- })
-}
-
-/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
-fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
- file.as_ref().map(clone_file).transpose()
-}
-
-/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
-fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
- // SAFETY: ownership is transferred from stream to f
- let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
- ParcelFileDescriptor::new(f)
-}
-
-/// Parses the platform version requirement string.
-fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
- VersionReq::parse(s).map_err(|e| {
- Status::new_exception_str(
- ExceptionCode::BAD_PARCELABLE,
- Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
- )
- })
-}
-
-/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
-/// it doesn't require that T implements Clone.
-enum BorrowedOrOwned<'a, T> {
- Borrowed(&'a T),
- Owned(T),
-}
-
-impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
- fn as_ref(&self) -> &T {
- match self {
- Self::Borrowed(b) => b,
- Self::Owned(o) => o,
- }
- }
-}
-
-/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
-#[derive(Debug, Default)]
-struct VirtualMachineService {
- state: Arc<Mutex<State>>,
- cid: Cid,
-}
-
-impl Interface for VirtualMachineService {}
-
-impl IVirtualMachineService for VirtualMachineService {
- fn notifyPayloadStarted(&self) -> binder::Result<()> {
- let cid = self.cid;
- if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
- info!("VM with CID {} started payload", cid);
- vm.update_payload_state(PayloadState::Started).map_err(|e| {
- Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
- })?;
- vm.callbacks.notify_payload_started(cid);
-
- let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
- write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
- Ok(())
- } else {
- error!("notifyPayloadStarted is called from an unknown CID {}", cid);
- Err(Status::new_service_specific_error_str(
- -1,
- Some(format!("cannot find a VM with CID {}", cid)),
- ))
- }
- }
-
- fn notifyPayloadReady(&self) -> binder::Result<()> {
- let cid = self.cid;
- if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
- info!("VM with CID {} reported payload is ready", cid);
- vm.update_payload_state(PayloadState::Ready).map_err(|e| {
- Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
- })?;
- vm.callbacks.notify_payload_ready(cid);
- Ok(())
- } else {
- error!("notifyPayloadReady is called from an unknown CID {}", cid);
- Err(Status::new_service_specific_error_str(
- -1,
- Some(format!("cannot find a VM with CID {}", cid)),
- ))
- }
- }
-
- fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
- let cid = self.cid;
- if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
- info!("VM with CID {} finished payload", cid);
- vm.update_payload_state(PayloadState::Finished).map_err(|e| {
- Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
- })?;
- vm.callbacks.notify_payload_finished(cid, exit_code);
- Ok(())
- } else {
- error!("notifyPayloadFinished is called from an unknown CID {}", cid);
- Err(Status::new_service_specific_error_str(
- -1,
- Some(format!("cannot find a VM with CID {}", cid)),
- ))
- }
- }
-
- fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
- let cid = self.cid;
- if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
- info!("VM with CID {} encountered an error", cid);
- vm.update_payload_state(PayloadState::Finished).map_err(|e| {
- Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
- })?;
- vm.callbacks.notify_error(cid, error_code, message);
- Ok(())
- } else {
- error!("notifyError is called from an unknown CID {}", cid);
- Err(Status::new_service_specific_error_str(
- -1,
- Some(format!("cannot find a VM with CID {}", cid)),
- ))
- }
- }
-}
-
-impl VirtualMachineService {
- fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
- BnVirtualMachineService::new_binder(
- VirtualMachineService { state, cid },
- BinderFeatures::default(),
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_is_allowed_label_for_partition() -> Result<()> {
- let expected_results = vec![
- ("u:object_r:system_file:s0", true),
- ("u:object_r:apk_data_file:s0", true),
- ("u:object_r:app_data_file:s0", false),
- ("u:object_r:app_data_file:s0:c512,c768", false),
- ("u:object_r:privapp_data_file:s0:c512,c768", false),
- ("invalid", false),
- ("user:role:apk_data_file:severity:categories", true),
- ("user:role:apk_data_file:severity:categories:extraneous", false),
- ];
-
- for (label, expected_valid) in expected_results {
- let context = SeContext::new(label)?;
- let result = check_label_is_allowed(&context);
- if expected_valid {
- assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
- } else if result.is_ok() {
- bail!("Expected label {} to be disallowed", label);
- }
- }
- Ok(())
- }
-
- #[test]
- fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
- let apk = tempfile::tempfile().unwrap();
- let idsig = tempfile::tempfile().unwrap();
-
- let ret = create_or_update_idsig_file(
- &ParcelFileDescriptor::new(apk),
- &ParcelFileDescriptor::new(idsig),
- );
- assert!(ret.is_err(), "should fail");
- Ok(())
- }
-
- #[test]
- fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
- let tmp_dir = tempfile::TempDir::new().unwrap();
- let apk = File::open(tmp_dir.path()).unwrap();
- let idsig = tempfile::tempfile().unwrap();
-
- let ret = create_or_update_idsig_file(
- &ParcelFileDescriptor::new(apk),
- &ParcelFileDescriptor::new(idsig),
- );
- assert!(ret.is_err(), "should fail");
- Ok(())
- }
-
- /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
- /// on ext4 filesystem is passed.
- /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
- /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
- /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
- #[test]
- fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
- // APEXes are backed by the ext4.
- let apk = File::open("/apex/com.android.virt/").unwrap();
- let idsig = tempfile::tempfile().unwrap();
-
- let ret = create_or_update_idsig_file(
- &ParcelFileDescriptor::new(apk),
- &ParcelFileDescriptor::new(idsig),
- );
- assert!(ret.is_err(), "should fail");
- Ok(())
- }
-}
diff --git a/virtualizationservice/src/atom.rs b/virtualizationservice/src/atom.rs
index e430c74..47a1603 100644
--- a/virtualizationservice/src/atom.rs
+++ b/virtualizationservice/src/atom.rs
@@ -14,122 +14,16 @@
//! Functions for creating and collecting atoms.
-use crate::aidl::{clone_file, GLOBAL_SERVICE};
-use crate::crosvm::VmMetric;
-use crate::get_calling_uid;
use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
-use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
- IVirtualMachine::IVirtualMachine,
- VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
- VirtualMachineConfig::VirtualMachineConfig,
-};
-use android_system_virtualizationservice::binder::{Status, Strong};
use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
AtomVmBooted::AtomVmBooted,
AtomVmCreationRequested::AtomVmCreationRequested,
AtomVmExited::AtomVmExited,
};
-use anyhow::{anyhow, Result};
-use binder::ParcelFileDescriptor;
+use anyhow::Result;
use log::{trace, warn};
-use microdroid_payload_config::VmPayloadConfig;
use rustutils::system_properties;
use statslog_virtualization_rust::{vm_booted, vm_creation_requested, vm_exited};
-use std::thread;
-use std::time::{Duration, SystemTime};
-use zip::ZipArchive;
-
-fn get_apex_list(config: &VirtualMachineAppConfig) -> String {
- match &config.payload {
- Payload::PayloadConfig(_) => String::new(),
- Payload::ConfigPath(config_path) => {
- let vm_payload_config = get_vm_payload_config(&config.apk, config_path);
- if let Ok(vm_payload_config) = vm_payload_config {
- vm_payload_config
- .apexes
- .iter()
- .map(|x| x.name.clone())
- .collect::<Vec<String>>()
- .join(":")
- } else {
- "INFO: Can't get VmPayloadConfig".to_owned()
- }
- }
- }
-}
-
-fn get_vm_payload_config(
- apk_fd: &Option<ParcelFileDescriptor>,
- config_path: &str,
-) -> Result<VmPayloadConfig> {
- let apk = apk_fd.as_ref().ok_or_else(|| anyhow!("APK is none"))?;
- let apk_file = clone_file(apk)?;
- let mut apk_zip = ZipArchive::new(&apk_file)?;
- let config_file = apk_zip.by_name(config_path)?;
- let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
- Ok(vm_payload_config)
-}
-
-fn get_duration(vm_start_timestamp: Option<SystemTime>) -> Duration {
- match vm_start_timestamp {
- Some(vm_start_timestamp) => vm_start_timestamp.elapsed().unwrap_or_default(),
- None => Duration::default(),
- }
-}
-
-/// Write the stats of VMCreation to statsd
-pub fn write_vm_creation_stats(
- config: &VirtualMachineConfig,
- is_protected: bool,
- ret: &binder::Result<Strong<dyn IVirtualMachine>>,
-) {
- let creation_succeeded;
- let binder_exception_code;
- match ret {
- Ok(_) => {
- creation_succeeded = true;
- binder_exception_code = Status::ok().exception_code() as i32;
- }
- Err(ref e) => {
- creation_succeeded = false;
- binder_exception_code = e.exception_code() as i32;
- }
- }
- let (vm_identifier, config_type, num_cpus, memory_mib, apexes) = match config {
- VirtualMachineConfig::AppConfig(config) => (
- config.name.clone(),
- vm_creation_requested::ConfigType::VirtualMachineAppConfig,
- config.numCpus,
- config.memoryMib,
- get_apex_list(config),
- ),
- VirtualMachineConfig::RawConfig(config) => (
- config.name.clone(),
- vm_creation_requested::ConfigType::VirtualMachineRawConfig,
- config.numCpus,
- config.memoryMib,
- String::new(),
- ),
- };
-
- let atom = AtomVmCreationRequested {
- uid: get_calling_uid() as i32,
- vmIdentifier: vm_identifier,
- isProtected: is_protected,
- creationSucceeded: creation_succeeded,
- binderExceptionCode: binder_exception_code,
- configType: config_type as i32,
- numCpus: num_cpus,
- memoryMib: memory_mib,
- apexes,
- };
-
- thread::spawn(move || {
- GLOBAL_SERVICE.atomVmCreationRequested(&atom).unwrap_or_else(|e| {
- warn!("Failed to write VmCreationRequested atom: {e}");
- });
- });
-}
pub fn forward_vm_creation_atom(atom: &AtomVmCreationRequested) {
let config_type = match atom.configType {
@@ -164,29 +58,6 @@
}
}
-/// Write the stats of VM boot to statsd
-/// The function creates a separate thread which waits fro statsd to start to push atom
-pub fn write_vm_booted_stats(
- uid: i32,
- vm_identifier: &str,
- vm_start_timestamp: Option<SystemTime>,
-) {
- let vm_identifier = vm_identifier.to_owned();
- let duration = get_duration(vm_start_timestamp);
-
- let atom = AtomVmBooted {
- uid,
- vmIdentifier: vm_identifier,
- elapsedTimeMillis: duration.as_millis() as i64,
- };
-
- thread::spawn(move || {
- GLOBAL_SERVICE.atomVmBooted(&atom).unwrap_or_else(|e| {
- warn!("Failed to write VmCreationRequested atom: {e}");
- });
- });
-}
-
pub fn forward_vm_booted_atom(atom: &AtomVmBooted) {
let vm_booted = vm_booted::VmBooted {
uid: atom.uid,
@@ -201,38 +72,6 @@
}
}
-/// Write the stats of VM exit to statsd
-/// The function creates a separate thread which waits fro statsd to start to push atom
-pub fn write_vm_exited_stats(
- uid: i32,
- vm_identifier: &str,
- reason: DeathReason,
- exit_signal: Option<i32>,
- vm_metric: &VmMetric,
-) {
- let vm_identifier = vm_identifier.to_owned();
- let elapsed_time_millis = get_duration(vm_metric.start_timestamp).as_millis() as i64;
- let guest_time_millis = vm_metric.cpu_guest_time.unwrap_or_default();
- let rss = vm_metric.rss.unwrap_or_default();
-
- let atom = AtomVmExited {
- uid,
- vmIdentifier: vm_identifier,
- elapsedTimeMillis: elapsed_time_millis,
- deathReason: reason,
- guestTimeMillis: guest_time_millis,
- rssVmKb: rss.vm,
- rssCrosvmKb: rss.crosvm,
- exitSignal: exit_signal.unwrap_or_default(),
- };
-
- thread::spawn(move || {
- GLOBAL_SERVICE.atomVmExited(&atom).unwrap_or_else(|e| {
- warn!("Failed to write VmExited atom: {e}");
- });
- });
-}
-
pub fn forward_vm_exited_atom(atom: &AtomVmExited) {
let death_reason = match atom.deathReason {
DeathReason::INFRASTRUCTURE_ERROR => vm_exited::DeathReason::InfrastructureError,
diff --git a/virtualizationservice/src/main.rs b/virtualizationservice/src/main.rs
index 35eeff3..64ccb13 100644
--- a/virtualizationservice/src/main.rs
+++ b/virtualizationservice/src/main.rs
@@ -16,12 +16,11 @@
mod aidl;
mod atom;
-mod composite;
-mod crosvm;
-mod payload;
-mod selinux;
-use crate::aidl::{remove_temporary_dir, BINDER_SERVICE_IDENTIFIER, TEMPORARY_DIRECTORY, VirtualizationServiceInternal};
+use crate::aidl::{
+ remove_temporary_dir, BINDER_SERVICE_IDENTIFIER, TEMPORARY_DIRECTORY,
+ VirtualizationServiceInternal
+};
use android_logger::{Config, FilterBuilder};
use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::BnVirtualizationServiceInternal;
use anyhow::Error;
diff --git a/vm/Android.bp b/vm/Android.bp
index b95dca3..e217786 100644
--- a/vm/Android.bp
+++ b/vm/Android.bp
@@ -14,6 +14,7 @@
"libbinder_rs",
"libclap",
"libenv_logger",
+ "libglob",
"liblibc",
"liblog_rust",
"libmicrodroid_payload_config",
diff --git a/vm/src/run.rs b/vm/src/run.rs
index 6c21dbc..e229933 100644
--- a/vm/src/run.rs
+++ b/vm/src/run.rs
@@ -25,6 +25,7 @@
};
use anyhow::{anyhow, bail, Context, Error};
use binder::ParcelFileDescriptor;
+use glob::glob;
use microdroid_payload_config::VmPayloadConfig;
use rand::{distributions::Alphanumeric, Rng};
use std::fs;
@@ -32,7 +33,6 @@
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::path::{Path, PathBuf};
-use std::process::Command;
use vmclient::{ErrorCode, VmInstance};
use vmconfig::{open_parcel_file, VmConfig};
use zip::ZipArchive;
@@ -147,18 +147,16 @@
run(service, &config, &payload_config_str, console_path, log_path)
}
-const EMPTY_PAYLOAD_APK: &str = "com.android.microdroid.empty_payload";
-
fn find_empty_payload_apk_path() -> Result<PathBuf, Error> {
- let output = Command::new("/system/bin/pm")
- .arg("path")
- .arg(EMPTY_PAYLOAD_APK)
- .output()
- .context("failed to execute pm path")?;
- let output_str = String::from_utf8(output.stdout).context("failed to parse output")?;
- match output_str.strip_prefix("package:") {
- None => Err(anyhow!("Unexpected output {}", output_str)),
- Some(apk_path) => Ok(PathBuf::from(apk_path.trim())),
+ const GLOB_PATTERN: &str = "/apex/com.android.virt/app/**/EmptyPayloadApp.apk";
+ let mut entries: Vec<PathBuf> =
+ glob(GLOB_PATTERN).context("failed to glob")?.filter_map(|e| e.ok()).collect();
+ if entries.len() > 1 {
+ return Err(anyhow!("Found more than one apk matching {}", GLOB_PATTERN));
+ }
+ match entries.pop() {
+ Some(path) => Ok(path),
+ None => Err(anyhow!("No apks match {}", GLOB_PATTERN)),
}
}
@@ -187,9 +185,8 @@
cpus: Option<u32>,
task_profiles: Vec<String>,
) -> Result<(), Error> {
- let apk = find_empty_payload_apk_path()
- .context(anyhow!("failed to find path for {} apk", EMPTY_PAYLOAD_APK))?;
- println!("found path for {} apk: {}", EMPTY_PAYLOAD_APK, apk.display());
+ let apk = find_empty_payload_apk_path()?;
+ println!("found path {}", apk.display());
let work_dir = work_dir.unwrap_or(create_work_dir()?);
let idsig = work_dir.join("apk.idsig");
diff --git a/vm/vm_shell.sh b/vm/vm_shell.sh
index 3db7003..b73a9dc 100755
--- a/vm/vm_shell.sh
+++ b/vm/vm_shell.sh
@@ -66,12 +66,16 @@
fi
if [ ! -n "${selected_cid}" ]; then
- PS3="Select CID of VM to adb-shell into: "
- select cid in ${available_cids}
- do
- selected_cid=${cid}
- break
- done
+ if [ ${#selected_cid[@]} -eq 1 ]; then
+ selected_cid=${available_cids[0]}
+ else
+ PS3="Select CID of VM to adb-shell into: "
+ select cid in ${available_cids}
+ do
+ selected_cid=${cid}
+ break
+ done
+ fi
fi
if [[ ! " ${available_cids[*]} " =~ " ${selected_cid} " ]]; then
diff --git a/vm_payload/README.md b/vm_payload/README.md
index bcba9be..d5f5331 100644
--- a/vm_payload/README.md
+++ b/vm_payload/README.md
@@ -2,13 +2,14 @@
This directory contains the definition of the VM Payload API. This is a native
API, exposed as a set of C functions, available to payload code running inside a
-[Microdroid](../microdroid/README.md) VM.
+[Microdroid](https://android.googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/master/microdroid/README.md)
+VM.
Note that only native code is supported in Microdroid, so no Java APIs are
available in the VM, and only 64 bit code is supported.
To create a VM and run the payload from Android, see
-[android.system.virtualmachine.VirtualMachineManager](../javalib/src/android/system/virtualmachine/VirtualMachineManager.java).
+[android.system.virtualmachine.VirtualMachineManager](https://android.googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/master/javalib/src/android/system/virtualmachine/VirtualMachineManager.java).
## Entry point
@@ -16,7 +17,7 @@
under the `lib/<ABI>` directory, like other JNI code.
The primary .so, which is specified as part of the VM configuration via
-[VirtualMachineConfig.Builder#setPayloadBinaryPath](../javalib/src/android/system/virtualmachine/VirtualMachineConfig.java),
+[VirtualMachineConfig.Builder#setPayloadBinaryPath](https://android.googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/master/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java),
must define the entry point for the payload.
This entry point is a C function called `AVmPayload_main()`, as declared in
@@ -34,11 +35,12 @@
against a stub `libvm_payload.so`, where the dependencies will be satisfied at
runtime from the real `libvm_payload.so` hosted within the Microdroid VM.
-See `MicrodroidTestNativeLib` in the [test APK](../tests/testapk/Android.bp) for
-an example.
+See `MicrodroidTestNativeLib` in the [test
+APK](https://android.googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/master/tests/testapk/Android.bp)
+for an example.
In other build systems a similar stub `libvm_payload.so` can be built using
-[stub.c](stub/stub.c).
+[stub.c](stub/stub.c) and the [linker script](libvm_payload.map.txt).
## Available NDK APIs