|
| 1 | +//! `memfd`-backed shared-memory buffers for cross-process content (Linux). |
| 2 | +//! |
| 3 | +//! The **CPU side of the Forma-as-compositor content path**: a content process |
| 4 | +//! renders pixels into a [`SharedBuffer`] (a `memfd` mapped `MAP_SHARED`) and |
| 5 | +//! passes its fd to the UI process over a Unix socket with [`crate::scm`]; the UI |
| 6 | +//! process maps the same fd ([`SharedBuffer::from_fd`]) and composites the pixels |
| 7 | +//! into a viewport. This is the dual of the GPU `dma-buf` path — the same |
| 8 | +//! architecture (a separate, sandboxable process; the buffer fd handed over a |
| 9 | +//! socket) with a CPU buffer instead of a GPU texture, so it works with no GPU |
| 10 | +//! (and is the path used when GPU sharing is unavailable). |
| 11 | +//! |
| 12 | +//! `memfd_create`/`mmap`/`munmap` are raw libc FFI — the reason for the |
| 13 | +//! module-level `allow(unsafe_code)` (the rest of the crate stays safe). |
| 14 | +#![allow(unsafe_code)] |
| 15 | + |
| 16 | +use std::ffi::{c_char, c_void}; |
| 17 | +use std::io; |
| 18 | +use std::os::fd::RawFd; |
| 19 | + |
| 20 | +unsafe extern "C" { |
| 21 | + fn memfd_create(name: *const c_char, flags: u32) -> i32; |
| 22 | + fn ftruncate(fd: i32, length: i64) -> i32; |
| 23 | + fn mmap(addr: *mut c_void, len: usize, prot: i32, flags: i32, fd: i32, off: i64) |
| 24 | + -> *mut c_void; |
| 25 | + fn munmap(addr: *mut c_void, len: usize) -> i32; |
| 26 | + fn close(fd: i32) -> i32; |
| 27 | +} |
| 28 | + |
| 29 | +const PROT_READ: i32 = 1; |
| 30 | +const PROT_WRITE: i32 = 2; |
| 31 | +const MAP_SHARED: i32 = 1; |
| 32 | +const MAP_FAILED: *mut c_void = usize::MAX as *mut c_void; |
| 33 | + |
| 34 | +/// A `memfd`-backed byte region mapped `MAP_SHARED` into this process. Owns the |
| 35 | +/// fd and the mapping; both are released on drop. Share it across a process |
| 36 | +/// boundary by passing [`fd`](SharedBuffer::fd) over a socket (see |
| 37 | +/// [`crate::scm::send_with_fds`]) and re-mapping it in the peer with |
| 38 | +/// [`from_fd`](SharedBuffer::from_fd) — writes through either mapping are visible |
| 39 | +/// to the other. |
| 40 | +pub struct SharedBuffer { |
| 41 | + fd: RawFd, |
| 42 | + ptr: *mut u8, |
| 43 | + len: usize, |
| 44 | +} |
| 45 | + |
| 46 | +impl SharedBuffer { |
| 47 | + /// Create a new `memfd` of `len` bytes, mapped read/write. |
| 48 | + pub fn create(len: usize) -> io::Result<Self> { |
| 49 | + if len == 0 { |
| 50 | + return Err(io::Error::new( |
| 51 | + io::ErrorKind::InvalidInput, |
| 52 | + "zero-length shared buffer", |
| 53 | + )); |
| 54 | + } |
| 55 | + let name = c"forma-shm"; |
| 56 | + let fd = unsafe { memfd_create(name.as_ptr(), 0) }; |
| 57 | + if fd < 0 { |
| 58 | + return Err(io::Error::last_os_error()); |
| 59 | + } |
| 60 | + if unsafe { ftruncate(fd, len as i64) } < 0 { |
| 61 | + let e = io::Error::last_os_error(); |
| 62 | + unsafe { close(fd) }; |
| 63 | + return Err(e); |
| 64 | + } |
| 65 | + Self::map(fd, len) |
| 66 | + } |
| 67 | + |
| 68 | + /// Map an existing `memfd` `fd` of `len` bytes — e.g. a buffer fd received |
| 69 | + /// from a content process over a socket. Takes ownership of `fd` (closed on |
| 70 | + /// drop). The caller must ensure `fd` really refers to a region of at least |
| 71 | + /// `len` bytes. |
| 72 | + pub fn from_fd(fd: RawFd, len: usize) -> io::Result<Self> { |
| 73 | + Self::map(fd, len) |
| 74 | + } |
| 75 | + |
| 76 | + fn map(fd: RawFd, len: usize) -> io::Result<Self> { |
| 77 | + let ptr = unsafe { |
| 78 | + mmap( |
| 79 | + core::ptr::null_mut(), |
| 80 | + len, |
| 81 | + PROT_READ | PROT_WRITE, |
| 82 | + MAP_SHARED, |
| 83 | + fd, |
| 84 | + 0, |
| 85 | + ) |
| 86 | + }; |
| 87 | + if ptr == MAP_FAILED { |
| 88 | + let e = io::Error::last_os_error(); |
| 89 | + unsafe { close(fd) }; |
| 90 | + return Err(e); |
| 91 | + } |
| 92 | + Ok(Self { |
| 93 | + fd, |
| 94 | + ptr: ptr as *mut u8, |
| 95 | + len, |
| 96 | + }) |
| 97 | + } |
| 98 | + |
| 99 | + /// The backing `memfd` (for passing to a peer via `SCM_RIGHTS`). |
| 100 | + #[inline] |
| 101 | + pub fn fd(&self) -> RawFd { |
| 102 | + self.fd |
| 103 | + } |
| 104 | + |
| 105 | + /// Length in bytes. |
| 106 | + #[inline] |
| 107 | + pub fn len(&self) -> usize { |
| 108 | + self.len |
| 109 | + } |
| 110 | + |
| 111 | + #[inline] |
| 112 | + pub fn is_empty(&self) -> bool { |
| 113 | + self.len == 0 |
| 114 | + } |
| 115 | + |
| 116 | + #[inline] |
| 117 | + pub fn as_slice(&self) -> &[u8] { |
| 118 | + unsafe { std::slice::from_raw_parts(self.ptr, self.len) } |
| 119 | + } |
| 120 | + |
| 121 | + #[inline] |
| 122 | + pub fn as_mut_slice(&mut self) -> &mut [u8] { |
| 123 | + unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) } |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +impl core::fmt::Debug for SharedBuffer { |
| 128 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 129 | + f.debug_struct("SharedBuffer") |
| 130 | + .field("fd", &self.fd) |
| 131 | + .field("len", &self.len) |
| 132 | + .finish() |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +impl Drop for SharedBuffer { |
| 137 | + fn drop(&mut self) { |
| 138 | + unsafe { |
| 139 | + munmap(self.ptr as *mut c_void, self.len); |
| 140 | + close(self.fd); |
| 141 | + } |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +// SAFETY: the handle owns a plain shared byte region; moving it between threads |
| 146 | +// is sound (concurrent access is &/&mut-guarded like any slice). |
| 147 | +unsafe impl Send for SharedBuffer {} |
| 148 | + |
| 149 | +#[cfg(test)] |
| 150 | +mod tests { |
| 151 | + use super::*; |
| 152 | + |
| 153 | + unsafe extern "C" { |
| 154 | + fn dup(oldfd: i32) -> i32; |
| 155 | + } |
| 156 | + |
| 157 | + #[test] |
| 158 | + fn second_mapping_sees_writes_through_the_shared_memfd() { |
| 159 | + let mut a = SharedBuffer::create(64).expect("create"); |
| 160 | + a.as_mut_slice()[..4].copy_from_slice(&[1, 2, 3, 4]); |
| 161 | + |
| 162 | + // A second mapping of the same memfd (as a peer process would make from a |
| 163 | + // received fd) sees the producer's writes — proving MAP_SHARED sharing. |
| 164 | + let fd2 = unsafe { dup(a.fd()) }; |
| 165 | + assert!(fd2 >= 0, "dup failed"); |
| 166 | + let mut b = SharedBuffer::from_fd(fd2, 64).expect("from_fd"); |
| 167 | + assert_eq!(&b.as_slice()[..4], &[1, 2, 3, 4]); |
| 168 | + |
| 169 | + // ...and writes through the second mapping are visible through the first. |
| 170 | + b.as_mut_slice()[8..12].copy_from_slice(&[9, 9, 9, 9]); |
| 171 | + assert_eq!(&a.as_slice()[8..12], &[9, 9, 9, 9]); |
| 172 | + } |
| 173 | +} |
0 commit comments