Merge "Add authfs and fd_server to com.android.virt apex"
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index c654600..3eee6f4 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -56,10 +56,11 @@
"tombstoned",
"cgroups.json",
- // These two files are temporary and only for test.
+ // These files are temporary and only for test.
// TODO(b/178993690): migrate cil files to Soong
"microdroid_plat_sepolicy.cil",
"microdroid_plat_mapping_file",
+ "microdroid_plat_sepolicy_and_mapping.sha256",
] + microdroid_shell_and_utilities,
multilib: {
common: {
@@ -94,6 +95,8 @@
"microdroid_plat_sepolicy_vers.txt",
"microdroid_vendor_sepolicy.cil",
"microdroid_plat_pub_versioned.cil",
+ "microdroid_precompiled_sepolicy",
+ "microdroid_precompiled_sepolicy.plat_sepolicy_and_mapping.sha256",
],
avb_private_key: "microdroid.pem",
avb_algorithm: "SHA256_RSA4096",
@@ -135,15 +138,15 @@
bootimg {
name: "microdroid_boot-5.10",
ramdisk_module: "microdroid_ramdisk-5.10",
- enabled: false,
+ // We don't have kernel for arm and x86. But Soong demands one when it builds for
+ // arm or x86 target. Satisfy that by providing an empty file as the kernel.
+ kernel_prebuilt: "empty_kernel",
arch: {
arm64: {
kernel_prebuilt: ":kernel_prebuilts-5.10-arm64",
- enabled: true,
},
x86_64: {
kernel_prebuilt: ":kernel_prebuilts-5.10-x86_64",
- enabled: true,
},
},
// TODO(jiyong): change the name to init, cause it's confusing
@@ -186,15 +189,6 @@
header_version: "4",
vendor_boot: true,
partition_name: "vendor_boot",
- enabled: false,
- arch: {
- arm64: {
- enabled: true,
- },
- x86_64: {
- enabled: true,
- },
- },
}
android_filesystem {
@@ -244,3 +238,52 @@
out: ["output.img"],
cmd: "$(location mkenvimage_host) -s 4096 -o $(out) $(in)",
}
+
+genrule {
+ name: "microdroid_plat_sepolicy_and_mapping.sha256_gen",
+ srcs: [
+ ":microdroid_plat_sepolicy.cil",
+ ":microdroid_plat_mapping_file",
+ ],
+ out: ["plat_sepolicy_and_mapping.sha256"],
+ cmd: "cat $(in) | sha256sum | cut -d' ' -f1 > $(out)",
+}
+
+// sepolicy sha256 for system
+prebuilt_etc {
+ name: "microdroid_plat_sepolicy_and_mapping.sha256",
+ src: ":microdroid_plat_sepolicy_and_mapping.sha256_gen",
+ filename: "plat_sepolicy_and_mapping.sha256",
+ relative_install_path: "selinux",
+ installable: false,
+}
+
+// sepolicy sha256 for vendor (filename differs)
+prebuilt_etc {
+ name: "microdroid_precompiled_sepolicy.plat_sepolicy_and_mapping.sha256",
+ src: ":microdroid_plat_sepolicy_and_mapping.sha256_gen",
+ filename: "precompiled_sepolicy.plat_sepolicy_and_mapping.sha256",
+ relative_install_path: "selinux",
+ installable: false,
+}
+
+genrule {
+ name: "microdroid_precompiled_sepolicy_gen",
+ tools: ["secilc"],
+ srcs: [
+ ":microdroid_plat_sepolicy.cil",
+ ":microdroid_plat_mapping_file",
+ ":microdroid_plat_pub_versioned.cil",
+ ":microdroid_vendor_sepolicy.cil",
+ ],
+ out: ["precompiled_sepolicy"],
+ cmd: "$(location secilc) -m -M true -G -c 30 $(in) -o $(out) -f /dev/null",
+}
+
+prebuilt_etc {
+ name: "microdroid_precompiled_sepolicy",
+ src: ":microdroid_precompiled_sepolicy_gen",
+ filename: "precompiled_sepolicy",
+ relative_install_path: "selinux",
+ installable: false,
+}
diff --git a/microdroid/empty_kernel b/microdroid/empty_kernel
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/microdroid/empty_kernel
diff --git a/tests/hostside/Android.bp b/tests/hostside/Android.bp
new file mode 100644
index 0000000..e07459a
--- /dev/null
+++ b/tests/hostside/Android.bp
@@ -0,0 +1,27 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+java_test_host {
+ name: "MicrodroidHostTestCases",
+ srcs: ["java/**/*.java"],
+ test_suites: ["device-tests"],
+ libs: ["tradefed"],
+ data: [
+ ":microdroid_super",
+ ":microdroid_boot-5.10",
+ ":microdroid_vendor_boot-5.10",
+ ":microdroid_uboot_env",
+ ":cuttlefish_crosvm_bootloader",
+ ":MicrodroidHostTestCase_EmptyImage",
+ ],
+}
+
+genrule {
+ name: "MicrodroidHostTestCase_EmptyImage",
+ tools: ["mke2fs"],
+ out: ["empty.img"],
+ cmd: "dd if=/dev/zero of=$(out) bs=4k count=600 &&" +
+ "$(location mke2fs) -t ext4 $(out)",
+ visibility: ["//visibility:private"],
+}
diff --git a/tests/hostside/AndroidTest.xml b/tests/hostside/AndroidTest.xml
new file mode 100644
index 0000000..da24b71
--- /dev/null
+++ b/tests/hostside/AndroidTest.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 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.
+-->
+<configuration description="Tests for microdroid">
+ <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer">
+ <option name="force-root" value="true" />
+ </target_preparer>
+
+ <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+ <option name="jar" value="MicrodroidHostTestCases.jar" />
+ </test>
+</configuration>
diff --git a/tests/hostside/java/android/virt/test/MicrodroidTestCase.java b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
new file mode 100644
index 0000000..7a45a8c
--- /dev/null
+++ b/tests/hostside/java/android/virt/test/MicrodroidTestCase.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 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.
+ */
+
+package android.virt.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.junit.Assert.assertThat;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.RunUtil;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class MicrodroidTestCase extends BaseHostJUnit4Test {
+ private static final String TEST_ROOT = "/data/local/tmp/virt/";
+ private static final String VIRT_APEX = "/apex/com.android.virt/";
+ private static final int TEST_VM_CID = 5;
+ private static final int TEST_VM_ADB_PORT = 8000;
+ private static final String MICRODROID_SERIAL = "localhost:" + TEST_VM_ADB_PORT;
+ private static final long MICRODROID_BOOT_TIMEOUT_MILLIS = 15000;
+
+ private void pushFile(String localName, String remoteName) {
+ try {
+ File localFile = getTestInformation().getDependencyFile(localName, false);
+ Path remotePath = Paths.get(TEST_ROOT, remoteName);
+ getDevice().executeShellCommand("mkdir -p " + remotePath.getParent());
+ getDevice().pushFile(localFile, remotePath.toString());
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private String executeCommand(String cmd) {
+ final long defaultCommandTimeoutMillis = 1000; // 1 sec
+ return executeCommand(defaultCommandTimeoutMillis, cmd);
+ }
+
+ private String executeCommand(long timeout, String cmd) {
+ CommandResult result = RunUtil.getDefault().runTimedCmd(timeout, cmd.split(" "));
+ return result.getStdout().trim(); // remove the trailing whitespace including newline
+ }
+
+ @Test
+ public void testMicrodroidBoots() throws Exception {
+ // Prepare input files
+ pushFile("u-boot.bin", "bootloader");
+ pushFile("microdroid_super.img", "super.img");
+ pushFile("microdroid_boot-5.10.img", "boot.img");
+ pushFile("microdroid_vendor_boot-5.10.img", "vendor_boot.img");
+ pushFile("uboot_env.img", "cuttlefish_runtime.1/uboot_env.img");
+ pushFile("empty.img", "userdata.img");
+ pushFile("empty.img", "vbmeta.img");
+ pushFile("empty.img", "vbmeta_system.img");
+ pushFile("empty.img", "cache.img");
+ getDevice().executeShellCommand("mkdir -p " + TEST_ROOT + "etc/cvd_config");
+ getDevice().pushString("{}", TEST_ROOT + "etc/cvd_config/cvd_config_phone.json");
+
+ // Run assemble_cvd to create composite.img
+ getDevice().executeShellCommand("HOME=" + TEST_ROOT + "; "
+ + "PATH=$PATH:" + VIRT_APEX + "bin; "
+ + VIRT_APEX + "bin/assemble_cvd < /dev/null");
+
+ // Make sure that composite.img is created
+ final String compositeImg = TEST_ROOT + "cuttlefish_runtime/composite.img";
+ CommandResult result = getDevice().executeShellV2Command("du -b " + compositeImg);
+ assertThat(result.getExitCode(), is(0));
+ assertThat(result.getStdout(), is(not("")));
+
+ // Start microdroid using crosvm
+ ExecutorService executor = Executors.newFixedThreadPool(1);
+ executor.execute(() -> {
+ try {
+ getDevice().executeShellV2Command("cd " + TEST_ROOT + "; "
+ + VIRT_APEX + "bin/crosvm run "
+ + "--cid=" + TEST_VM_CID + " "
+ + "--disable-sandbox "
+ + "--bios=bootloader "
+ + "--serial=type=syslog "
+ + "--disk=cuttlefish_runtime/composite.img");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ // .. and wait for microdroid to boot
+ // TODO(jiyong): don't wait too long. We can wait less by monitoring log from microdroid
+ Thread.sleep(MICRODROID_BOOT_TIMEOUT_MILLIS);
+
+ // Connect to microdroid and read a system property from there
+ executeCommand("adb forward tcp:" + TEST_VM_ADB_PORT + " vsock:" + TEST_VM_CID + ":5555");
+ executeCommand("adb connect " + MICRODROID_SERIAL);
+ String prop = executeCommand("adb -s " + MICRODROID_SERIAL + " shell getprop ro.hardware");
+ assertThat(prop, is("microdroid"));
+
+ // Shutdown microdroid
+ executeCommand("adb -s localhost:" + TEST_VM_ADB_PORT + " shell reboot");
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ // delete the test root
+ getDevice().executeShellCommand("rm -rf " + TEST_ROOT);
+
+ // disconnect from microdroid
+ executeCommand("adb disconnect " + MICRODROID_SERIAL);
+ }
+
+ @After
+ public void shutdown() throws Exception {
+ // disconnect from microdroid
+ executeCommand("adb disconnect " + MICRODROID_SERIAL);
+
+ // kill stale crosvm processes
+ getDevice().executeShellV2Command("killall crosvm");
+ }
+}
diff --git a/virtmanager/aidl/android/system/virtmanager/IVirtManager.aidl b/virtmanager/aidl/android/system/virtmanager/IVirtManager.aidl
index ade8717..a401fe6 100644
--- a/virtmanager/aidl/android/system/virtmanager/IVirtManager.aidl
+++ b/virtmanager/aidl/android/system/virtmanager/IVirtManager.aidl
@@ -16,8 +16,15 @@
package android.system.virtmanager;
import android.system.virtmanager.IVirtualMachine;
+import android.system.virtmanager.VirtualMachineDebugInfo;
interface IVirtManager {
- /** Start the VM with the given config file, and return a handle to it. */
- IVirtualMachine startVm(String configPath);
+ /** Start the VM with the given config file, and return a handle to it. */
+ IVirtualMachine startVm(String configPath);
+
+ /**
+ * 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.
+ */
+ VirtualMachineDebugInfo[] debugListVms();
}
diff --git a/virtmanager/aidl/android/system/virtmanager/IVirtualMachine.aidl b/virtmanager/aidl/android/system/virtmanager/IVirtualMachine.aidl
index 5f408f8..0358bfd 100644
--- a/virtmanager/aidl/android/system/virtmanager/IVirtualMachine.aidl
+++ b/virtmanager/aidl/android/system/virtmanager/IVirtualMachine.aidl
@@ -16,6 +16,6 @@
package android.system.virtmanager;
interface IVirtualMachine {
- /** Get the CID allocated to the VM. */
- int getCid();
+ /** Get the CID allocated to the VM. */
+ int getCid();
}
diff --git a/virtmanager/aidl/android/system/virtmanager/VirtualMachineDebugInfo.aidl b/virtmanager/aidl/android/system/virtmanager/VirtualMachineDebugInfo.aidl
new file mode 100644
index 0000000..d877a56
--- /dev/null
+++ b/virtmanager/aidl/android/system/virtmanager/VirtualMachineDebugInfo.aidl
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+package android.system.virtmanager;
+
+/** Information about a running VM, for debug purposes only. */
+parcelable VirtualMachineDebugInfo {
+ /** The CID assigned to the VM. */
+ int cid;
+
+ /**
+ * The filename of the config file used to start the VM. This may have changed since it was
+ * read so it shouldn't be trusted; it is only stored for debugging purposes.
+ */
+ String configPath;
+}
diff --git a/virtmanager/src/aidl.rs b/virtmanager/src/aidl.rs
index 8394e36..1b3819f 100644
--- a/virtmanager/src/aidl.rs
+++ b/virtmanager/src/aidl.rs
@@ -21,12 +21,17 @@
use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{
BnVirtualMachine, IVirtualMachine,
};
-use android_system_virtmanager::binder::{self, Interface, StatusCode, Strong};
+use android_system_virtmanager::aidl::android::system::virtmanager::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
+use android_system_virtmanager::binder::{self, Interface, StatusCode, Strong, ThreadState};
use log::error;
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, Mutex, Weak};
pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
+// TODO(qwandor): Use PermissionController once it is available to Rust.
+/// Only processes running with one of these UIDs are allowed to call debug methods.
+const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
+
/// Implementation of `IVirtManager`, the entry point of the AIDL service.
#[derive(Debug, Default)]
pub struct VirtManager {
@@ -42,11 +47,38 @@
fn startVm(&self, config_path: &str) -> binder::Result<Strong<dyn IVirtualMachine>> {
let state = &mut *self.state.lock().unwrap();
let cid = state.next_cid;
- let instance = start_vm(config_path, cid)?;
+ let instance = Arc::new(start_vm(config_path, cid)?);
// TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
state.next_cid = state.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?;
- Ok(VirtualMachine::create(Arc::new(instance)))
+ state.add_vm(Arc::downgrade(&instance));
+ Ok(VirtualMachine::create(instance))
}
+
+ /// 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>> {
+ if !debug_access_allowed() {
+ return Err(StatusCode::PERMISSION_DENIED.into());
+ }
+
+ let state = &mut *self.state.lock().unwrap();
+ let vms = state.vms();
+ let cids = vms
+ .into_iter()
+ .map(|vm| VirtualMachineDebugInfo {
+ cid: vm.cid as i32,
+ configPath: vm.config_path.clone(),
+ })
+ .collect();
+ Ok(cids)
+ }
+}
+
+/// Check whether the caller of the current Binder method is allowed to call debug methods.
+fn debug_access_allowed() -> bool {
+ let uid = ThreadState::get_calling_uid();
+ log::trace!("Debug method call from UID {}.", uid);
+ DEBUG_ALLOWED_UIDS.contains(&uid)
}
/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
@@ -73,12 +105,36 @@
/// The mutable state of the Virt Manager. There should only be one instance of this struct.
#[derive(Debug)]
struct State {
+ /// The next available unused CID.
next_cid: Cid,
+
+ /// 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 are currently running.
+ 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);
+ }
}
impl Default for State {
fn default() -> Self {
- State { next_cid: FIRST_GUEST_CID }
+ State { next_cid: FIRST_GUEST_CID, vms: vec![] }
}
}
@@ -89,7 +145,7 @@
error!("Failed to load VM config {}: {:?}", config_path, e);
StatusCode::BAD_VALUE
})?;
- Ok(VmInstance::start(&config, cid).map_err(|e| {
+ Ok(VmInstance::start(&config, cid, config_path).map_err(|e| {
error!("Failed to start VM {}: {:?}", config_path, e);
StatusCode::UNKNOWN_ERROR
})?)
diff --git a/virtmanager/src/crosvm.rs b/virtmanager/src/crosvm.rs
index 057b791..4ae1fcd 100644
--- a/virtmanager/src/crosvm.rs
+++ b/virtmanager/src/crosvm.rs
@@ -29,19 +29,22 @@
child: Child,
/// The CID assigned to the VM for vsock communication.
pub cid: Cid,
+ /// The filename of the config file that was used to start the VM. This may have changed since
+ /// it was read so it shouldn't be trusted; it is only stored for debugging purposes.
+ pub config_path: String,
}
impl VmInstance {
/// Create a new `VmInstance` for the given process.
- fn new(child: Child, cid: Cid) -> VmInstance {
- VmInstance { child, cid }
+ fn new(child: Child, cid: Cid, config_path: &str) -> VmInstance {
+ VmInstance { child, cid, config_path: config_path.to_owned() }
}
/// Start an instance of `crosvm` to manage a new VM. The `crosvm` instance will be killed when
/// the `VmInstance` is dropped.
- pub fn start(config: &VmConfig, cid: Cid) -> Result<VmInstance, Error> {
+ pub fn start(config: &VmConfig, cid: Cid, config_path: &str) -> Result<VmInstance, Error> {
let child = run_vm(config, cid)?;
- Ok(VmInstance::new(child, cid))
+ Ok(VmInstance::new(child, cid, config_path))
}
}
diff --git a/vm/src/main.rs b/vm/src/main.rs
index 1e642cb..df375e4 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -35,25 +35,27 @@
if args.len() < 2 {
eprintln!("Usage:");
eprintln!(" {} run <vm_config.json>", args[0]);
+ eprintln!(" {} list", args[0]);
exit(1);
}
// We need to start the thread pool for Binder to work properly, especially link_to_death.
ProcessState::start_thread_pool();
+ let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
+ .context("Failed to find Virt Manager service")?;
+
match args[1].as_ref() {
- "run" if args.len() == 3 => command_run(&args[2]),
+ "run" if args.len() == 3 => command_run(virt_manager, &args[2]),
+ "list" if args.len() == 2 => command_list(virt_manager),
command => bail!("Invalid command '{}' or wrong number of arguments", command),
}
}
/// Run a VM from the given configuration file.
-fn command_run(config_filename: &str) -> Result<(), Error> {
- let virt_manager: Strong<dyn IVirtManager> =
- get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
- .with_context(|| "Failed to find Virt Manager service")?;
- let vm = virt_manager.startVm(config_filename).with_context(|| "Failed to start VM")?;
- let cid = vm.getCid().with_context(|| "Failed to get CID")?;
+fn command_run(virt_manager: Strong<dyn IVirtManager>, config_filename: &str) -> Result<(), Error> {
+ let vm = virt_manager.startVm(config_filename).context("Failed to start VM")?;
+ let cid = vm.getCid().context("Failed to get CID")?;
println!("Started VM from {} with CID {}.", config_filename, cid);
// Wait until the VM dies. If we just returned immediately then the IVirtualMachine Binder
@@ -63,6 +65,13 @@
Ok(())
}
+/// List the VMs currently running.
+fn command_list(virt_manager: Strong<dyn IVirtManager>) -> Result<(), Error> {
+ let vms = virt_manager.debugListVms().context("Failed to get list of VMs")?;
+ println!("Running VMs: {:#?}", vms);
+ Ok(())
+}
+
/// Block until the given Binder object dies.
fn wait_for_death(binder: &mut impl IBinder) -> Result<(), Error> {
let dead = AtomicFlag::default();