synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-wire / src / shm.rs
| 1 | //! The operating-system calls the shared-memory ring needs (Linux, 64-bit): a sealed |
| 2 | //! `memfd` region mapped `MAP_SHARED`, and a futex doorbell. This is the only unsafe code in |
| 3 | //! the crate outside the fuzzer's counting allocator. |
| 4 | //! |
| 5 | //! Declarations and constants are taken from the system headers on the build host (glibc |
| 6 | //! 2.39, aarch64): `sys/mman.h` (`mmap`, `munmap`, `MAP_FAILED`), `bits/mman-linux.h` |
| 7 | //! (`PROT_READ` 1, `PROT_WRITE` 2, `MAP_SHARED` 1), `bits/mman-shared.h` (`memfd_create`), |
| 8 | //! `linux/memfd.h` (`MFD_CLOEXEC` 1, `MFD_ALLOW_SEALING` 2), `bits/fcntl-linux.h` |
| 9 | //! (`F_ADD_SEALS` 1033, `F_GET_SEALS` 1034, `F_SEAL_SEAL` 1, `F_SEAL_SHRINK` 2, |
| 10 | //! `F_SEAL_GROW` 4), `linux/futex.h` (`FUTEX_WAIT` 0, `FUTEX_WAKE` 1) and |
| 11 | //! `asm-generic/unistd.h` (`__NR_futex` 98 on aarch64); 202 on x86_64 as in the kernel's |
| 12 | //! `syscall_64.tbl` (cross-checked against the `libc` 0.2.189 crate source in the local |
| 13 | //! registry). On 64-bit Linux `off_t` and `long` are 64 bits. |
| 14 | //! |
| 15 | //! Why sealed: a reader of a file-backed mapping takes `SIGBUS` if the peer shrinks the file |
| 16 | //! under it. The creator seals its `memfd` against shrinking and growing before anyone can |
| 17 | //! attach, and an attacher refuses any file without the shrink seal. |
| 18 | |
| 19 | use crate::ring::RingRefusal; |
| 20 | use std::ffi::{c_int, c_long, c_uint, c_void}; |
| 21 | use std::fs::File; |
| 22 | use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; |
| 23 | use std::path::{Path, PathBuf}; |
| 24 | use std::ptr::NonNull; |
| 25 | use std::sync::atomic::AtomicU64; |
| 26 | use std::time::Duration; |
| 27 | |
| 28 | const PROT_READ: c_int = 0x1; |
| 29 | const PROT_WRITE: c_int = 0x2; |
| 30 | const MAP_SHARED: c_int = 0x01; |
| 31 | const MFD_CLOEXEC: c_uint = 0x0001; |
| 32 | const MFD_ALLOW_SEALING: c_uint = 0x0002; |
| 33 | const F_ADD_SEALS: c_int = 1033; |
| 34 | const F_GET_SEALS: c_int = 1034; |
| 35 | const F_SEAL_SEAL: c_int = 0x0001; |
| 36 | const F_SEAL_SHRINK: c_int = 0x0002; |
| 37 | const F_SEAL_GROW: c_int = 0x0004; |
| 38 | |
| 39 | extern "C" { |
| 40 | fn mmap( |
| 41 | addr: *mut c_void, |
| 42 | len: usize, |
| 43 | prot: c_int, |
| 44 | flags: c_int, |
| 45 | fd: c_int, |
| 46 | offset: i64, |
| 47 | ) -> *mut c_void; |
| 48 | fn munmap(addr: *mut c_void, len: usize) -> c_int; |
| 49 | fn memfd_create(name: *const std::ffi::c_char, flags: c_uint) -> c_int; |
| 50 | fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int; |
| 51 | } |
| 52 | |
| 53 | /// A `MAP_SHARED` mapping of a whole sealed file, viewed as `u64` atomics. |
| 54 | pub(crate) struct Mapping { |
| 55 | ptr: NonNull<AtomicU64>, |
| 56 | len: usize, |
| 57 | file: File, |
| 58 | } |
| 59 | |
| 60 | // SAFETY: the mapping is plain shared memory that stays mapped until `drop`, and it is only |
| 61 | // ever accessed through `AtomicU64` (see `words`), so sharing or sending the handle between |
| 62 | // threads cannot create a data race. |
| 63 | unsafe impl Send for Mapping {} |
| 64 | // SAFETY: as for `Send`: every access through `&Mapping` is an atomic operation. |
| 65 | unsafe impl Sync for Mapping {} |
| 66 | |
| 67 | pub(crate) enum AttachError { |
| 68 | Io(std::io::Error), |
| 69 | Refused(RingRefusal), |
| 70 | } |
| 71 | |
| 72 | impl Mapping { |
| 73 | /// A new anonymous memory file of `len` bytes (zero-filled), sealed against shrinking, |
| 74 | /// growing and further sealing, then mapped. |
| 75 | pub(crate) fn create(len: usize) -> std::io::Result<Self> { |
| 76 | // SAFETY: the name is a NUL-terminated literal; memfd_create reads it and returns a |
| 77 | // new descriptor or -1. |
| 78 | let fd = unsafe { memfd_create(c"synapse-ring".as_ptr(), MFD_CLOEXEC | MFD_ALLOW_SEALING) }; |
| 79 | if fd < 0 { |
| 80 | return Err(std::io::Error::last_os_error()); |
| 81 | } |
| 82 | // SAFETY: `fd` was just returned by memfd_create, is open, and nothing else owns it. |
| 83 | let file = File::from(unsafe { OwnedFd::from_raw_fd(fd) }); |
| 84 | file.set_len(len as u64)?; |
| 85 | // SAFETY: F_ADD_SEALS takes one int argument; `file` keeps the descriptor open. |
| 86 | let rc = unsafe { |
| 87 | fcntl( |
| 88 | file.as_raw_fd(), |
| 89 | F_ADD_SEALS, |
| 90 | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL, |
| 91 | ) |
| 92 | }; |
| 93 | if rc < 0 { |
| 94 | return Err(std::io::Error::last_os_error()); |
| 95 | } |
| 96 | Self::map(file, len) |
| 97 | } |
| 98 | |
| 99 | /// Open and map a region another process created. Refused unless the file carries the |
| 100 | /// shrink seal and is exactly `len` bytes long. |
| 101 | pub(crate) fn attach(path: &Path, len: usize) -> Result<Self, AttachError> { |
| 102 | let file = std::fs::OpenOptions::new() |
| 103 | .read(true) |
| 104 | .write(true) |
| 105 | .open(path) |
| 106 | .map_err(AttachError::Io)?; |
| 107 | // SAFETY: F_GET_SEALS takes no further argument; `file` keeps the descriptor open. |
| 108 | let seals = unsafe { fcntl(file.as_raw_fd(), F_GET_SEALS) }; |
| 109 | if seals < 0 || seals & F_SEAL_SHRINK == 0 { |
| 110 | return Err(AttachError::Refused(RingRefusal::RegionNotSealed)); |
| 111 | } |
| 112 | let found = file.metadata().map_err(AttachError::Io)?.len(); |
| 113 | if found != len as u64 { |
| 114 | return Err(AttachError::Refused(RingRefusal::RegionSize { |
| 115 | need: len, |
| 116 | found: found as usize, |
| 117 | })); |
| 118 | } |
| 119 | Self::map(file, len).map_err(AttachError::Io) |
| 120 | } |
| 121 | |
| 122 | fn map(file: File, len: usize) -> std::io::Result<Self> { |
| 123 | // SAFETY: a fresh mapping (null hint) of `len` bytes of an open file whose size is |
| 124 | // `len` and cannot shrink (sealed); the kernel validates every argument. |
| 125 | let p = unsafe { |
| 126 | mmap( |
| 127 | std::ptr::null_mut(), |
| 128 | len, |
| 129 | PROT_READ | PROT_WRITE, |
| 130 | MAP_SHARED, |
| 131 | file.as_raw_fd(), |
| 132 | 0, |
| 133 | ) |
| 134 | }; |
| 135 | // MAP_FAILED is ((void *) -1). |
| 136 | if p as usize == usize::MAX { |
| 137 | return Err(std::io::Error::last_os_error()); |
| 138 | } |
| 139 | let ptr = NonNull::new(p.cast::<AtomicU64>()) |
| 140 | .ok_or_else(|| std::io::Error::other("mmap returned null"))?; |
| 141 | Ok(Self { ptr, len, file }) |
| 142 | } |
| 143 | |
| 144 | /// The mapping as words. Every access is atomic, so a peer process writing the same |
| 145 | /// memory concurrently is not a data race on this side. |
| 146 | pub(crate) fn words(&self) -> &[AtomicU64] { |
| 147 | // SAFETY: `ptr` is the start of a live mapping of `len` bytes (unmapped only in |
| 148 | // `drop`, which needs `&mut self`); mappings are page aligned, so the pointer is |
| 149 | // aligned for `AtomicU64`; `AtomicU64` has the size and layout of `u64` and every bit |
| 150 | // pattern is valid; the file cannot shrink, so every page stays backed. |
| 151 | unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len / 8) } |
| 152 | } |
| 153 | |
| 154 | pub(crate) fn attach_path(&self) -> PathBuf { |
| 155 | PathBuf::from(format!( |
| 156 | "/proc/{}/fd/{}", |
| 157 | std::process::id(), |
| 158 | self.file.as_raw_fd() |
| 159 | )) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | impl Drop for Mapping { |
| 164 | fn drop(&mut self) { |
| 165 | // SAFETY: unmaps exactly the mapping made in `map`; no reference from `words` can |
| 166 | // outlive `&self`, and `drop` has exclusive access. |
| 167 | unsafe { |
| 168 | munmap(self.ptr.as_ptr().cast::<c_void>(), self.len); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | #[cfg(target_arch = "aarch64")] |
| 174 | const SYS_FUTEX: c_long = 98; |
| 175 | #[cfg(target_arch = "x86_64")] |
| 176 | const SYS_FUTEX: c_long = 202; |
| 177 | #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] |
| 178 | const FUTEX_WAIT: c_int = 0; |
| 179 | #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] |
| 180 | const FUTEX_WAKE: c_int = 1; |
| 181 | |
| 182 | #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] |
| 183 | extern "C" { |
| 184 | fn syscall(num: c_long, ...) -> c_long; |
| 185 | } |
| 186 | |
| 187 | #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] |
| 188 | #[repr(C)] |
| 189 | struct Timespec { |
| 190 | tv_sec: i64, |
| 191 | tv_nsec: i64, |
| 192 | } |
| 193 | |
| 194 | /// The futex word: the low 32 bits of the doorbell word. |
| 195 | #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] |
| 196 | fn futex_word(word: &AtomicU64) -> *const u32 { |
| 197 | let p = word.as_ptr().cast::<u32>().cast_const(); |
| 198 | if cfg!(target_endian = "big") { |
| 199 | p.wrapping_add(1) |
| 200 | } else { |
| 201 | p |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /// Sleep until the doorbell's low 32 bits differ from `expected`, a wake, or `timeout`. |
| 206 | /// Shared (not private) futex, so it works across processes. Errors (value already |
| 207 | /// changed, timeout, signal) all mean "look again", which the caller does. |
| 208 | #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] |
| 209 | pub(crate) fn futex_wait(word: &AtomicU64, expected: u32, timeout: Duration) { |
| 210 | let ts = Timespec { |
| 211 | tv_sec: timeout.as_secs() as i64, |
| 212 | tv_nsec: i64::from(timeout.subsec_nanos()), |
| 213 | }; |
| 214 | // SAFETY: FUTEX_WAIT reads the aligned 32-bit word at the address (inside a live atomic |
| 215 | // word) and the timespec on this stack frame; it writes nothing. |
| 216 | unsafe { |
| 217 | syscall( |
| 218 | SYS_FUTEX, |
| 219 | futex_word(word), |
| 220 | FUTEX_WAIT, |
| 221 | expected, |
| 222 | &ts as *const Timespec, |
| 223 | ); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// Wake one sleeper on the doorbell. |
| 228 | #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] |
| 229 | pub(crate) fn futex_wake(word: &AtomicU64) { |
| 230 | // SAFETY: FUTEX_WAKE only uses the address as a key (inside a live atomic word). |
| 231 | unsafe { |
| 232 | syscall(SYS_FUTEX, futex_word(word), FUTEX_WAKE, 1 as c_int); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] |
| 237 | pub(crate) fn futex_wait(_word: &AtomicU64, _expected: u32, _timeout: Duration) { |
| 238 | std::thread::sleep(Duration::from_micros(50)); |
| 239 | } |
| 240 | |
| 241 | #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] |
| 242 | pub(crate) fn futex_wake(_word: &AtomicU64) {} |