tilo_render_protocol/shm.rs
1//! Shared memory between an app and the processes it draws through: the ring an app writes its
2//! frames into, and the images, fonts and large patch batches it hands over once.
3//!
4//! The app creates every buffer, so its pages are charged to the app: an app cannot push its
5//! memory onto the service.
6//!
7//! The buffers themselves are [`tilo_shm`]'s: a sealed memfd on Linux, unlinked POSIX shared
8//! memory on macOS. On Linux the service maps a buffer read-only only after checking its seals:
9//!
10//! - every buffer is sealed against shrinking, so a mapping the service reads
11//! can never turn into `SIGBUS` under it, and against growing and further
12//! sealing, so its size is the size the service checked;
13//! - an image or font is also sealed against writes: it is immutable once
14//! registered, so what was validated is what is drawn.
15//!
16//! The ring stays writable for the app. The service never trusts what it
17//! read from the ring twice: a frame is decoded into the service's own
18//! memory in one pass ([`crate::scene::decode`]), and only that copy is
19//! validated and drawn.
20//!
21//! Other Unix systems (macOS) cannot seal memory: there an immutable buffer is copied once into
22//! the reader's own memory. The writable ring and `SharedMemory` need seals, so they stay
23//! Linux's.
24
25#[cfg(any(target_os = "linux", target_os = "android"))]
26use std::collections::VecDeque;
27use std::io;
28#[cfg(unix)]
29use std::os::fd::OwnedFd;
30#[cfg(any(target_os = "linux", target_os = "android"))]
31use std::os::fd::{AsFd, BorrowedFd};
32#[cfg(windows)]
33use std::os::windows::io::OwnedHandle;
34
35#[cfg(any(target_os = "linux", target_os = "android"))]
36use memmap2::MmapMut;
37
38pub use tilo_shm::Mapping;
39
40/// A buffer the system made and sealed: a file descriptor on Unix, and on Windows a section's
41/// handle, which a packet carries as it is.
42#[cfg(unix)]
43pub type Sealed = OwnedFd;
44#[cfg(windows)]
45pub type Sealed = OwnedHandle;
46
47/// An immutable buffer holding `bytes`: what an app registers an image's pixels or a font's
48/// bytes in, and hands a large patch batch or a module over in. A memfd sealed against writes and
49/// resizing on Linux, unlinked shared memory elsewhere, a pagefile-backed section on Windows;
50/// [`Mapping::map_sealed`] reads any of them.
51pub fn sealed_blob(name: &str, bytes: &[u8]) -> io::Result<Sealed> {
52 tilo_shm::from_bytes(name, bytes)
53}
54
55#[cfg(any(target_os = "linux", target_os = "android"))]
56/// The app's side of the ring: a writable mapping and the records the
57/// service has not finished with yet.
58pub struct RingWriter {
59 fd: OwnedFd,
60 map: MmapMut,
61 len: usize,
62 /// Records the service has not answered yet, oldest first.
63 outstanding: VecDeque<(u64, usize, usize)>,
64 /// Where the next record goes.
65 head: usize,
66}
67
68#[cfg(any(target_os = "linux", target_os = "android"))]
69impl RingWriter {
70 /// A ring of `len` bytes, sealed against resizing.
71 pub fn create(len: usize) -> io::Result<Self> {
72 let file = tilo_shm::create("tilo-render-ring", len as u64)?;
73 tilo_shm::seal_sizes(&file)?;
74 let map = tilo_shm::map_writable(&file)?;
75 Ok(Self {
76 fd: file.into(),
77 map,
78 len,
79 outstanding: VecDeque::new(),
80 head: 0,
81 })
82 }
83
84 /// The memfd, to send with the hello.
85 pub fn fd(&self) -> BorrowedFd<'_> {
86 self.fd.as_fd()
87 }
88
89 pub fn len(&self) -> usize {
90 self.len
91 }
92
93 pub fn is_empty(&self) -> bool {
94 self.len == 0
95 }
96
97 /// Whether the service still holds any record.
98 pub fn busy(&self) -> bool {
99 !self.outstanding.is_empty()
100 }
101
102 /// Copy `record` into the ring as frame `sequence` and return its
103 /// offset, or `None` when the free space cannot take it now.
104 pub fn write(&mut self, sequence: u64, record: &[u8]) -> Option<usize> {
105 let len = record.len();
106 if len == 0 || len > self.len {
107 return None;
108 }
109 let start = self.place(len)?;
110 let end = start.checked_add(len)?;
111 // `start..end` lies inside the `len`-byte mapping (checked by `place`), and only this
112 // writer writes to it.
113 let ring: &mut [u8] = &mut self.map;
114 ring.get_mut(start..end)?.copy_from_slice(record);
115 self.outstanding.push_back((sequence, start, end));
116 self.head = end;
117 Some(start)
118 }
119
120 /// Where `len` bytes fit without overwriting an outstanding record:
121 /// after the head, or from the start of the ring.
122 fn place(&self, len: usize) -> Option<usize> {
123 let Some(&(_, oldest, _)) = self.outstanding.front() else {
124 return Some(if self.head.checked_add(len)? <= self.len {
125 self.head
126 } else {
127 0
128 });
129 };
130 let head = self.head;
131 if head >= oldest {
132 // Free: head..end and 0..oldest.
133 if head.checked_add(len)? <= self.len {
134 return Some(head);
135 }
136 return (len <= oldest).then_some(0);
137 }
138 // Free: head..oldest.
139 (head.checked_add(len)? <= oldest).then_some(head)
140 }
141
142 /// The service answered every frame up to `sequence`: their space is
143 /// free.
144 pub fn release(&mut self, sequence: u64) {
145 while self
146 .outstanding
147 .front()
148 .is_some_and(|(seq, _, _)| *seq <= sequence)
149 {
150 self.outstanding.pop_front();
151 }
152 }
153
154 /// Forget every outstanding record (the service went away).
155 pub fn reset(&mut self) {
156 self.outstanding.clear();
157 self.head = 0;
158 }
159}
160
161#[cfg(any(target_os = "linux", target_os = "android"))]
162/// A writable shared memfd: a buffer the service without a GPU draws into
163/// and the app attaches as `wl_shm`. Sealed against shrinking, so the
164/// compositor's mapping of it never faults.
165pub struct SharedMemory {
166 fd: OwnedFd,
167 map: MmapMut,
168}
169
170#[cfg(any(target_os = "linux", target_os = "android"))]
171impl SharedMemory {
172 /// `len` zeroed bytes.
173 pub fn create(name: &str, len: usize) -> io::Result<Self> {
174 let file = tilo_shm::create(name, len as u64)?;
175 tilo_shm::seal_sizes(&file)?;
176 let map = tilo_shm::map_writable(&file)?;
177 Ok(Self {
178 fd: file.into(),
179 map,
180 })
181 }
182
183 pub fn fd(&self) -> BorrowedFd<'_> {
184 self.fd.as_fd()
185 }
186
187 pub fn as_mut_slice(&mut self) -> &mut [u8] {
188 &mut self.map
189 }
190}