Skip to main content

tilo_shm/
lib.rs

1//! Anonymous memory files: how bulk data crosses a process boundary without copies through a
2//! socket. The writer creates a memory file, fills it and drops every writable mapping. On Linux it
3//! then seals the memfd against writes and resizing, and the reader verifies the seals before
4//! mapping it read-only, so a sealed mapping cannot change under the reader. macOS has no sealing:
5//! there [`Mapping::map_sealed`] copies the bytes once into private memory, which gives the reader
6//! the same guarantee at the price of one copy. macOS also rounds a shared memory object's size up to
7//! the page size, so a file's length is only an upper bound. Every reader here takes the meaningful
8//! length from its caller.
9//!
10//! Windows has no memory files: a buffer there is a pagefile-backed section ([`windows`]). Its
11//! writer fills it and hands on only a handle that maps it read-only, after closing every handle
12//! and view that could write it, so no process can change it again. A section cannot be resized,
13//! so a view of it never faults under its reader either.
14//!
15//! A buffer that stays writable — the ring an app writes its frames into, a render target — is only
16//! sealed against resizing: a mapping the reader holds can never turn into `SIGBUS` under it.
17
18#![cfg(any(unix, windows))]
19
20#[cfg(unix)]
21use std::fs::File;
22#[cfg(unix)]
23use std::io;
24use std::ops::Deref;
25#[cfg(unix)]
26use std::os::fd::{AsFd, OwnedFd};
27
28use memmap2::Mmap;
29#[cfg(unix)]
30use memmap2::{MmapMut, MmapOptions};
31
32#[cfg(windows)]
33pub mod windows;
34#[cfg(windows)]
35pub use windows::from_bytes;
36
37/// The largest page size of a supported system: Apple silicon's 16 KiB.
38#[cfg(not(any(target_os = "linux", target_os = "android")))]
39const MAX_PAGE: usize = 16 * 1024;
40
41#[cfg(unix)]
42/// Create an empty anonymous memory file of at least `len` bytes. `name` is a diagnostic label. A
43/// file can be sized only once on macOS: create it at its final size.
44pub fn create(name: &str, len: u64) -> io::Result<File> {
45    sys::create(name, len)
46}
47
48/// A read-only memory file holding a copy of `bytes`, sealed where the platform can seal.
49#[cfg(unix)]
50pub fn from_bytes(name: &str, bytes: &[u8]) -> io::Result<OwnedFd> {
51    let len = bytes.len() as u64;
52    let file = create(name, len)?;
53    if !bytes.is_empty() {
54        let mut map = map_writable(&file)?;
55        map.get_mut(..bytes.len())
56            .ok_or_else(|| io::Error::other("memory file shorter than requested"))?
57            .copy_from_slice(bytes);
58        map.flush()?;
59    }
60    sys::seal(&file)?;
61    Ok(file.into())
62}
63
64/// Seal `file` against shrinking, growing and further sealing, keeping it writable: a reader maps it
65/// read-only, and its size can no longer change under that mapping.
66#[cfg(unix)]
67pub fn seal_sizes(file: &File) -> io::Result<()> {
68    sys::seal_sizes(file)
69}
70
71/// Bytes read from a memory file or regular file, truncated to the length the caller vouched for.
72pub struct Mapping {
73    backing: Backing,
74    len: usize,
75}
76
77enum Backing {
78    #[cfg_attr(windows, allow(dead_code, reason = "Windows copies what it reads"))]
79    Mapped(Mmap),
80    /// A copy, where this system cannot seal memory.
81    #[cfg_attr(
82        any(target_os = "linux", target_os = "android"),
83        allow(dead_code, reason = "Linux maps instead of copying")
84    )]
85    Copied(Vec<u8>),
86}
87
88impl Mapping {
89    #[cfg(unix)]
90    fn view(map: Mmap, len: usize) -> Self {
91        Self {
92            backing: Backing::Mapped(map),
93            len,
94        }
95    }
96
97    /// Map a whole regular file read-only, limited to `max_len` bytes: a font from the shared
98    /// read-only view, which lives on the image's read-only `/usr` and so cannot shrink under the
99    /// mapping.
100    #[cfg(unix)]
101    pub fn map_file(fd: &OwnedFd, max_len: usize) -> io::Result<Self> {
102        let file = File::from(fd.as_fd().try_clone_to_owned()?);
103        let metadata = file.metadata()?;
104        if !metadata.is_file() {
105            return Err(io::Error::new(
106                io::ErrorKind::InvalidInput,
107                "not a regular file",
108            ));
109        }
110        let len = usize::try_from(metadata.len()).map_err(io::Error::other)?;
111        if len == 0 || len > max_len {
112            return Err(io::Error::new(
113                io::ErrorKind::InvalidData,
114                "a file's size is out of range",
115            ));
116        }
117        // SAFETY: a fresh private read-only mapping of a file we hold, unmapped exactly once in
118        // `Drop`.
119        let map = unsafe { MmapOptions::new().map_copy_read_only(&file) }?;
120        Ok(Self::view(map, len))
121    }
122
123    /// Map a file or memory file read-only, limited to `len` bytes when given (a memory file's size
124    /// can exceed its content). A concurrent truncation by the sender can only fault this process,
125    /// so use it where this process is the confined one.
126    #[cfg(unix)]
127    pub fn map_document(file: &File, len: Option<u64>) -> io::Result<Self> {
128        let actual = file.metadata()?.len();
129        let len = len.unwrap_or(actual);
130        if len == 0 || actual == 0 {
131            return Err(io::Error::new(
132                io::ErrorKind::InvalidData,
133                "the document is empty",
134            ));
135        }
136        if actual < len {
137            return Err(io::Error::new(
138                io::ErrorKind::InvalidData,
139                "the document is shorter than announced",
140            ));
141        }
142        let len = usize::try_from(len).map_err(io::Error::other)?;
143        // SAFETY: see the function documentation; the only party that can be hurt by a changing
144        // file is this (confined) process.
145        let map = unsafe { Mmap::map(file) }?;
146        Ok(Self::view(map, len))
147    }
148
149    pub fn len(&self) -> usize {
150        self.len
151    }
152
153    pub fn is_empty(&self) -> bool {
154        self.len == 0
155    }
156
157    /// `len` bytes at `offset`, or `None` outside the mapping.
158    pub fn get(&self, offset: usize, len: usize) -> Option<&[u8]> {
159        let end = offset.checked_add(len)?;
160        self.as_ref().get(offset..end)
161    }
162}
163
164#[cfg(any(target_os = "linux", target_os = "android"))]
165impl Mapping {
166    /// Map `fd` read-only after checking it is a memfd sealed against resizing (and against writes
167    /// when `immutable`), at least `min_len` bytes and at most `max_len`.
168    pub fn map_sealed(
169        fd: &impl AsFd,
170        immutable: bool,
171        min_len: usize,
172        max_len: usize,
173    ) -> io::Result<Self> {
174        Self::sealed(
175            &File::from(fd.as_fd().try_clone_to_owned()?),
176            immutable,
177            min_len,
178            max_len,
179        )
180    }
181
182    fn sealed(file: &File, immutable: bool, min_len: usize, max_len: usize) -> io::Result<Self> {
183        sys::require_seals(file, immutable)?;
184        let len = usize::try_from(file.metadata()?.len()).map_err(io::Error::other)?;
185        if len < min_len || len > max_len || len == 0 {
186            return Err(io::Error::new(
187                io::ErrorKind::InvalidData,
188                "a shared buffer's size is out of range",
189            ));
190        }
191        // SAFETY: the file is sealed against shrinking, so the mapping can never be truncated under
192        // us, and against writes when `immutable`. An immutable buffer is read whole, so it is
193        // populated up front: one batched fault is far cheaper than one per page. A writable buffer
194        // (the ring) is populated lazily, as the app writes it.
195        let mut options = MmapOptions::new();
196        if immutable {
197            options.populate();
198        }
199        let map = unsafe { options.map(file) }?;
200        Ok(Self::view(map, len))
201    }
202}
203
204#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
205impl Mapping {
206    /// The bytes of `fd`, at least `min_len` and at most `max_len` of them, copied once into this
207    /// process's own read-only memory: nothing seals memory here, so a sender that kept it could
208    /// still change it, but never the copy. A shared memory object's size is rounded up to whole
209    /// pages, so it may exceed `max_len` by less than a page; what lies beyond `max_len` is not
210    /// copied. A writable buffer (`immutable` false) needs seals and is refused.
211    pub fn map_sealed(
212        fd: &impl AsFd,
213        immutable: bool,
214        min_len: usize,
215        max_len: usize,
216    ) -> io::Result<Self> {
217        Self::sealed(
218            &File::from(fd.as_fd().try_clone_to_owned()?),
219            immutable,
220            min_len,
221            max_len,
222        )
223    }
224
225    fn sealed(file: &File, immutable: bool, min_len: usize, max_len: usize) -> io::Result<Self> {
226        if !immutable {
227            return Err(io::Error::new(
228                io::ErrorKind::Unsupported,
229                "a writable shared buffer needs sealed memory, which only Linux has",
230            ));
231        }
232        let size = usize::try_from(file.metadata()?.len()).map_err(io::Error::other)?;
233        let len = size.min(max_len);
234        if size < min_len || len == 0 || size.saturating_sub(max_len) >= MAX_PAGE {
235            return Err(io::Error::new(
236                io::ErrorKind::InvalidData,
237                "a shared buffer's size is out of range",
238            ));
239        }
240        // SAFETY: the sender may still write this memory; the mapping is only read once, to copy
241        // the bytes out, and nothing is inferred from them until the copy is complete.
242        let map = unsafe { MmapOptions::new().len(len).map(file) }?;
243        Ok(Self {
244            backing: Backing::Copied(map.to_vec()),
245            len,
246        })
247    }
248}
249
250impl Deref for Mapping {
251    type Target = [u8];
252
253    fn deref(&self) -> &[u8] {
254        let all: &[u8] = match &self.backing {
255            Backing::Mapped(map) => map,
256            Backing::Copied(bytes) => bytes,
257        };
258        all.get(..self.len).unwrap_or(all)
259    }
260}
261
262impl AsRef<[u8]> for Mapping {
263    fn as_ref(&self) -> &[u8] {
264        self
265    }
266}
267
268/// Map a memory file this process shares with another read-only, for memory the other side writes
269/// on request (a render target).
270#[cfg(unix)]
271pub fn map_shared(file: &File) -> io::Result<Mmap> {
272    // SAFETY: the peer writes this memory only while serving a request the caller made and waits
273    // for; callers treat the bytes as plain data.
274    unsafe { Mmap::map(file) }
275}
276
277#[cfg(unix)]
278pub fn map_writable(file: &File) -> io::Result<MmapMut> {
279    // SAFETY: the file is a memory file shared only with a peer that reads it after this side
280    // reports the write complete. Pages fault in as they are written, so a buffer only as large as
281    // what is used is charged to the writer.
282    unsafe { MmapOptions::new().map_mut(file) }
283}
284
285/// Reopen a regular file read-only, so a descriptor that also allows writing is not handed to a
286/// less trusted process. `None` when the platform cannot name the file (it was deleted, or is not a
287/// regular file); callers then copy the bytes into a memory file.
288#[cfg(unix)]
289#[must_use]
290pub fn reopen_read_only(file: &File) -> Option<File> {
291    sys::reopen_read_only(file)
292}
293
294#[cfg(any(target_os = "linux", target_os = "android"))]
295mod sys {
296    use std::fs::File;
297    use std::io;
298    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
299
300    /// Seals every buffer carries: its size can never change.
301    const SIZE_SEALS: libc::c_int = libc::F_SEAL_SHRINK | libc::F_SEAL_GROW | libc::F_SEAL_SEAL;
302
303    pub fn create(name: &str, len: u64) -> io::Result<File> {
304        let cname = std::ffi::CString::new(name).map_err(io::Error::other)?;
305        // The system call itself, not libc's wrapper: Android's libc has the wrapper only from
306        // API 30, and the phone runs from API 29, whose kernels all have the call.
307        // SAFETY: `cname` is a valid NUL-terminated string for the call.
308        let raw = unsafe {
309            libc::syscall(
310                libc::SYS_memfd_create,
311                cname.as_ptr(),
312                libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
313            )
314        };
315        if raw < 0 {
316            return Err(io::Error::last_os_error());
317        }
318        let raw = libc::c_int::try_from(raw).map_err(io::Error::other)?;
319        // SAFETY: memfd_create returned a fresh descriptor we now own.
320        let file = File::from(unsafe { OwnedFd::from_raw_fd(raw) });
321        file.set_len(len)?;
322        Ok(file)
323    }
324
325    pub fn seal(file: &File) -> io::Result<()> {
326        add_seals(file, SIZE_SEALS | libc::F_SEAL_WRITE)
327    }
328
329    pub fn seal_sizes(file: &File) -> io::Result<()> {
330        add_seals(file, SIZE_SEALS)
331    }
332
333    fn add_seals(file: &File, seals: libc::c_int) -> io::Result<()> {
334        // SAFETY: F_ADD_SEALS on a descriptor we own; no pointers involved.
335        let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, seals) };
336        if rc < 0 {
337            return Err(io::Error::last_os_error());
338        }
339        Ok(())
340    }
341
342    /// Whether `file` carries the seals `immutable` needs: a buffer whose size cannot change, and
343    /// which cannot be written either.
344    pub fn require_seals(file: &File, immutable: bool) -> io::Result<()> {
345        let required = if immutable {
346            SIZE_SEALS | libc::F_SEAL_WRITE
347        } else {
348            SIZE_SEALS
349        };
350        // SAFETY: F_GET_SEALS on a descriptor we own; no pointers involved.
351        let seals = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GET_SEALS) };
352        if seals < 0 {
353            return Err(io::Error::last_os_error());
354        }
355        if seals & required != required {
356            return Err(io::Error::new(
357                io::ErrorKind::PermissionDenied,
358                "a shared buffer must be a sealed memfd",
359            ));
360        }
361        Ok(())
362    }
363
364    pub fn reopen_read_only(file: &File) -> Option<File> {
365        File::open(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()
366    }
367}
368
369#[cfg(target_os = "macos")]
370mod sys {
371    use std::fs::File;
372    use std::io;
373    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
374    use std::sync::atomic::{AtomicU64, Ordering};
375
376    /// `PSHMNAMLEN`: the longest name `shm_open` accepts.
377    const MAX_NAME: usize = 31;
378    /// Every object this crate creates is named under this prefix; the Seatbelt profile lets a
379    /// confined helper create only these.
380    pub const NAME_PREFIX: &str = "/tilo-";
381
382    /// `name` is not used: shared memory names are global, so each object gets a unique one and is
383    /// unlinked at once.
384    pub fn create(_name: &str, len: u64) -> io::Result<File> {
385        static NEXT: AtomicU64 = AtomicU64::new(0);
386        let len = libc::off_t::try_from(len).map_err(io::Error::other)?;
387        for _ in 0..16 {
388            let serial = NEXT.fetch_add(1, Ordering::Relaxed);
389            let mut path = format!("{NAME_PREFIX}{}-{serial}-{:x}", std::process::id(), nonce());
390            path.truncate(MAX_NAME);
391            let cpath = std::ffi::CString::new(path).map_err(io::Error::other)?;
392            // SAFETY: `cpath` is a valid NUL-terminated string for the call.
393            let raw = unsafe {
394                libc::shm_open(
395                    cpath.as_ptr(),
396                    libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
397                    0o600 as libc::c_uint,
398                )
399            };
400            if raw < 0 {
401                let err = io::Error::last_os_error();
402                if err.kind() == io::ErrorKind::AlreadyExists {
403                    continue;
404                }
405                return Err(err);
406            }
407            // SAFETY: shm_open returned a fresh descriptor we now own.
408            let fd = unsafe { OwnedFd::from_raw_fd(raw) };
409            // The object stays alive through the descriptor only. SAFETY: `cpath` is a valid
410            // NUL-terminated string.
411            unsafe { libc::shm_unlink(cpath.as_ptr()) };
412            set_cloexec(&fd)?;
413            // SAFETY: ftruncate on a descriptor we own.
414            if unsafe { libc::ftruncate(fd.as_raw_fd(), len) } != 0 {
415                return Err(io::Error::last_os_error());
416            }
417            return Ok(File::from(fd));
418        }
419        Err(io::Error::new(
420            io::ErrorKind::AlreadyExists,
421            "no free shared memory name",
422        ))
423    }
424
425    fn set_cloexec(fd: &OwnedFd) -> io::Result<()> {
426        // SAFETY: fcntl with integer arguments on a descriptor we own.
427        let rc = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) };
428        if rc < 0 {
429            return Err(io::Error::last_os_error());
430        }
431        Ok(())
432    }
433
434    fn nonce() -> u32 {
435        let mut value = 0u32;
436        // SAFETY: arc4random_buf fills exactly the bytes it is given.
437        unsafe { libc::arc4random_buf((&raw mut value).cast(), size_of::<u32>()) };
438        value
439    }
440
441    #[expect(
442        clippy::unnecessary_wraps,
443        reason = "the same signature as the Linux implementation, where it can fail"
444    )]
445    pub fn seal(_file: &File) -> io::Result<()> {
446        Ok(())
447    }
448
449    /// Unlinked shared memory cannot be sealed, but nothing verifies sizes here: a writable buffer
450    /// is only mapped on Linux.
451    #[expect(
452        clippy::unnecessary_wraps,
453        reason = "the same signature as the Linux implementation, where it can fail"
454    )]
455    pub fn seal_sizes(_file: &File) -> io::Result<()> {
456        Ok(())
457    }
458
459    pub fn reopen_read_only(file: &File) -> Option<File> {
460        let mut buf = vec![0u8; libc::PATH_MAX as usize];
461        // SAFETY: F_GETPATH writes at most PATH_MAX bytes into `buf`.
462        let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
463        if rc < 0 {
464            return None;
465        }
466        let end = buf.iter().position(|&b| b == 0)?;
467        buf.truncate(end);
468        let path = std::path::PathBuf::from(
469            <std::ffi::OsString as std::os::unix::ffi::OsStringExt>::from_vec(buf),
470        );
471        let reopened = File::open(path).ok()?;
472        let same = |f: &File| {
473            f.metadata().ok().map(|m| {
474                use std::os::unix::fs::MetadataExt;
475                (m.dev(), m.ino())
476            })
477        };
478        (same(file)? == same(&reopened)?).then_some(reopened)
479    }
480}
481
482#[cfg(all(
483    unix,
484    not(any(target_os = "linux", target_os = "android", target_os = "macos"))
485))]
486mod sys {
487    use std::fs::File;
488    use std::io;
489
490    pub fn create(_name: &str, _len: u64) -> io::Result<File> {
491        Err(io::Error::new(
492            io::ErrorKind::Unsupported,
493            "no anonymous memory files on this platform",
494        ))
495    }
496
497    #[expect(
498        clippy::unnecessary_wraps,
499        reason = "the signature of the platforms that seal memory, whose callers this shares"
500    )]
501    pub fn seal(_file: &File) -> io::Result<()> {
502        Ok(())
503    }
504
505    #[expect(
506        clippy::unnecessary_wraps,
507        reason = "the signature of the platforms that seal memory, whose callers this shares"
508    )]
509    pub fn seal_sizes(_file: &File) -> io::Result<()> {
510        Ok(())
511    }
512
513    pub fn reopen_read_only(_file: &File) -> Option<File> {
514        None
515    }
516}
517
518#[cfg(all(test, unix))]
519mod tests {
520    use super::*;
521
522    #[cfg(any(target_os = "linux", target_os = "android"))]
523    #[test]
524    fn unsealed_memfd_is_refused() {
525        let unsealed: OwnedFd = create("u", 4).unwrap().into();
526        assert!(Mapping::map_sealed(&unsealed, true, 4, 4).is_err());
527    }
528
529    #[cfg(any(target_os = "linux", target_os = "android"))]
530    #[test]
531    fn a_sizes_sealed_buffer_maps_read_only_while_its_writer_keeps_it() {
532        let file = create("ring", 8).unwrap();
533        seal_sizes(&file).unwrap();
534        let fd: OwnedFd = file.as_fd().try_clone_to_owned().unwrap();
535        let mut writer = map_writable(&file).unwrap();
536        writer[..3].copy_from_slice(b"abc");
537        let reader = Mapping::map_sealed(&fd, false, 8, 8).unwrap();
538        assert_eq!(&reader[..3], b"abc");
539        assert!(
540            Mapping::map_sealed(&fd, true, 8, 8).is_err(),
541            "a writable buffer is not an immutable one"
542        );
543    }
544
545    tilo_test_env::scenario! {
546        fn memory_files_map_at_their_length_share_writes_and_reopen_read_only;
547
548        phase memory_file_round_trips_with_its_length;
549        {
550            let fd = from_bytes("t", b"hello").unwrap();
551            let bytes = Mapping::map_sealed(&fd, true, 5, 5).unwrap();
552            assert_eq!(&bytes[..], b"hello");
553            let file = File::from(fd.try_clone().unwrap());
554            assert_eq!(&Mapping::map_document(&file, Some(5)).unwrap()[..], b"hello");
555        }
556
557        phase empty_and_short_buffers_are_refused;
558        {
559            let fd = from_bytes("t", b"hello").unwrap();
560            assert!(Mapping::map_sealed(&fd, true, 0, 0).is_err());
561            assert!(Mapping::map_sealed(&fd, true, 1 << 30, 1 << 30).is_err());
562        }
563
564        phase shared_mapping_sees_the_writers_bytes;
565        {
566            let file = create("pixels", 4096).unwrap();
567            let reader = map_shared(&file).unwrap();
568            let writer_file = File::from(file.as_fd().try_clone_to_owned().unwrap());
569            let mut writer = map_writable(&writer_file).unwrap();
570            writer[..4].copy_from_slice(b"rgba");
571            assert_eq!(&reader[..4], b"rgba");
572        }
573
574        phase a_regular_file_reopens_read_only;
575        {
576            let dir = std::env::temp_dir().join(format!("tilo-shm-{}", std::process::id()));
577            std::fs::create_dir_all(&dir).unwrap();
578            let path = dir.join("doc.pdf");
579            std::fs::write(&path, b"%PDF").unwrap();
580            let rw = std::fs::OpenOptions::new()
581                .read(true)
582                .write(true)
583                .open(&path)
584                .unwrap();
585            let ro = reopen_read_only(&rw).expect("regular files reopen");
586            let mut probe = &ro;
587            assert!(std::io::Write::write(&mut probe, b"x").is_err());
588            let _ = std::fs::remove_dir_all(&dir);
589        }
590    }
591}