Delete temp directory for VM when it's gone

Flag: EXEMPT clean-up
Bug: 420736937
Test: run microdroid, and then kill the vm.
/data/misc/virtualizationservice/<cid> doesn't exist.

Test: run microdroid, and then kill virtmgr.
/data/misc/virtualizationservice/<cid> doesn't exist.

Change-Id: I972dcc80b0a7d440c8ef42a2f813d7d0ca7b2bcf
diff --git a/android/virtualizationservice/src/aidl.rs b/android/virtualizationservice/src/aidl.rs
index 1224b1d..07507b0 100644
--- a/android/virtualizationservice/src/aidl.rs
+++ b/android/virtualizationservice/src/aidl.rs
@@ -31,7 +31,7 @@
 use anyhow::{anyhow, ensure, Context, Result};
 use avflog::LogResult;
 use binder::{
-    self, wait_for_interface, ExceptionCode, Interface, IntoBinderResult,
+    self, wait_for_interface, DeathRecipient, ExceptionCode, IBinder, Interface, IntoBinderResult,
     ParcelFileDescriptor, Status, StatusCode, Strong,
 };
 use libc::{VMADDR_CID_HOST, VMADDR_CID_HYPERVISOR, VMADDR_CID_LOCAL};
@@ -232,7 +232,7 @@
             .virtual_machines
             .iter()
             .filter_map(|(cid, vm)| {
-                vm.getDebugInfo()
+                vm.0.getDebugInfo()
                     .inspect_err(|e| {
                         error!("Failed to get debug info for VM with CID {cid}: {e:?}")
                     })
@@ -759,7 +759,7 @@
 #[derive(Default)]
 struct GlobalState {
     /// List of VMs currently running.
-    virtual_machines: HashMap<Cid, Strong<dyn IVirtualMachine>>,
+    virtual_machines: HashMap<Cid, (Strong<dyn IVirtualMachine>, DeathRecipient)>,
 
     /// State relating to secrets held by (optional) Secretkeeper instance on behalf of VMs.
     sk_state: Option<maintenance::State>,
@@ -839,7 +839,14 @@
         cid: Cid,
         vm: &Strong<dyn IVirtualMachine>,
     ) -> Result<()> {
-        let old_vm = self.virtual_machines.insert(cid, vm.clone());
+        let mut dr = DeathRecipient::new(move || {
+            let temp_dir = format!("{TEMPORARY_DIRECTORY}/{cid}").into();
+            remove_temporary_dir(&temp_dir).unwrap_or_else(|e| {
+                warn!("Could not delete temporary directory {:?}: {}", temp_dir, e);
+            });
+        });
+        vm.as_binder().link_to_death(&mut dr)?;
+        let old_vm = self.virtual_machines.insert(cid, (vm.clone(), dr));
         if let Some(_old_vm) = old_vm {
             warn!("CID ({cid}) reuse detected!");
             // TODO(b/418877672): print more information about old_vm