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        // SAFETY: `cname` is a valid NUL-terminated string for the call.
306        let raw = unsafe {
307            libc::memfd_create(cname.as_ptr(), libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING)
308        };
309        if raw < 0 {
310            return Err(io::Error::last_os_error());
311        }
312        // SAFETY: memfd_create returned a fresh descriptor we now own.
313        let file = File::from(unsafe { OwnedFd::from_raw_fd(raw) });
314        file.set_len(len)?;
315        Ok(file)
316    }
317
318    pub fn seal(file: &File) -> io::Result<()> {
319        add_seals(file, SIZE_SEALS | libc::F_SEAL_WRITE)
320    }
321
322    pub fn seal_sizes(file: &File) -> io::Result<()> {
323        add_seals(file, SIZE_SEALS)
324    }
325
326    fn add_seals(file: &File, seals: libc::c_int) -> io::Result<()> {
327        // SAFETY: F_ADD_SEALS on a descriptor we own; no pointers involved.
328        let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, seals) };
329        if rc < 0 {
330            return Err(io::Error::last_os_error());
331        }
332        Ok(())
333    }
334
335    /// Whether `file` carries the seals `immutable` needs: a buffer whose size cannot change, and
336    /// which cannot be written either.
337    pub fn require_seals(file: &File, immutable: bool) -> io::Result<()> {
338        let required = if immutable {
339            SIZE_SEALS | libc::F_SEAL_WRITE
340        } else {
341            SIZE_SEALS
342        };
343        // SAFETY: F_GET_SEALS on a descriptor we own; no pointers involved.
344        let seals = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GET_SEALS) };
345        if seals < 0 {
346            return Err(io::Error::last_os_error());
347        }
348        if seals & required != required {
349            return Err(io::Error::new(
350                io::ErrorKind::PermissionDenied,
351                "a shared buffer must be a sealed memfd",
352            ));
353        }
354        Ok(())
355    }
356
357    pub fn reopen_read_only(file: &File) -> Option<File> {
358        File::open(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()
359    }
360}
361
362#[cfg(target_os = "macos")]
363mod sys {
364    use std::fs::File;
365    use std::io;
366    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
367    use std::sync::atomic::{AtomicU64, Ordering};
368
369    /// `PSHMNAMLEN`: the longest name `shm_open` accepts.
370    const MAX_NAME: usize = 31;
371    /// Every object this crate creates is named under this prefix; the Seatbelt profile lets a
372    /// confined helper create only these.
373    pub const NAME_PREFIX: &str = "/tilo-";
374
375    /// `name` is not used: shared memory names are global, so each object gets a unique one and is
376    /// unlinked at once.
377    pub fn create(_name: &str, len: u64) -> io::Result<File> {
378        static NEXT: AtomicU64 = AtomicU64::new(0);
379        let len = libc::off_t::try_from(len).map_err(io::Error::other)?;
380        for _ in 0..16 {
381            let serial = NEXT.fetch_add(1, Ordering::Relaxed);
382            let mut path = format!("{NAME_PREFIX}{}-{serial}-{:x}", std::process::id(), nonce());
383            path.truncate(MAX_NAME);
384            let cpath = std::ffi::CString::new(path).map_err(io::Error::other)?;
385            // SAFETY: `cpath` is a valid NUL-terminated string for the call.
386            let raw = unsafe {
387                libc::shm_open(
388                    cpath.as_ptr(),
389                    libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
390                    0o600 as libc::c_uint,
391                )
392            };
393            if raw < 0 {
394                let err = io::Error::last_os_error();
395                if err.kind() == io::ErrorKind::AlreadyExists {
396                    continue;
397                }
398                return Err(err);
399            }
400            // SAFETY: shm_open returned a fresh descriptor we now own.
401            let fd = unsafe { OwnedFd::from_raw_fd(raw) };
402            // The object stays alive through the descriptor only. SAFETY: `cpath` is a valid
403            // NUL-terminated string.
404            unsafe { libc::shm_unlink(cpath.as_ptr()) };
405            set_cloexec(&fd)?;
406            // SAFETY: ftruncate on a descriptor we own.
407            if unsafe { libc::ftruncate(fd.as_raw_fd(), len) } != 0 {
408                return Err(io::Error::last_os_error());
409            }
410            return Ok(File::from(fd));
411        }
412        Err(io::Error::new(
413            io::ErrorKind::AlreadyExists,
414            "no free shared memory name",
415        ))
416    }
417
418    fn set_cloexec(fd: &OwnedFd) -> io::Result<()> {
419        // SAFETY: fcntl with integer arguments on a descriptor we own.
420        let rc = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) };
421        if rc < 0 {
422            return Err(io::Error::last_os_error());
423        }
424        Ok(())
425    }
426
427    fn nonce() -> u32 {
428        let mut value = 0u32;
429        // SAFETY: arc4random_buf fills exactly the bytes it is given.
430        unsafe { libc::arc4random_buf((&raw mut value).cast(), size_of::<u32>()) };
431        value
432    }
433
434    #[expect(
435        clippy::unnecessary_wraps,
436        reason = "the same signature as the Linux implementation, where it can fail"
437    )]
438    pub fn seal(_file: &File) -> io::Result<()> {
439        Ok(())
440    }
441
442    /// Unlinked shared memory cannot be sealed, but nothing verifies sizes here: a writable buffer
443    /// is only mapped on Linux.
444    #[expect(
445        clippy::unnecessary_wraps,
446        reason = "the same signature as the Linux implementation, where it can fail"
447    )]
448    pub fn seal_sizes(_file: &File) -> io::Result<()> {
449        Ok(())
450    }
451
452    pub fn reopen_read_only(file: &File) -> Option<File> {
453        let mut buf = vec![0u8; libc::PATH_MAX as usize];
454        // SAFETY: F_GETPATH writes at most PATH_MAX bytes into `buf`.
455        let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
456        if rc < 0 {
457            return None;
458        }
459        let end = buf.iter().position(|&b| b == 0)?;
460        buf.truncate(end);
461        let path = std::path::PathBuf::from(
462            <std::ffi::OsString as std::os::unix::ffi::OsStringExt>::from_vec(buf),
463        );
464        let reopened = File::open(path).ok()?;
465        let same = |f: &File| {
466            f.metadata().ok().map(|m| {
467                use std::os::unix::fs::MetadataExt;
468                (m.dev(), m.ino())
469            })
470        };
471        (same(file)? == same(&reopened)?).then_some(reopened)
472    }
473}
474
475#[cfg(all(
476    unix,
477    not(any(target_os = "linux", target_os = "android", target_os = "macos"))
478))]
479mod sys {
480    use std::fs::File;
481    use std::io;
482
483    pub fn create(_name: &str, _len: u64) -> io::Result<File> {
484        Err(io::Error::new(
485            io::ErrorKind::Unsupported,
486            "no anonymous memory files on this platform",
487        ))
488    }
489
490    #[expect(
491        clippy::unnecessary_wraps,
492        reason = "the signature of the platforms that seal memory, whose callers this shares"
493    )]
494    pub fn seal(_file: &File) -> io::Result<()> {
495        Ok(())
496    }
497
498    #[expect(
499        clippy::unnecessary_wraps,
500        reason = "the signature of the platforms that seal memory, whose callers this shares"
501    )]
502    pub fn seal_sizes(_file: &File) -> io::Result<()> {
503        Ok(())
504    }
505
506    pub fn reopen_read_only(_file: &File) -> Option<File> {
507        None
508    }
509}
510
511#[cfg(all(test, unix))]
512mod tests {
513    use super::*;
514
515    #[cfg(any(target_os = "linux", target_os = "android"))]
516    #[test]
517    fn unsealed_memfd_is_refused() {
518        let unsealed: OwnedFd = create("u", 4).unwrap().into();
519        assert!(Mapping::map_sealed(&unsealed, true, 4, 4).is_err());
520    }
521
522    #[cfg(any(target_os = "linux", target_os = "android"))]
523    #[test]
524    fn a_sizes_sealed_buffer_maps_read_only_while_its_writer_keeps_it() {
525        let file = create("ring", 8).unwrap();
526        seal_sizes(&file).unwrap();
527        let fd: OwnedFd = file.as_fd().try_clone_to_owned().unwrap();
528        let mut writer = map_writable(&file).unwrap();
529        writer[..3].copy_from_slice(b"abc");
530        let reader = Mapping::map_sealed(&fd, false, 8, 8).unwrap();
531        assert_eq!(&reader[..3], b"abc");
532        assert!(
533            Mapping::map_sealed(&fd, true, 8, 8).is_err(),
534            "a writable buffer is not an immutable one"
535        );
536    }
537
538    tilo_test_env::scenario! {
539        fn memory_files_map_at_their_length_share_writes_and_reopen_read_only;
540
541        phase memory_file_round_trips_with_its_length;
542        {
543            let fd = from_bytes("t", b"hello").unwrap();
544            let bytes = Mapping::map_sealed(&fd, true, 5, 5).unwrap();
545            assert_eq!(&bytes[..], b"hello");
546            let file = File::from(fd.try_clone().unwrap());
547            assert_eq!(&Mapping::map_document(&file, Some(5)).unwrap()[..], b"hello");
548        }
549
550        phase empty_and_short_buffers_are_refused;
551        {
552            let fd = from_bytes("t", b"hello").unwrap();
553            assert!(Mapping::map_sealed(&fd, true, 0, 0).is_err());
554            assert!(Mapping::map_sealed(&fd, true, 1 << 30, 1 << 30).is_err());
555        }
556
557        phase shared_mapping_sees_the_writers_bytes;
558        {
559            let file = create("pixels", 4096).unwrap();
560            let reader = map_shared(&file).unwrap();
561            let writer_file = File::from(file.as_fd().try_clone_to_owned().unwrap());
562            let mut writer = map_writable(&writer_file).unwrap();
563            writer[..4].copy_from_slice(b"rgba");
564            assert_eq!(&reader[..4], b"rgba");
565        }
566
567        phase a_regular_file_reopens_read_only;
568        {
569            let dir = std::env::temp_dir().join(format!("tilo-shm-{}", std::process::id()));
570            std::fs::create_dir_all(&dir).unwrap();
571            let path = dir.join("doc.pdf");
572            std::fs::write(&path, b"%PDF").unwrap();
573            let rw = std::fs::OpenOptions::new()
574                .read(true)
575                .write(true)
576                .open(&path)
577                .unwrap();
578            let ro = reopen_read_only(&rw).expect("regular files reopen");
579            let mut probe = &ro;
580            assert!(std::io::Write::write(&mut probe, b"x").is_err());
581            let _ = std::fs::remove_dir_all(&dir);
582        }
583    }
584}