Add method to get list of VMs for vm tool.

Bug: 181869875
Test: Ran on VIM3L
Change-Id: I90506962171d6c16469e265521b435bec905e0f4
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();