| // Copyright 2024 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. | |
| //! Stable C library for AVF. | |
| use std::ffi::{CStr, c_void}; | |
| use std::fs::File; | |
| use std::os::fd::{FromRawFd, IntoRawFd}; | |
| use std::os::raw::{c_char, c_int}; | |
| use std::ptr; | |
| use std::sync::{Arc, Weak}; | |
| use std::time::Duration; | |
| use android_system_virtualizationservice::{ | |
| aidl::android::system::virtualizationservice::{ | |
| CpuOptions::CpuOptions, CpuOptions::CpuTopology::CpuTopology, | |
| CustomMemoryBackingFile::CustomMemoryBackingFile, DiskImage::DiskImage, | |
| IVirtualizationService::IVirtualizationService, VirtualMachineConfig::VirtualMachineConfig, | |
| VirtualMachineRawConfig::VirtualMachineRawConfig, | |
| }, | |
| binder::{ParcelFileDescriptor, Strong}, | |
| }; | |
| use avf_bindgen::{ | |
| AVirtualMachine_stopCallback, AVirtualMachineMemoryMappingAttributes, AVirtualMachineStopReason, | |
| }; | |
| use libc::timespec; | |
| use log::error; | |
| use vmclient::{DeathReason, ErrorCode, VirtualizationService, VmCallback, VmInstance}; | |
| /// Create a new virtual machine config object with no properties. | |
| #[unsafe(no_mangle)] | |
| pub extern "C" fn AVirtualMachineRawConfig_create() -> *mut VirtualMachineRawConfig { | |
| let config = Box::new(VirtualMachineRawConfig { | |
| platformVersion: "~1.0".to_owned(), | |
| ..Default::default() | |
| }); | |
| Box::into_raw(config) | |
| } | |
| /// Destroy a virtual machine config object. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. `config` must not be | |
| /// used after deletion. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_destroy(config: *mut VirtualMachineRawConfig) { | |
| if !config.is_null() { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| unsafe { | |
| let _ = Box::from_raw(config); | |
| } | |
| } | |
| } | |
| /// Set a name of a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setName( | |
| config: *mut VirtualMachineRawConfig, | |
| name: *const c_char, | |
| ) -> c_int { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| // SAFETY: `name` is assumed to be a pointer to a valid C string. | |
| let name = unsafe { CStr::from_ptr(name) }; | |
| match name.to_str() { | |
| Ok(name) => { | |
| config.name = name.to_owned(); | |
| 0 | |
| } | |
| Err(_) => -libc::EINVAL, | |
| } | |
| } | |
| /// Set an instance ID of a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. `instanceId` must be a | |
| /// valid, non-null pointer to 64-byte data. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setInstanceId( | |
| config: *mut VirtualMachineRawConfig, | |
| instance_id: *const u8, | |
| instance_id_size: usize, | |
| ) -> c_int { | |
| if instance_id_size != 64 { | |
| return -libc::EINVAL; | |
| } | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| // SAFETY: `instanceId` is assumed to be a valid pointer to 64 bytes of memory. `config` | |
| // is assumed to be a valid object returned by AVirtuaMachineConfig_create. | |
| // Both never overlap. | |
| unsafe { | |
| ptr::copy_nonoverlapping(instance_id, config.instanceId.as_mut_ptr(), instance_id_size); | |
| } | |
| 0 | |
| } | |
| /// Set a kernel image of a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. `fd` must be a valid | |
| /// file descriptor or -1. `AVirtualMachineRawConfig_setKernel` takes ownership of `fd` and `fd` | |
| /// will be closed upon `AVirtualMachineRawConfig_delete`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setKernel( | |
| config: *mut VirtualMachineRawConfig, | |
| fd: c_int, | |
| ) { | |
| let file = get_file_from_fd(fd); | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| config.kernel = file.map(ParcelFileDescriptor::new); | |
| } | |
| /// Set an init rd of a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. `fd` must be a valid | |
| /// file descriptor or -1. `AVirtualMachineRawConfig_setInitRd` takes ownership of `fd` and `fd` | |
| /// will be closed upon `AVirtualMachineRawConfig_delete`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setInitRd( | |
| config: *mut VirtualMachineRawConfig, | |
| fd: c_int, | |
| ) { | |
| let file = get_file_from_fd(fd); | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| config.initrd = file.map(ParcelFileDescriptor::new); | |
| } | |
| /// Add a disk for a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. `fd` must be a valid | |
| /// file descriptor. `AVirtualMachineRawConfig_addDisk` takes ownership of `fd` and `fd` will be | |
| /// closed upon `AVirtualMachineRawConfig_delete`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_addDisk( | |
| config: *mut VirtualMachineRawConfig, | |
| fd: c_int, | |
| writable: bool, | |
| ) -> c_int { | |
| let file = get_file_from_fd(fd); | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| match file { | |
| // partition not supported yet | |
| None => -libc::EINVAL, | |
| Some(file) => { | |
| config.disks.push(DiskImage { | |
| image: Some(ParcelFileDescriptor::new(file)), | |
| writable, | |
| partitions: vec![], | |
| id: None, | |
| }); | |
| 0 | |
| } | |
| } | |
| } | |
| /// Set how much memory will be given to a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setMemoryMiB( | |
| config: *mut VirtualMachineRawConfig, | |
| memory_mib: i32, | |
| ) { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| config.memoryMib = memory_mib; | |
| } | |
| /// Set how much swiotlb will be given to a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setSwiotlbMiB( | |
| config: *mut VirtualMachineRawConfig, | |
| swiotlb_mib: i32, | |
| ) { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| config.swiotlbMib = swiotlb_mib; | |
| } | |
| /// Set vCPU count. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. | |
| #[unsafe(no_mangle)] | |
| #[allow(clippy::needless_update)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setVCpuCount( | |
| config: *mut VirtualMachineRawConfig, | |
| n: i32, | |
| ) { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| config.cpuOptions = CpuOptions { cpuTopology: CpuTopology::CpuCount(n), ..Default::default() }; | |
| } | |
| /// Set whether a virtual machine is protected or not. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setProtectedVm( | |
| config: *mut VirtualMachineRawConfig, | |
| protected_vm: bool, | |
| ) { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| config.protectedVm = protected_vm; | |
| } | |
| /// Set whether to use an alternate, hypervisor-specific authentication method for protected VMs. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setHypervisorSpecificAuthMethod( | |
| config: *mut VirtualMachineRawConfig, | |
| enable: bool, | |
| ) -> c_int { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| config.enableHypervisorSpecificAuthMethod = enable; | |
| // We don't validate whether this is supported until later, when the VM is started. | |
| 0 | |
| } | |
| /// Use the specified fd as the backing memfd for a range of the guest physical memory. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_addCustomMemoryBackingFile( | |
| config: *mut VirtualMachineRawConfig, | |
| fd: c_int, | |
| range_start: u64, | |
| range_end: u64, | |
| ) -> c_int { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| let Some(file) = get_file_from_fd(fd) else { | |
| return -libc::EINVAL; | |
| }; | |
| let Some(size) = range_end.checked_sub(range_start) else { | |
| return -libc::EINVAL; | |
| }; | |
| config.customMemoryBackingFiles.push(CustomMemoryBackingFile { | |
| file: Some(ParcelFileDescriptor::new(file)), | |
| // AIDL doesn't support unsigned ints, so we've got to reinterpret the bytes into a signed | |
| // int. | |
| rangeStart: range_start as i64, | |
| size: size as i64, | |
| }); | |
| 0 | |
| } | |
| /// Add device tree overlay blob | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. `fd` must be a valid | |
| /// file descriptor or -1. `AVirtualMachineRawConfig_setDeviceTreeOverlay` takes ownership of `fd` | |
| /// and `fd` will be closed upon `AVirtualMachineRawConfig_delete`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setDeviceTreeOverlay( | |
| config: *mut VirtualMachineRawConfig, | |
| fd: c_int, | |
| ) { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| config.deviceTreeOverlay = get_file_from_fd(fd).map(ParcelFileDescriptor::new); | |
| } | |
| /// Adds a `tee_service` to the list of TEE (Trusted Execution Environment) services accesses by | |
| /// this pVM. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`, `tee_service` must be | |
| /// a valid pointer to the null-terminated UTF-8 encoded string. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_addTeeService( | |
| config: *mut VirtualMachineRawConfig, | |
| tee_service: *const c_char, | |
| ) -> c_int { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| // SAFETY: `tee_service` is assumed to be a pointer to a valid C string. | |
| let tee_service = unsafe { CStr::from_ptr(tee_service) }; | |
| match tee_service.to_str() { | |
| Ok(tee_service) => { | |
| config.teeServices.push(tee_service.to_owned()); | |
| 0 | |
| } | |
| Err(_) => -libc::EINVAL, | |
| } | |
| } | |
| /// Sets `profile_name` | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`, `profile_name` must be | |
| /// a valid pointer to the null-terminated UTF-8 encoded string. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachineRawConfig_setProfileName( | |
| config: *mut VirtualMachineRawConfig, | |
| profile_name: *const c_char, | |
| ) -> c_int { | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachineRawConfig_create. It's the only reference to the object. | |
| let config = unsafe { &mut *config }; | |
| // SAFETY: `profile_name` is assumed to be a pointer to a valid C string. | |
| let profile_name = unsafe { CStr::from_ptr(profile_name) }; | |
| match profile_name.to_str() { | |
| Ok(profile_name) => { | |
| config.profileName = Some(profile_name.to_owned()); | |
| 0 | |
| } | |
| Err(_) => -libc::EINVAL, | |
| } | |
| } | |
| /// Spawn a new instance of `virtmgr`, a child process that will host the `VirtualizationService` | |
| /// AIDL service, and connect to the child process. | |
| /// | |
| /// # Safety | |
| /// `service_ptr` must be a valid, non-null pointer to a mutable raw pointer. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualizationService_create( | |
| service_ptr: *mut *mut Strong<dyn IVirtualizationService>, | |
| early: bool, | |
| ) -> c_int { | |
| let virtmgr = | |
| if early { VirtualizationService::new_early() } else { VirtualizationService::new() }; | |
| let virtmgr = match virtmgr { | |
| Ok(virtmgr) => virtmgr, | |
| Err(e) => return -e.raw_os_error().unwrap_or(libc::EIO), | |
| }; | |
| match virtmgr.connect() { | |
| Ok(service) => { | |
| // SAFETY: `service` is assumed to be a valid, non-null pointer to a mutable raw | |
| // pointer. `service` is the only reference here and `config` takes | |
| // ownership. | |
| unsafe { | |
| *service_ptr = Box::into_raw(Box::new(service)); | |
| } | |
| 0 | |
| } | |
| Err(_) => -libc::ECONNREFUSED, | |
| } | |
| } | |
| /// Destroy a VirtualizationService object. | |
| /// | |
| /// # Safety | |
| /// `service` must be a pointer returned by `AVirtualizationService_create` or | |
| /// `AVirtualizationService_create_early`. `service` must not be reused after deletion. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualizationService_destroy( | |
| service: *mut Strong<dyn IVirtualizationService>, | |
| ) { | |
| if !service.is_null() { | |
| // SAFETY: `service` is assumed to be a valid, non-null pointer returned by | |
| // `AVirtualizationService_create`. It's the only reference to the object. | |
| unsafe { | |
| let _ = Box::from_raw(service); | |
| } | |
| } | |
| } | |
| struct OpaqueFfiPtr(*mut c_void); | |
| /// SAFETY: Synchronization of underlying data is handled outside. | |
| unsafe impl Send for OpaqueFfiPtr {} | |
| /// SAFETY: Synchronization of underlying data is handled outside. | |
| unsafe impl Sync for OpaqueFfiPtr {} | |
| struct LocalVmInstance { | |
| vm: Weak<VmInstance>, | |
| callback: AVirtualMachine_stopCallback, | |
| data: OpaqueFfiPtr, | |
| } | |
| impl VmCallback for LocalVmInstance { | |
| fn on_payload_started(&self, _cid: i32) { | |
| // Microdroid only. no-op. | |
| } | |
| fn on_payload_ready(&self, _cid: i32) { | |
| // Microdroid only. no-op. | |
| } | |
| fn on_payload_finished(&self, _cid: i32, _exit_code: i32) { | |
| // Microdroid only. no-op. | |
| } | |
| fn on_error(&self, _cid: i32, _error_code: ErrorCode, _message: &str) { | |
| // Microdroid only. no-op. | |
| } | |
| fn on_died(&self, _cid: i32, death_reason: DeathReason) { | |
| let Some(callback) = self.callback else { | |
| return; | |
| }; | |
| let stop_reason = death_reason_to_stop_reason(death_reason); | |
| // Note: VM launching app should hold strong reference of VmInstance. | |
| // The reference is managed internally by libavf and caller doesn't have direct | |
| // control. | |
| let vm = self.vm.upgrade().unwrap(); | |
| // SAFETY: We trust the caller of `AVirtualMachine_start` to provide a valid `callback`. | |
| // The callback would be called only once, as `virtmgr` does so for `on_died()`. | |
| unsafe { | |
| callback(Arc::as_ptr(&vm) as *mut _, stop_reason, self.data.0); | |
| } | |
| } | |
| } | |
| /// Create a virtual machine with given `config`. | |
| /// | |
| /// # Safety | |
| /// `config` must be a pointer returned by `AVirtualMachineRawConfig_create`. `service` must be a | |
| /// pointer returned by `AVirtualMachineRawConfig_create`. `vm_ptr` must be a valid, non-null | |
| /// pointer to a mutable raw pointer. `console_out_fd`, `console_in_fd`, and `log_fd` must be a | |
| /// valid file descriptor or -1. `AVirtualMachine_create` takes ownership of `console_out_fd`, | |
| /// `console_in_fd`, and `log_fd`, and taken file descriptors must not be reused. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_createRaw( | |
| service: *const Strong<dyn IVirtualizationService>, | |
| config: *mut VirtualMachineRawConfig, | |
| console_out_fd: c_int, | |
| console_in_fd: c_int, | |
| log_fd: c_int, | |
| vm_ptr: *mut *mut VmInstance, | |
| ) -> c_int { | |
| // SAFETY: `service` is assumed to be a valid, non-null pointer returned by | |
| // `AVirtualizationService_create` or `AVirtualizationService_create_early`. It's the only | |
| // reference to the object. | |
| let service = unsafe { &*service }; | |
| // SAFETY: `config` is assumed to be a valid, non-null pointer returned by | |
| // `AVirtualMachineRawConfig_create`. It's the only reference to the object. | |
| let config = unsafe { *Box::from_raw(config) }; | |
| let config = VirtualMachineConfig::RawConfig(config); | |
| let console_out = get_file_from_fd(console_out_fd); | |
| let console_in = get_file_from_fd(console_in_fd); | |
| let log = get_file_from_fd(log_fd); | |
| match VmInstance::create(service.as_ref(), &config, console_out, console_in, log, None) { | |
| Ok(vm) => { | |
| // SAFETY: `vm_ptr` is assumed to be a valid, non-null pointer to a mutable raw pointer. | |
| unsafe { | |
| *vm_ptr = Arc::into_raw(Arc::new(vm)) as *mut _; | |
| } | |
| 0 | |
| } | |
| Err(e) => { | |
| error!("AVirtualMachine_createRaw failed: {e:?}"); | |
| -libc::EIO | |
| } | |
| } | |
| } | |
| /// Start a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `vm` must be a pointer returned by `AVirtualMachine_createRaw`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_start(vm: *mut VmInstance) -> c_int { | |
| // SAFETY: Fills default parameters and delegates to another function | |
| // with the same safety requirement. | |
| unsafe { AVirtualMachine_startWithStopCallback(vm, None, ptr::null_mut()) } | |
| } | |
| /// Start a virtual machine with stop callback | |
| /// | |
| /// # Safety | |
| /// `vm` must be a pointer returned by `AVirtualMachine_createRaw`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_startWithStopCallback( | |
| vm: *mut VmInstance, | |
| callback: AVirtualMachine_stopCallback, | |
| data: *mut c_void, | |
| ) -> c_int { | |
| // SAFETY: `vm` is assumed to be a valid, non-null pointer returned by | |
| // `AVirtualMachine_createRaw`. It's the only reference to the object. | |
| let vm = unsafe { | |
| Arc::increment_strong_count(vm); | |
| Arc::from_raw(vm) | |
| }; | |
| let callback = callback.map(|_| { | |
| let cb: Box<dyn VmCallback + Send + Sync> = Box::new(LocalVmInstance { | |
| vm: Arc::downgrade(&vm), | |
| callback, | |
| data: OpaqueFfiPtr(data), | |
| }); | |
| cb | |
| }); | |
| match vm.start(callback) { | |
| Ok(_) => 0, | |
| Err(e) => { | |
| error!("AVirtualMachine_start failed: {e:?}"); | |
| -libc::EIO | |
| } | |
| } | |
| } | |
| /// Stop a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `vm` must be a pointer returned by `AVirtualMachine_create`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_stop(vm: *mut VmInstance) -> c_int { | |
| // SAFETY: `vm` is assumed to be a valid, non-null pointer returned by | |
| // `AVirtualMachine_createRaw`. It's the only reference to the object. | |
| let vm = unsafe { &*vm }; | |
| match vm.stop() { | |
| Ok(_) => 0, | |
| Err(e) => { | |
| error!("AVirtualMachine_stop failed: {e:?}"); | |
| -libc::EIO | |
| } | |
| } | |
| } | |
| /// Open a vsock connection to the CID of the virtual machine on the given vsock port. | |
| /// | |
| /// # Safety | |
| /// `vm` must be a pointer returned by `AVirtualMachine_create`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_connectVsock(vm: *mut VmInstance, port: u32) -> c_int { | |
| // SAFETY: `vm` is assumed to be a valid, non-null pointer returned by | |
| // `AVirtualMachine_createRaw`. It's the only reference to the object. | |
| let vm = unsafe { &*vm }; | |
| match vm.connect_vsock(port) { | |
| Ok(pfd) => pfd.into_raw_fd(), | |
| Err(e) => { | |
| error!("AVirtualMachine_connectVsock failed: {e:?}"); | |
| -libc::EIO | |
| } | |
| } | |
| } | |
| fn add_accessor( | |
| vm: &VmInstance, | |
| rpc_service_name: &str, | |
| accessor_name: &str, | |
| port: i32, | |
| ) -> Result<(), c_int> { | |
| let accessor = vm.vm.createAccessorBinder(rpc_service_name, port).map_err(|e| { | |
| error!("AVirtualMachine_addAccessor: createAccessorBinder failed: {e:?}"); | |
| libc::EIO | |
| })?; | |
| let accessor_delegator = | |
| binder::delegate_accessor(rpc_service_name, accessor).map_err(|e| { | |
| error!("AVirtualMachine_addAccessor: delegate_accessor failed: {e:?}"); | |
| libc::EIO | |
| })?; | |
| binder::add_service(accessor_name, accessor_delegator).map_err(|e| { | |
| error!("AVirtualMachine_addAccessor: add_service failed: {e:?}"); | |
| libc::EIO | |
| })?; | |
| Ok(()) | |
| } | |
| /// Registers an accessor for an RPC service within the virtual machine. | |
| /// | |
| /// # Safety | |
| /// | |
| /// * `vm` must be a pointer returned by `AVirtualMachine_create`. | |
| /// * `rpc_service_name` and `accessor_name` must be valid, null-terminated C strings pointing to | |
| /// readable memory. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_addAccessor( | |
| vm: *mut VmInstance, | |
| rpc_service_name: *const c_char, | |
| accessor_name: *const c_char, | |
| port: i32, | |
| ) -> c_int { | |
| if vm.is_null() { | |
| return -libc::EINVAL; | |
| } | |
| // SAFETY: We verified `vm` is not null. The caller guarantees the memory is valid | |
| // and properly initialized. | |
| let vm = unsafe { &mut *vm }; | |
| if rpc_service_name.is_null() || accessor_name.is_null() { | |
| return -libc::EINVAL; | |
| } | |
| // SAFETY: The caller guarantees `rpc_service_name` is a valid C string. | |
| let rpc_service_cstr = unsafe { CStr::from_ptr(rpc_service_name) }; | |
| let Ok(rpc_service_str) = rpc_service_cstr.to_str() else { | |
| error!("AVirtualMachine_addAccessor: rpc_service_name is not valid UTF-8"); | |
| return -libc::EINVAL; | |
| }; | |
| // SAFETY: The caller guarantees `accessor_name` is a valid C string. | |
| let accessor_cstr = unsafe { CStr::from_ptr(accessor_name) }; | |
| let Ok(accessor_str) = accessor_cstr.to_str() else { | |
| error!("AVirtualMachine_addAccessor: accessor_name is not valid UTF-8"); | |
| return -libc::EINVAL; | |
| }; | |
| match add_accessor(vm, rpc_service_str, accessor_str, port) { | |
| Ok(_) => 0, | |
| Err(err) => -err, | |
| } | |
| } | |
| fn death_reason_to_stop_reason(death_reason: DeathReason) -> AVirtualMachineStopReason { | |
| match death_reason { | |
| DeathReason::VirtualizationServiceDied => { | |
| AVirtualMachineStopReason::AVIRTUAL_MACHINE_VIRTUALIZATION_SERVICE_DIED | |
| } | |
| DeathReason::InfrastructureError => { | |
| AVirtualMachineStopReason::AVIRTUAL_MACHINE_INFRASTRUCTURE_ERROR | |
| } | |
| DeathReason::Killed => AVirtualMachineStopReason::AVIRTUAL_MACHINE_KILLED, | |
| DeathReason::Unknown => AVirtualMachineStopReason::AVIRTUAL_MACHINE_UNKNOWN, | |
| DeathReason::Shutdown => AVirtualMachineStopReason::AVIRTUAL_MACHINE_SHUTDOWN, | |
| DeathReason::StartFailed => AVirtualMachineStopReason::AVIRTUAL_MACHINE_START_FAILED, | |
| DeathReason::Reboot => AVirtualMachineStopReason::AVIRTUAL_MACHINE_REBOOT, | |
| DeathReason::Crash => AVirtualMachineStopReason::AVIRTUAL_MACHINE_CRASH, | |
| DeathReason::PvmFirmwarePublicKeyMismatch => { | |
| AVirtualMachineStopReason::AVIRTUAL_MACHINE_PVM_FIRMWARE_PUBLIC_KEY_MISMATCH | |
| } | |
| DeathReason::PvmFirmwareInstanceImageChanged => { | |
| AVirtualMachineStopReason::AVIRTUAL_MACHINE_PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED | |
| } | |
| DeathReason::Hangup => AVirtualMachineStopReason::AVIRTUAL_MACHINE_HANGUP, | |
| _ => AVirtualMachineStopReason::AVIRTUAL_MACHINE_UNRECOGNISED, | |
| } | |
| } | |
| /// Wait until a virtual machine stops or the timeout elapses. | |
| /// | |
| /// # Safety | |
| /// `vm` must be a pointer returned by `AVirtualMachine_createRaw`. `timeout` must be a valid | |
| /// pointer to a `struct timespec` object or null. `reason` must be a valid, non-null pointer to an | |
| /// AVirtualMachineStopReason object. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_waitForStop( | |
| vm: *mut VmInstance, | |
| timeout: *const timespec, | |
| reason: *mut AVirtualMachineStopReason, | |
| ) -> bool { | |
| // SAFETY: `vm` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachine_create. It's the only reference to the object. | |
| let vm = unsafe { &*vm }; | |
| let death_reason = if timeout.is_null() { | |
| vm.wait_for_death() | |
| } else { | |
| // SAFETY: `timeout` is assumed to be a valid pointer to a `struct timespec` object if | |
| // non-null. | |
| let timeout = unsafe { &*timeout }; | |
| let timeout = Duration::new(timeout.tv_sec as u64, timeout.tv_nsec as u32); | |
| match vm.wait_for_death_with_timeout(timeout) { | |
| Some(death_reason) => death_reason, | |
| None => return false, | |
| } | |
| }; | |
| // SAFETY: `reason` is assumed to be a valid, non-null pointer to an | |
| // AVirtualMachineStopReason object. | |
| unsafe { *reason = death_reason_to_stop_reason(death_reason) }; | |
| true | |
| } | |
| /// Destroy a virtual machine. | |
| /// | |
| /// # Safety | |
| /// `vm` must be a pointer returned by `AVirtualMachine_createRaw`. `vm` must not be reused after | |
| /// deletion. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_destroy(vm: *mut VmInstance) { | |
| if !vm.is_null() { | |
| // SAFETY: `vm` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachine_create. It's the only reference to the object. | |
| unsafe { | |
| let _ = Arc::from_raw(vm); | |
| } | |
| } | |
| } | |
| /// Adds this fd as memory into the guest IPA space at the given range. | |
| /// | |
| /// # Safety | |
| /// `vm` must be a pointer returned by `AVirtualMachine_createRaw`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_addMemoryMapping( | |
| vm: *const VmInstance, | |
| fd: c_int, | |
| range_start: u64, | |
| range_end: u64, | |
| offset: u64, | |
| memory_attrs: AVirtualMachineMemoryMappingAttributes, | |
| ) -> c_int { | |
| // SAFETY: `vm` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachine_create. It's the only reference to the object. | |
| let vm = unsafe { &*vm }; | |
| let Some(fd) = get_file_from_fd(fd) else { | |
| return -libc::EINVAL; | |
| }; | |
| let cache_coherent = match memory_attrs { | |
| AVirtualMachineMemoryMappingAttributes::AVIRTUAL_MACHINE_MEMORY_MAPPING_ATTRIBUTE_CACHE_COHERENT => true, | |
| AVirtualMachineMemoryMappingAttributes::AVIRTUAL_MACHINE_MEMORY_MAPPING_ATTRIBUTE_NON_CACHE_COHERENT => false, | |
| }; | |
| match vm.add_memory_mapping(fd, range_start, range_end, offset, cache_coherent) { | |
| Ok(memory_id) => memory_id, | |
| Err(e) => { | |
| error!("AVirtualMachine_addFileMapping failed: {e:?}"); | |
| -libc::EIO | |
| } | |
| } | |
| } | |
| /// Removes previously shared with guest memory from the guest IPA space. | |
| /// | |
| /// # Safety | |
| /// `vm` must be a pointer returned by `AVirtualMachine_createRaw`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn AVirtualMachine_removeMemoryMapping( | |
| vm: *const VmInstance, | |
| memory_id: c_int, | |
| ) -> bool { | |
| // SAFETY: `vm` is assumed to be a valid, non-null pointer returned by | |
| // AVirtualMachine_create. It's the only reference to the object. | |
| let vm = unsafe { &*vm }; | |
| match vm.remove_memory_mapping(memory_id) { | |
| Ok(_) => true, | |
| Err(e) => { | |
| error!("AVirtualMachine_removeFileMapping failed: {e:?}"); | |
| false | |
| } | |
| } | |
| } | |
| fn get_file_from_fd(fd: i32) -> Option<File> { | |
| if fd == -1 { | |
| None | |
| } else { | |
| // SAFETY: transferring ownership of `fd` from the caller | |
| Some(unsafe { File::from_raw_fd(fd) }) | |
| } | |
| } |