Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1 | // Copyright 2021, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Implementation of the AIDL interface of the Virt Manager. |
| 16 | |
Andrew Walbran | a2f8c23 | 2021-03-11 11:46:53 +0000 | [diff] [blame] | 17 | use crate::config::VmConfig; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 18 | use crate::crosvm::VmInstance; |
| 19 | use crate::{Cid, FIRST_GUEST_CID}; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame^] | 20 | use ::binder::FromIBinder; // TODO(dbrazdil): remove once b/182890877 is fixed |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 21 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager; |
| 22 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{ |
| 23 | BnVirtualMachine, IVirtualMachine, |
| 24 | }; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 25 | use android_system_virtmanager::aidl::android::system::virtmanager::VirtualMachineDebugInfo::VirtualMachineDebugInfo; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 26 | use android_system_virtmanager::binder::{ |
| 27 | self, Interface, ParcelFileDescriptor, StatusCode, Strong, ThreadState, |
| 28 | }; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 29 | use log::error; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 30 | use std::fs::File; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 31 | use std::sync::{Arc, Mutex, Weak}; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 32 | |
| 33 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager"; |
| 34 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 35 | // TODO(qwandor): Use PermissionController once it is available to Rust. |
| 36 | /// Only processes running with one of these UIDs are allowed to call debug methods. |
| 37 | const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000]; |
| 38 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 39 | /// Implementation of `IVirtManager`, the entry point of the AIDL service. |
| 40 | #[derive(Debug, Default)] |
| 41 | pub struct VirtManager { |
Andrew Walbran | 9c01baa | 2021-03-08 18:23:50 +0000 | [diff] [blame] | 42 | state: Mutex<State>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 43 | } |
| 44 | |
| 45 | impl Interface for VirtManager {} |
| 46 | |
| 47 | impl IVirtManager for VirtManager { |
| 48 | /// Create and start a new VM with the given configuration, assigning it the next available CID. |
| 49 | /// |
| 50 | /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client. |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 51 | fn startVm( |
| 52 | &self, |
| 53 | config_path: &str, |
| 54 | log_fd: Option<&ParcelFileDescriptor>, |
| 55 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 56 | let state = &mut *self.state.lock().unwrap(); |
| 57 | let cid = state.next_cid; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 58 | let log_fd = log_fd |
| 59 | .map(|fd| fd.as_ref().try_clone().map_err(|_| StatusCode::UNKNOWN_ERROR)) |
| 60 | .transpose()?; |
| 61 | let instance = Arc::new(start_vm(config_path, cid, log_fd)?); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 62 | // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them. |
| 63 | state.next_cid = state.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 64 | state.add_vm(Arc::downgrade(&instance)); |
| 65 | Ok(VirtualMachine::create(instance)) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 66 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 67 | |
| 68 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 69 | /// and as such is only permitted from the shell user. |
| 70 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
| 71 | if !debug_access_allowed() { |
| 72 | return Err(StatusCode::PERMISSION_DENIED.into()); |
| 73 | } |
| 74 | |
| 75 | let state = &mut *self.state.lock().unwrap(); |
| 76 | let vms = state.vms(); |
| 77 | let cids = vms |
| 78 | .into_iter() |
| 79 | .map(|vm| VirtualMachineDebugInfo { |
| 80 | cid: vm.cid as i32, |
| 81 | configPath: vm.config_path.clone(), |
| 82 | }) |
| 83 | .collect(); |
| 84 | Ok(cids) |
| 85 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame^] | 86 | |
| 87 | /// Hold a strong reference to a VM in Virt Manager. This method is only intended for debug |
| 88 | /// purposes, and as such is only permitted from the shell user. |
| 89 | fn debugHoldVmRef(&self, vmref: &dyn IVirtualMachine) -> binder::Result<()> { |
| 90 | if !debug_access_allowed() { |
| 91 | return Err(StatusCode::PERMISSION_DENIED.into()); |
| 92 | } |
| 93 | |
| 94 | // Workaround for b/182890877. |
| 95 | let vm: Strong<dyn IVirtualMachine> = FromIBinder::try_from(vmref.as_binder()).unwrap(); |
| 96 | |
| 97 | let state = &mut *self.state.lock().unwrap(); |
| 98 | state.debug_hold_vm(vm); |
| 99 | Ok(()) |
| 100 | } |
| 101 | |
| 102 | /// Drop reference to a VM that is being held by Virt Manager. Returns the reference if VM was |
| 103 | /// found and None otherwise. This method is only intended for debug purposes, and as such is |
| 104 | /// only permitted from the shell user. |
| 105 | fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> { |
| 106 | if !debug_access_allowed() { |
| 107 | return Err(StatusCode::PERMISSION_DENIED.into()); |
| 108 | } |
| 109 | |
| 110 | let state = &mut *self.state.lock().unwrap(); |
| 111 | Ok(state.debug_drop_vm(cid)) |
| 112 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 113 | } |
| 114 | |
| 115 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 116 | fn debug_access_allowed() -> bool { |
| 117 | let uid = ThreadState::get_calling_uid(); |
| 118 | log::trace!("Debug method call from UID {}.", uid); |
| 119 | DEBUG_ALLOWED_UIDS.contains(&uid) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 120 | } |
| 121 | |
| 122 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 123 | #[derive(Debug)] |
| 124 | struct VirtualMachine { |
| 125 | instance: Arc<VmInstance>, |
| 126 | } |
| 127 | |
| 128 | impl VirtualMachine { |
| 129 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
| 130 | let binder = VirtualMachine { instance }; |
| 131 | BnVirtualMachine::new_binder(binder) |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | impl Interface for VirtualMachine {} |
| 136 | |
| 137 | impl IVirtualMachine for VirtualMachine { |
| 138 | fn getCid(&self) -> binder::Result<i32> { |
| 139 | Ok(self.instance.cid as i32) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | /// The mutable state of the Virt Manager. There should only be one instance of this struct. |
| 144 | #[derive(Debug)] |
| 145 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 146 | /// The next available unused CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 147 | next_cid: Cid, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 148 | |
| 149 | /// The VMs which have been started. When VMs are started a weak reference is added to this list |
| 150 | /// while a strong reference is returned to the caller over Binder. Once all copies of the |
| 151 | /// Binder client are dropped the weak reference here will become invalid, and will be removed |
| 152 | /// from the list opportunistically the next time `add_vm` is called. |
| 153 | vms: Vec<Weak<VmInstance>>, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame^] | 154 | |
| 155 | /// Vector of strong VM references held on behalf of users that cannot hold them themselves. |
| 156 | /// This is only used for debugging purposes. |
| 157 | debug_held_vms: Vec<Strong<dyn IVirtualMachine>>, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 158 | } |
| 159 | |
| 160 | impl State { |
| 161 | /// Get a list of VMs which are currently running. |
| 162 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 163 | // Attempt to upgrade the weak pointers to strong pointers. |
| 164 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 165 | } |
| 166 | |
| 167 | /// Add a new VM to the list. |
| 168 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 169 | // Garbage collect any entries from the stored list which no longer exist. |
| 170 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 171 | |
| 172 | // Actually add the new VM. |
| 173 | self.vms.push(vm); |
| 174 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame^] | 175 | |
| 176 | /// Store a strong VM reference. |
| 177 | fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) { |
| 178 | self.debug_held_vms.push(vm); |
| 179 | } |
| 180 | |
| 181 | /// Retrieve and remove a strong VM reference. |
| 182 | fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> { |
| 183 | let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?; |
| 184 | Some(self.debug_held_vms.swap_remove(pos)) |
| 185 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 186 | } |
| 187 | |
| 188 | impl Default for State { |
| 189 | fn default() -> Self { |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame^] | 190 | State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 191 | } |
| 192 | } |
| 193 | |
| 194 | /// Start a new VM instance from the given VM config filename. This assumes the VM is not already |
| 195 | /// running. |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 196 | fn start_vm(config_path: &str, cid: Cid, log_fd: Option<File>) -> binder::Result<VmInstance> { |
Andrew Walbran | a2f8c23 | 2021-03-11 11:46:53 +0000 | [diff] [blame] | 197 | let config = VmConfig::load(config_path).map_err(|e| { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 198 | error!("Failed to load VM config {}: {:?}", config_path, e); |
| 199 | StatusCode::BAD_VALUE |
| 200 | })?; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 201 | Ok(VmInstance::start(&config, cid, config_path, log_fd).map_err(|e| { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 202 | error!("Failed to start VM {}: {:?}", config_path, e); |
| 203 | StatusCode::UNKNOWN_ERROR |
| 204 | })?) |
| 205 | } |