Merge "Add MicrodroidHostTestCases"
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index f19abd1..a6b1f95 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -1,7 +1,12 @@
 [Builtin Hooks]
+aidl_format = true
+android_test_mapping_format = true
 bpfmt = true
 clang_format = true
+jsonlint = true
+pylint3 = true
 rustfmt = true
+xmllint = true
 
 [Builtin Hooks Options]
 clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp
diff --git a/apex/Android.bp b/apex/Android.bp
index 0985577..50c17f6 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -29,6 +29,7 @@
     binaries: [
         "assemble_cvd",
         "virtmanager",
+        "vm",
     ],
     filesystems: ["microdroid"],
 }
diff --git a/authfs/src/main.rs b/authfs/src/main.rs
index 74553f5..41b922d 100644
--- a/authfs/src/main.rs
+++ b/authfs/src/main.rs
@@ -27,7 +27,7 @@
 //! Regardless of the actual file name, the exposed file names through AuthFS are currently integer,
 //! e.g. /mountpoint/42.
 
-use anyhow::{anyhow, bail, Result};
+use anyhow::{bail, Context, Result};
 use std::collections::BTreeMap;
 use std::fs::File;
 use std::io::Read;
@@ -180,9 +180,7 @@
 
 fn new_config_remote_verified_file(remote_id: i32, file_size: u64) -> Result<FileConfig> {
     let service = remote_file::server::get_local_service();
-    let signature = service
-        .readFsveritySignature(remote_id)
-        .map_err(|e| anyhow!("Failed to read signature: {}", e.get_description()))?;
+    let signature = service.readFsveritySignature(remote_id).context("Failed to read signature")?;
 
     let service = Arc::new(Mutex::new(service));
     let authenticator = FakeAuthenticator::always_succeed();
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index 945a27a..3eee6f4 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -14,14 +14,8 @@
     "proc",
     "sys",
 
-    // TODO(b/180267599): clean up unnecessary partition mount points
     "system",
-    "system_ext",
     "vendor",
-    "vendor_dlkm",
-    "product",
-    "odm",
-    "odm_dlkm",
     "debug_ramdisk",
     "mnt",
 
@@ -62,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: {
@@ -100,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",
@@ -241,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/README.md b/microdroid/README.md
index e6cbec8..fe0843f 100644
--- a/microdroid/README.md
+++ b/microdroid/README.md
@@ -52,7 +52,7 @@
 future, this shall be done via [`virtmanager`](../virtmanager/).
 
 ```
-$ adb shell 'HOME=/data/local/tmp; /apex/com.android.virt/bin/assemble_cvd < /dev/null'
+$ adb shell 'HOME=/data/local/tmp; PATH=$PATH:/apex/com.android.virt/bin; assemble_cvd < /dev/null'
 $ adb shell 'cd /data/local/tmp; /apex/com.android.virt/bin/crosvm run --cid=5 --disable-sandbox --bios=bootloader --serial=type=stdout --disk=cuttlefish_runtime/composite.img'
 ```
 
diff --git a/microdroid/init.rc b/microdroid/init.rc
index 2c32b28..e70fb77 100644
--- a/microdroid/init.rc
+++ b/microdroid/init.rc
@@ -113,40 +113,12 @@
     seclabel u:r:shell:s0
     setenv HOSTNAME console
 
-service servicemanager /system/bin/servicemanager
-    class core animation
-    user system
-    group system readproc
-    critical
-    # TODO(b/179342589): uncomment after turning off APEX session on microdroid
-    # onrestart restart apexd
-    onrestart class_restart main
-    shutdown critical
-
-service logd /system/bin/logd
-    socket logd stream 0666 logd logd
-    socket logdr seqpacket 0666 logd logd
-    socket logdw dgram+passcred 0222 logd logd
-    file /proc/kmsg r
-    file /dev/kmsg w
-    user logd
-    group logd system package_info readproc
-    capabilities SYSLOG AUDIT_CONTROL
-    priority 10
-
-service logd-reinit /system/bin/logd --reinit
-    oneshot
+# TODO(b/181093750): remove these after adding apex support
+service adbd /system/bin/adbd --root_seclabel=u:r:su:s0
+    class core
+    socket adbd seqpacket 660 system system
     disabled
-    user logd
-    group logd
-
-# Limit SELinux denial generation to 5/second
-service logd-auditctl /system/bin/auditctl -r 5
-    oneshot
-    disabled
-    user logd
-    group logd
-    capabilities AUDIT_CONTROL
+    seclabel u:r:adbd:s0
 
 on fs
     write /dev/event-log-tags "# content owned by logd
@@ -157,26 +129,3 @@
 on property:sys.boot_completed=1
     start logd-auditctl
 
-service adbd /system/bin/adbd --root_seclabel=u:r:su:s0
-    class core
-    socket adbd seqpacket 660 system system
-    disabled
-    seclabel u:r:adbd:s0
-
-#TODO(b/179342589): uncomment after turning off APEX session on microdroid
-#service apexd /system/bin/apexd
-#    interface aidl apexservice
-#    class core
-#    user root
-#    group system
-#    oneshot
-#    disabled # does not start with the core class
-#    reboot_on_failure reboot,apexd-failed
-
-service apexd-bootstrap /system/bin/apexd --bootstrap
-    user root
-    group system
-    oneshot
-    disabled
-    reboot_on_failure reboot,bootloader,bootstrap-apexd-failed
-
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
new file mode 100644
index 0000000..1b3819f
--- /dev/null
+++ b/virtmanager/src/aidl.rs
@@ -0,0 +1,152 @@
+// 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 Virt Manager.
+
+use crate::config::load_vm_config;
+use crate::crosvm::VmInstance;
+use crate::{Cid, FIRST_GUEST_CID};
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager;
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{
+    BnVirtualMachine, IVirtualMachine,
+};
+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, 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 {
+    state: Mutex<State>,
+}
+
+impl Interface for VirtManager {}
+
+impl IVirtManager for VirtManager {
+    /// Create and 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 startVm(&self, config_path: &str) -> binder::Result<Strong<dyn IVirtualMachine>> {
+        let state = &mut *self.state.lock().unwrap();
+        let cid = state.next_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)?;
+        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.
+#[derive(Debug)]
+struct VirtualMachine {
+    instance: Arc<VmInstance>,
+}
+
+impl VirtualMachine {
+    fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
+        let binder = VirtualMachine { instance };
+        BnVirtualMachine::new_binder(binder)
+    }
+}
+
+impl Interface for VirtualMachine {}
+
+impl IVirtualMachine for VirtualMachine {
+    fn getCid(&self) -> binder::Result<i32> {
+        Ok(self.instance.cid as i32)
+    }
+}
+
+/// 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, vms: vec![] }
+    }
+}
+
+/// Start a new VM instance from the given VM config filename. This assumes the VM is not already
+/// running.
+fn start_vm(config_path: &str, cid: Cid) -> binder::Result<VmInstance> {
+    let config = load_vm_config(config_path).map_err(|e| {
+        error!("Failed to load VM config {}: {:?}", config_path, e);
+        StatusCode::BAD_VALUE
+    })?;
+    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/config.rs b/virtmanager/src/config.rs
new file mode 100644
index 0000000..c0d23f0
--- /dev/null
+++ b/virtmanager/src/config.rs
@@ -0,0 +1,68 @@
+// 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.
+
+//! Function and types for VM configuration.
+
+use anyhow::{bail, Context, Error};
+use serde::{Deserialize, Serialize};
+use std::fs::File;
+use std::io::BufReader;
+
+/// Configuration for a particular VM to be started.
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct VmConfig {
+    /// The filename of the kernel image, if any.
+    pub kernel: Option<String>,
+    /// The filename of the initial ramdisk for the kernel, if any.
+    pub initrd: Option<String>,
+    /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
+    /// just a string, but typically it will contain multiple parameters separated by spaces.
+    pub params: Option<String>,
+    /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
+    /// the bootloader is instead responsibly for loading the kernel from one of the disks.
+    pub bootloader: Option<String>,
+    /// Disk images to be made available to the VM.
+    #[serde(default)]
+    pub disks: Vec<DiskImage>,
+}
+
+impl VmConfig {
+    /// Ensure that the configuration has a valid combination of fields set, or return an error if
+    /// not.
+    pub fn validate(&self) -> Result<(), Error> {
+        if self.bootloader.is_none() && self.kernel.is_none() {
+            bail!("VM must have either a bootloader or a kernel image.");
+        }
+        if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
+            bail!("Can't have both bootloader and kernel/initrd image.");
+        }
+        Ok(())
+    }
+}
+
+/// A disk image to be made available to the VM.
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct DiskImage {
+    /// The filename of the disk image.
+    pub image: String,
+    /// Whether this disk should be writable by the VM.
+    pub writable: bool,
+}
+
+/// Load the configuration for the VM with the given ID from a JSON file.
+pub fn load_vm_config(path: &str) -> Result<VmConfig, Error> {
+    let file = File::open(path).with_context(|| format!("Failed to open {}", path))?;
+    let buffered = BufReader::new(file);
+    Ok(serde_json::from_reader(buffered)?)
+}
diff --git a/virtmanager/src/crosvm.rs b/virtmanager/src/crosvm.rs
new file mode 100644
index 0000000..4ae1fcd
--- /dev/null
+++ b/virtmanager/src/crosvm.rs
@@ -0,0 +1,93 @@
+// 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.
+
+//! Functions for running instances of `crosvm`.
+
+use crate::config::VmConfig;
+use crate::Cid;
+use anyhow::Error;
+use log::{debug, error, info};
+use std::process::{Child, Command};
+
+const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
+
+/// Information about a particular instance of a VM which is running.
+#[derive(Debug)]
+pub struct VmInstance {
+    /// The crosvm child process.
+    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, 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, config_path: &str) -> Result<VmInstance, Error> {
+        let child = run_vm(config, cid)?;
+        Ok(VmInstance::new(child, cid, config_path))
+    }
+}
+
+impl Drop for VmInstance {
+    fn drop(&mut self) {
+        debug!("Dropping {:?}", self);
+        // TODO: Talk to crosvm to shutdown cleanly.
+        if let Err(e) = self.child.kill() {
+            error!("Error killing crosvm instance: {}", e);
+        }
+        // We need to wait on the process after killing it to avoid zombies.
+        match self.child.wait() {
+            Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
+            Ok(status) => info!("Crosvm exited with status {}", status),
+        }
+    }
+}
+
+/// Start an instance of `crosvm` to manage a new VM.
+fn run_vm(config: &VmConfig, cid: Cid) -> Result<Child, Error> {
+    config.validate()?;
+
+    let mut command = Command::new(CROSVM_PATH);
+    // TODO(qwandor): Remove --disable-sandbox.
+    command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
+    // TODO(jiyong): Don't redirect console to the host syslog
+    command.arg("--serial=type=syslog");
+    if let Some(bootloader) = &config.bootloader {
+        command.arg("--bios").arg(bootloader);
+    }
+    if let Some(initrd) = &config.initrd {
+        command.arg("--initrd").arg(initrd);
+    }
+    if let Some(params) = &config.params {
+        command.arg("--params").arg(params);
+    }
+    for disk in &config.disks {
+        command.arg(if disk.writable { "--rwdisk" } else { "--disk" }).arg(&disk.image);
+    }
+    if let Some(kernel) = &config.kernel {
+        command.arg(kernel);
+    }
+    info!("Running {:?}", command);
+    // TODO: Monitor child process, and remove from VM map if it dies.
+    Ok(command.spawn()?)
+}
diff --git a/virtmanager/src/main.rs b/virtmanager/src/main.rs
index bdb89d2..7cca4a9 100644
--- a/virtmanager/src/main.rs
+++ b/virtmanager/src/main.rs
@@ -14,200 +14,27 @@
 
 //! Android Virt Manager
 
-use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::{
-    BnVirtManager, IVirtManager,
-};
-use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{
-    BnVirtualMachine, IVirtualMachine,
-};
-use android_system_virtmanager::binder::{self, add_service, Interface, StatusCode, Strong};
-use anyhow::{bail, Context, Error};
-use log::{debug, error, info};
-use serde::{Deserialize, Serialize};
-use std::fs::File;
-use std::io::BufReader;
-use std::process::{Child, Command};
-use std::sync::{Arc, Mutex};
+mod aidl;
+mod config;
+mod crosvm;
+
+use crate::aidl::{VirtManager, BINDER_SERVICE_IDENTIFIER};
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::BnVirtManager;
+use android_system_virtmanager::binder::{add_service, ProcessState};
+use log::info;
 
 /// The first CID to assign to a guest VM managed by the Virt Manager. CIDs lower than this are
 /// reserved for the host or other usage.
 const FIRST_GUEST_CID: Cid = 10;
 
-const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
-const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
-
 /// The unique ID of a VM used (together with a port number) for vsock communication.
 type Cid = u32;
 
-/// Configuration for a particular VM to be started.
-#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
-struct VmConfig {
-    kernel: Option<String>,
-    initrd: Option<String>,
-    params: Option<String>,
-    bootloader: Option<String>,
-    #[serde(default)]
-    disks: Vec<DiskImage>,
-}
-
-/// A disk image to be made available to the VM.
-#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
-struct DiskImage {
-    image: String,
-    writable: bool,
-}
-
 fn main() {
     env_logger::init();
-    let state = Arc::new(Mutex::new(State::new()));
-    let virt_manager = VirtManager::new(state);
+    let virt_manager = VirtManager::default();
     let virt_manager = BnVirtManager::new_binder(virt_manager);
     add_service(BINDER_SERVICE_IDENTIFIER, virt_manager.as_binder()).unwrap();
     info!("Registered Binder service, joining threadpool.");
-    binder::ProcessState::join_thread_pool();
-}
-
-#[derive(Debug)]
-struct VirtManager {
-    state: Arc<Mutex<State>>,
-}
-
-impl VirtManager {
-    fn new(state: Arc<Mutex<State>>) -> Self {
-        VirtManager { state }
-    }
-}
-
-impl Interface for VirtManager {}
-
-impl IVirtManager for VirtManager {
-    /// Create and 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 startVm(&self, config_path: &str) -> binder::Result<Strong<dyn IVirtualMachine>> {
-        let state = &mut *self.state.lock().unwrap();
-        let cid = state.next_cid;
-        let child = 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(VmInstance::new(child, cid))))
-    }
-}
-
-/// 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> {
-        let binder = VirtualMachine { instance };
-        BnVirtualMachine::new_binder(binder)
-    }
-}
-
-impl Interface for VirtualMachine {}
-
-impl IVirtualMachine for VirtualMachine {
-    fn getCid(&self) -> binder::Result<i32> {
-        Ok(self.instance.cid as i32)
-    }
-}
-
-/// Information about a particular instance of a VM which is running.
-#[derive(Debug)]
-struct VmInstance {
-    /// The crosvm child process.
-    child: Child,
-    /// The CID assigned to the VM for vsock communication.
-    cid: Cid,
-}
-
-impl VmInstance {
-    /// Create a new `VmInstance` with a single reference for the given process.
-    fn new(child: Child, cid: Cid) -> VmInstance {
-        VmInstance { child, cid }
-    }
-}
-
-impl Drop for VmInstance {
-    fn drop(&mut self) {
-        debug!("Dropping {:?}", self);
-        // TODO: Talk to crosvm to shutdown cleanly.
-        if let Err(e) = self.child.kill() {
-            error!("Error killing crosvm instance: {}", e);
-        }
-        // We need to wait on the process after killing it to avoid zombies.
-        match self.child.wait() {
-            Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
-            Ok(status) => info!("Crosvm exited with status {}", status),
-        }
-    }
-}
-
-/// The mutable state of the Virt Manager. There should only be one instance of this struct.
-#[derive(Debug)]
-struct State {
-    next_cid: Cid,
-}
-
-impl State {
-    fn new() -> Self {
-        State { next_cid: FIRST_GUEST_CID }
-    }
-}
-
-/// Start a new VM instance from the given VM config filename. This assumes the VM is not already
-/// running.
-fn start_vm(config_path: &str, cid: Cid) -> binder::Result<Child> {
-    let config = load_vm_config(config_path).map_err(|e| {
-        error!("Failed to load VM config {}: {:?}", config_path, e);
-        StatusCode::BAD_VALUE
-    })?;
-    Ok(run_vm(&config, cid).map_err(|e| {
-        error!("Failed to start VM {}: {:?}", config_path, e);
-        StatusCode::UNKNOWN_ERROR
-    })?)
-}
-
-/// Load the configuration for the VM with the given ID from a JSON file.
-fn load_vm_config(path: &str) -> Result<VmConfig, Error> {
-    let file = File::open(path).with_context(|| format!("Failed to open {}", path))?;
-    let buffered = BufReader::new(file);
-    Ok(serde_json::from_reader(buffered)?)
-}
-
-/// Start an instance of `crosvm` to manage a new VM.
-fn run_vm(config: &VmConfig, cid: Cid) -> Result<Child, Error> {
-    if config.bootloader.is_none() && config.kernel.is_none() {
-        bail!("VM must have either a bootloader or a kernel image.");
-    }
-    if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
-        bail!("Can't have both bootloader and kernel/initrd image.");
-    }
-
-    let mut command = Command::new(CROSVM_PATH);
-    // TODO(qwandor): Remove --disable-sandbox.
-    command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
-    // TODO(jiyong): Don't redirect console to the host syslog
-    command.arg("--serial=type=syslog");
-    if let Some(bootloader) = &config.bootloader {
-        command.arg("--bios").arg(bootloader);
-    }
-    if let Some(initrd) = &config.initrd {
-        command.arg("--initrd").arg(initrd);
-    }
-    if let Some(params) = &config.params {
-        command.arg("--params").arg(params);
-    }
-    for disk in &config.disks {
-        command.arg(if disk.writable { "--rwdisk" } else { "--disk" }).arg(&disk.image);
-    }
-    if let Some(kernel) = &config.kernel {
-        command.arg(kernel);
-    }
-    info!("Running {:?}", command);
-    // TODO: Monitor child process, and remove from VM map if it dies.
-    Ok(command.spawn()?)
+    ProcessState::join_thread_pool();
 }
diff --git a/vm/Android.bp b/vm/Android.bp
new file mode 100644
index 0000000..0de6cae
--- /dev/null
+++ b/vm/Android.bp
@@ -0,0 +1,20 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_binary {
+    name: "vm",
+    crate_name: "vm",
+    srcs: ["src/main.rs"],
+    edition: "2018",
+    rustlibs: [
+        "android.system.virtmanager-rust",
+        "libanyhow",
+        "libbinder_rs",
+        "libenv_logger",
+        "liblog_rust",
+    ],
+    apex_available: [
+        "com.android.virt",
+    ],
+}
diff --git a/vm/src/main.rs b/vm/src/main.rs
new file mode 100644
index 0000000..df375e4
--- /dev/null
+++ b/vm/src/main.rs
@@ -0,0 +1,87 @@
+// 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.
+
+//! Android VM control tool.
+
+mod sync;
+
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager;
+use android_system_virtmanager::binder::{get_interface, ProcessState, Strong};
+use anyhow::{bail, Context, Error};
+// TODO: Import these via android_system_virtmanager::binder once https://r.android.com/1619403 is
+// submitted.
+use binder::{DeathRecipient, IBinder};
+use std::env;
+use std::process::exit;
+use sync::AtomicFlag;
+
+const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
+
+fn main() -> Result<(), Error> {
+    env_logger::init();
+
+    let args: Vec<_> = env::args().collect();
+    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(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(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
+    // object would be dropped and the VM would be killed.
+    wait_for_death(&mut vm.as_binder())?;
+    println!("VM died");
+    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();
+    let mut death_recipient = {
+        let dead = dead.clone();
+        DeathRecipient::new(move || {
+            dead.raise();
+        })
+    };
+    binder.link_to_death(&mut death_recipient)?;
+    dead.wait();
+    Ok(())
+}
diff --git a/vm/src/sync.rs b/vm/src/sync.rs
new file mode 100644
index 0000000..82839b3
--- /dev/null
+++ b/vm/src/sync.rs
@@ -0,0 +1,46 @@
+// 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.
+
+//! Synchronisation utilities.
+
+use std::sync::{Arc, Condvar, Mutex};
+
+/// A flag which one thread can use to notify other threads when a condition becomes true. This is
+/// something like a single-use binary semaphore.
+#[derive(Clone, Debug)]
+pub struct AtomicFlag {
+    state: Arc<(Mutex<bool>, Condvar)>,
+}
+
+impl Default for AtomicFlag {
+    #[allow(clippy::mutex_atomic)]
+    fn default() -> Self {
+        Self { state: Arc::new((Mutex::new(false), Condvar::new())) }
+    }
+}
+
+#[allow(clippy::mutex_atomic)]
+impl AtomicFlag {
+    /// Wait until the flag is set.
+    pub fn wait(&self) {
+        let _flag = self.state.1.wait_while(self.state.0.lock().unwrap(), |flag| !*flag).unwrap();
+    }
+
+    /// Set the flag, and notify all waiting threads.
+    pub fn raise(&self) {
+        let mut flag = self.state.0.lock().unwrap();
+        *flag = true;
+        self.state.1.notify_all();
+    }
+}