| // Copyright 2026, 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. | |
| //! Wrappers for wrapfd driver. | |
| use nix::errno::Errno; | |
| use nix::fcntl::{OFlag, open}; | |
| use nix::sys::stat::Mode; | |
| use std::os::fd::FromRawFd; | |
| use std::os::unix::io::{AsRawFd, BorrowedFd, OwnedFd, RawFd}; | |
| use std::ptr; | |
| use wrapfd_bindings::{ | |
| WrapfdState as CWrapfdState, WrapfdState_WRAPFD_STATE_EMPTY, WrapfdState_WRAPFD_STATE_RDONLY, | |
| WrapfdState_WRAPFD_STATE_RDWR, | |
| }; | |
| mod ioctls; | |
| bitflags::bitflags! { | |
| /// Represents Wrapfd state. | |
| #[derive(Debug, PartialEq)] | |
| pub struct WrapfdState : CWrapfdState { | |
| /// Wrapfd is empty. | |
| const EMPTY = WrapfdState_WRAPFD_STATE_EMPTY; | |
| /// Wrapfd is read-only. | |
| const RDONLY = WrapfdState_WRAPFD_STATE_RDONLY; | |
| /// Wrapfd is read-write. | |
| const RDWR = WrapfdState_WRAPFD_STATE_RDWR; | |
| } | |
| } | |
| /// Represents API on /dev/wrapfd. | |
| pub struct WrapfdDriver { | |
| dev_fd: OwnedFd, | |
| } | |
| impl WrapfdDriver { | |
| fn wrap_optional_fd(&self, fd: Option<BorrowedFd>, prot: i32) -> nix::Result<OwnedFd> { | |
| const INVALID_FD: RawFd = -1; | |
| let raw_fd = fd.map_or(INVALID_FD, |fd| fd.as_raw_fd()); | |
| // SAFETY: The driver instance is valid, wrapfd_driver_wrap() does not mutate it, and | |
| // raw_fd remains valid as long as it is borrowed, or is known-invalid and | |
| // passed only to generate an error condition. | |
| let res = unsafe { wrapfd_driver_wrap(self as *const WrapfdDriver, raw_fd, prot) }; | |
| package_into_nix_result(res).map(|wrapfd| { | |
| // SAFETY: wrapfd is a new, valid file descriptor returned by the driver if the wrap | |
| // ioctl command executes successfully, and we take exclusive ownership of the fd. | |
| unsafe { OwnedFd::from_raw_fd(wrapfd) } | |
| }) | |
| } | |
| /// Opens the driver device node. | |
| pub fn new() -> nix::Result<WrapfdDriver> { | |
| let dev_fd = open("/dev/wrapfd", OFlag::O_RDONLY, Mode::empty())?; | |
| let driver = WrapfdDriver { dev_fd }; | |
| // Probe driver ioctl compatibility by not passing an fd to wrap. This should ultimately | |
| // fail with EBADF. If it does, then that means that we actually ran the logic that handles | |
| // the wrap ioctl command, and the driver works as expected. | |
| // | |
| // If the kernel and userspace header definitions mismatch (e.g. struct wrapfd_wrap size | |
| // changed), the ioctl command code will differ and the kernel returns ENOTTY. We remap | |
| // ENOTTY to ENOTSUP to not leak implementation details about the WrapfdDriver object. | |
| match driver.wrap_optional_fd(None, libc::PROT_READ) { | |
| Err(Errno::EBADF) => Ok(driver), | |
| Err(Errno::ENOTTY) => Err(Errno::ENOTSUP), | |
| Err(e) => Err(e), | |
| Ok(_) => unreachable!("The wrap ioctl command must not succeed given an invalid fd."), | |
| } | |
| } | |
| /// Wraps a buffer represented by a file descriptor. | |
| /// | |
| /// # Arguments | |
| /// - `fd`: The fd to wrap | |
| /// - `prot`: Protection flags. Either `PROT_NONE` or bitwise-or of some or all | |
| /// of `PROT_READ`, `PROT_WRITE`, and `PROT_EXEC`. | |
| pub fn wrap(&self, fd: BorrowedFd, prot: i32) -> nix::Result<OwnedFd> { | |
| self.wrap_optional_fd(Some(fd), prot) | |
| } | |
| } | |
| /// Gets the state of a wrapfd. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: The fd to get the state of. | |
| pub fn get_state(wrapfd: BorrowedFd) -> nix::Result<WrapfdState> { | |
| let mut state: u32 = 0; | |
| // SAFETY: wrapfd remains valid as long as it is borrowed. | |
| let res = unsafe { wrapfd_get_state(wrapfd.as_raw_fd(), &mut state as *mut u32) }; | |
| package_into_nix_result(res).map(|_| WrapfdState::from_bits_retain(state)) | |
| } | |
| /// Acquire buffer ownership. | |
| /// | |
| /// Use [WrapfdOwnershipGuard] for an RAII guard. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| pub fn acquire_ownership(wrapfd: BorrowedFd) -> nix::Result<()> { | |
| // SAFETY: The wrapfd_acquire_ownership_ioctl is a generated ioctl. | |
| unsafe { ioctls::wrapfd_acquire_ownership_ioctl(wrapfd.as_raw_fd())? }; | |
| Ok(()) | |
| } | |
| /// Release buffer ownership. | |
| /// | |
| /// Use [WrapfdOwnershipGuard] for an RAII guard. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| pub fn release_ownership(wrapfd: BorrowedFd) -> nix::Result<()> { | |
| // SAFETY: The wrapfd_release_ownership_ioctl is a generated ioctl. | |
| unsafe { ioctls::wrapfd_release_ownership_ioctl(wrapfd.as_raw_fd())? }; | |
| Ok(()) | |
| } | |
| /// A RAII guard that holds ownership of a wrapfd. | |
| /// | |
| /// When the guard is dropped, the wrapfd is put. The user can also call | |
| /// `put()` to release the ownership early to get the result of the put | |
| /// operation. If you rely on the `drop` to put the wrapfd, the result from | |
| /// the `put()` operation is ignored. | |
| pub struct WrapfdOwnershipGuard<'a> { | |
| fd: Option<BorrowedFd<'a>>, | |
| } | |
| impl<'a> WrapfdOwnershipGuard<'a> { | |
| /// Creates the guard by getting ownership of the wrapfd. | |
| pub fn new(fd: BorrowedFd<'a>) -> nix::Result<Self> { | |
| acquire_ownership(fd)?; | |
| Ok(Self { fd: Some(fd) }) | |
| } | |
| /// Releases ownership of the wrapfd. | |
| pub fn release_ownership(&mut self) -> nix::Result<()> { | |
| if let Some(fd) = self.fd.take() { release_ownership(fd) } else { Ok(()) } | |
| } | |
| } | |
| impl<'a> Drop for WrapfdOwnershipGuard<'a> { | |
| /// Releases ownership of the wrapfd, suppressing any errors. | |
| fn drop(&mut self) { | |
| if let Err(e) = self.release_ownership() { | |
| log::error!("Failed to put wrapfd ownership: {:?}", e); | |
| } | |
| } | |
| } | |
| /// Loads a segment of a file into the buffer at the given offset. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| pub fn load( | |
| wrapfd: BorrowedFd, | |
| file: BorrowedFd, | |
| file_offset: u64, | |
| buf_offset: u64, | |
| len: u64, | |
| ) -> nix::Result<()> { | |
| // SAFETY: wrapfd and file remain valid throughout this call since they are borrowed fds. | |
| let res = | |
| unsafe { wrapfd_load(wrapfd.as_raw_fd(), file.as_raw_fd(), file_offset, buf_offset, len) }; | |
| package_into_nix_result(res)?; | |
| Ok(()) | |
| } | |
| /// Move the buffer into a new wrap. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| pub fn rewrap(wrapfd: BorrowedFd, prot: i32) -> nix::Result<OwnedFd> { | |
| // SAFETY: wrapfd remains valid as long as it is borrowed by this function. | |
| let res = unsafe { wrapfd_rewrap(wrapfd.as_raw_fd(), prot) }; | |
| package_into_nix_result(res).map(|new_fd| { | |
| // SAFETY: raw_fd is a new, valid file descriptor. | |
| unsafe { OwnedFd::from_raw_fd(new_fd) } | |
| }) | |
| } | |
| /// Free the wrapped buffer. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| pub fn empty(wrapfd: BorrowedFd) -> nix::Result<()> { | |
| // SAFETY: The wrapfd_empty_ioctl is a generated ioctl. | |
| unsafe { ioctls::wrapfd_empty_ioctl(wrapfd.as_raw_fd())? }; | |
| Ok(()) | |
| } | |
| /// Allow non-owner processes to map the buffer. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| pub fn allow_guests(wrapfd: BorrowedFd) -> nix::Result<()> { | |
| // SAFETY: The wrapfd_allow_guests_ioctl is a generated ioctl. | |
| unsafe { ioctls::wrapfd_allow_guests_ioctl(wrapfd.as_raw_fd())? }; | |
| Ok(()) | |
| } | |
| /// Disallow non-owner processes from mapping the buffer. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| pub fn prohibit_guests(wrapfd: BorrowedFd) -> nix::Result<()> { | |
| // SAFETY: The wrapfd_prohibit_guests_ioctl is a generated ioctl. | |
| unsafe { ioctls::wrapfd_prohibit_guests_ioctl(wrapfd.as_raw_fd())? }; | |
| Ok(()) | |
| } | |
| fn package_into_nix_result(res: i32) -> nix::Result<i32> { | |
| if res < 0 { | |
| return Err(Errno::from_raw(-res)); | |
| } | |
| Ok(res) | |
| } | |
| /// Create an instance of a WrapfdDriver and opens the /dev/wrapfd node. | |
| #[unsafe(no_mangle)] | |
| pub extern "C" fn wrapfd_driver_new() -> *mut WrapfdDriver { | |
| match WrapfdDriver::new() { | |
| Ok(driver) => Box::into_raw(Box::new(driver)), | |
| Err(_e) => ptr::null_mut(), | |
| } | |
| } | |
| /// Destroys an instance of a WrapfdDriver. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `driver` is from [wrapfd_driver_new]. | |
| /// | |
| /// # Arguments | |
| /// - `driver`: A pointer to a WrapfdDriver instance. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_driver_destroy(driver: *mut WrapfdDriver) { | |
| if !driver.is_null() { | |
| // SAFETY: Reconstruct the box to let it drop and close the dev_fd. | |
| unsafe { drop(Box::from_raw(driver)) }; | |
| } | |
| } | |
| /// Wraps a buffer represented by a file descriptor. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `driver` is from [wrapfd_driver_new]. | |
| /// | |
| /// The caller ensures that `fd` is a valid file descriptor and remains valid throughout this call. | |
| /// | |
| /// # Arguments | |
| /// - `driver`: A pointer to a WrapfdDriver instance. | |
| /// - `fd`: The fd to wrap. | |
| /// - `prot`: Protection flags. Either `PROT_NONE` or bitwise-or of some or all | |
| /// of `PROT_READ`, `PROT_WRITE`. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_driver_wrap( | |
| driver: *const WrapfdDriver, | |
| fd: RawFd, | |
| prot: i32, | |
| ) -> RawFd { | |
| if driver.is_null() { | |
| return -libc::EINVAL; | |
| } | |
| let wrap = ioctls::wrapfd_wrap { fd: fd as u32, prot: prot as u32, reserved: 0 }; | |
| // SAFETY: Caller provides a valid pointer to a WrapfdDriver, and we know it is not NULL. | |
| // The wrapfd_wrap_ioctl is a generated ioctl. | |
| let res = unsafe { ioctls::wrapfd_wrap_ioctl((*driver).dev_fd.as_raw_fd(), &wrap) }; | |
| res.unwrap_or_else(|e| -(e as i32)) | |
| } | |
| /// Gets the state of a wrapfd. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `wrapfd` is a valid file descriptor from [wrapfd_driver_wrap] | |
| /// throughout the call. | |
| /// | |
| /// The caller ensures that `state_out` is a valid pointer to a u32. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: The fd to get the state of. | |
| /// - `state_out`: A pointer that is used to store the wrapfd state. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_get_state(wrapfd: RawFd, state_out: *mut u32) -> i32 { | |
| if state_out.is_null() { | |
| return -libc::EINVAL; | |
| } | |
| let mut get_state = ioctls::wrapfd_get_state { state: 0, pad: 0, reserved: 0 }; | |
| // SAFETY: The wrapfd_get_state_ioctl is a generated ioctl. Caller guarantees wrapfd | |
| // and state_out remain valid throughout this call. | |
| match unsafe { ioctls::wrapfd_get_state_ioctl(wrapfd, &mut get_state) } { | |
| Ok(_) => { | |
| // SAFETY: Caller provides a valid pointer to store the output and we know it is not | |
| // NULL. | |
| unsafe { *state_out = get_state.state }; | |
| 0 | |
| } | |
| Err(e) => -(e as i32), | |
| } | |
| } | |
| /// Acquire buffer ownership. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `wrapfd` is a valid file descriptor from [wrapfd_driver_wrap] | |
| /// throughout the call. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [wrapfd_driver_wrap]. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_acquire_ownership(wrapfd: RawFd) -> i32 { | |
| // SAFETY: The wrapfd_acquire_ownership_ioctl is a generated ioctl and | |
| // the caller guarantees the fd remains valid throughout this call. | |
| let res = unsafe { ioctls::wrapfd_acquire_ownership_ioctl(wrapfd) }; | |
| res.map_or_else(|e| -(e as i32), |_| 0) | |
| } | |
| /// Release buffer ownership. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `wrapfd` is a valid file descriptor from [wrapfd_driver_wrap] | |
| /// throughout the call. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [wrapfd_driver_get_state]. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_release_ownership(wrapfd: RawFd) -> i32 { | |
| // SAFETY: The wrapfd_release_ownership_ioctl is a generated ioctl and | |
| // the caller guarantees the fd remains valid throughout this call. | |
| let res = unsafe { ioctls::wrapfd_release_ownership_ioctl(wrapfd) }; | |
| res.map_or_else(|e| -(e as i32), |_| 0) | |
| } | |
| /// Loads a segment of a file into the buffer at the given offset. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `wrapfd` is a valid file descriptor from [wrapfd_driver_wrap] | |
| /// throughout the call. | |
| /// | |
| /// The caller ensures that `file` is a valid file descriptor that remains valid throughout | |
| /// the call. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [wrapfd_driver_wrap]. | |
| /// - `file`: An fd that we're loading data from. | |
| /// - `file_offset`: Offset into the file being loaded. | |
| /// - `buf_offset`: Offset into the buffer we're loading into. | |
| /// - `len`: Length of the data. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_load( | |
| wrapfd: RawFd, | |
| file: RawFd, | |
| file_offset: u64, | |
| buf_offset: u64, | |
| len: u64, | |
| ) -> i32 { | |
| let load = ioctls::wrapfd_load { | |
| fd: file as u32, | |
| pad: 0, | |
| file_offs: file_offset, | |
| buf_offs: buf_offset, | |
| len, | |
| reserved: 0, | |
| }; | |
| // SAFETY: The wrapfd_load_ioctl is a generated ioctl. Caller guarantees that the wrapfd and | |
| // file fd remain valid throughout this call. | |
| let res = unsafe { ioctls::wrapfd_load_ioctl(wrapfd, &load) }; | |
| res.map_or_else(|e| -(e as i32), |_| 0) | |
| } | |
| /// Move the buffer into a new wrap. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `wrapfd` is a valid file descriptor from [wrapfd_driver_wrap] | |
| /// throughout the call. | |
| /// | |
| // The caller ensures that `wrapfd` is a valid file descriptor throughout this call. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_rewrap(wrapfd: RawFd, prot: i32) -> RawFd { | |
| let rewrap = ioctls::wrapfd_rewrap { prot: prot as u32, pad: 0, reserved: 0 }; | |
| // SAFETY: The wrapfd_rewrap_ioctl is a generated ioctl. Caller guarantees wrapfd is a valid | |
| // fd throughout this call. | |
| let res = unsafe { ioctls::wrapfd_rewrap_ioctl(wrapfd, &rewrap) }; | |
| res.unwrap_or_else(|e| -(e as i32)) | |
| } | |
| /// Free the wrapped buffer. | |
| /// # Safety | |
| /// The caller ensures that `wrapfd` is a valid file descriptor from [wrapfd_driver_wrap] | |
| /// throughout the call. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_empty(wrapfd: RawFd) -> i32 { | |
| // SAFETY: The wrapfd_empty_ioctl is a generated ioctl and caller guarantees that the | |
| // wrapfd remains valid throughout this call. | |
| let res = unsafe { ioctls::wrapfd_empty_ioctl(wrapfd) }; | |
| res.map_or_else(|e| -(e as i32), |_| 0) | |
| } | |
| /// Allow non-owner processes to map the buffer. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `wrapfd` is a valid file descriptor from [wrapfd_driver_wrap] | |
| /// throughout the call. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_allow_guests(wrapfd: RawFd) -> i32 { | |
| // SAFETY: The wrapfd_allow_guests_ioctl is a generated ioctl. Caller guarantees that wrapfd | |
| // remains valid throughout this call. | |
| let res = unsafe { ioctls::wrapfd_allow_guests_ioctl(wrapfd) }; | |
| res.map_or_else(|e| -(e as i32), |_| 0) | |
| } | |
| /// Disallow non-owner processes from mapping the buffer. | |
| /// | |
| /// # Safety | |
| /// The caller ensures that `wrapfd` is a valid file descriptor from [wrapfd_driver_wrap] | |
| /// throughout the call. | |
| /// | |
| /// # Arguments | |
| /// - `wrapfd`: An fd from [WrapfdDriver::wrap]. | |
| #[unsafe(no_mangle)] | |
| pub unsafe extern "C" fn wrapfd_prohibit_guests(wrapfd: RawFd) -> i32 { | |
| // SAFETY: The wrapfd_prohibit_guests_ioctl is a generated ioctl. Caller guarantees that wrapfd | |
| // remains valid throughout this call. | |
| let res = unsafe { ioctls::wrapfd_prohibit_guests_ioctl(wrapfd) }; | |
| res.map_or_else(|e| -(e as i32), |_| 0) | |
| } |