Skip to main content

tilo_process/
shared_memory.rs

1//! Memory shared with a child process this one starts.
2//!
3//! The parent creates and maps the memory; the child inherits its descriptor at spawn
4//! ([`SharedMemory::hand_to`]) and maps the same pages, so bulk data crosses with one
5//! copy in and one out and no pipe in between.
6//!
7//! On Linux and Android it is a memfd sealed against resizing; on macOS a POSIX shared
8//! memory object unlinked at once.
9
10use std::io;
11use std::process::Command;
12
13pub struct SharedMemory(imp::Memory);
14
15impl SharedMemory {
16    /// New zeroed memory of `len` bytes; `name` labels it for diagnostics.
17    ///
18    /// # Errors
19    ///
20    /// Creation, sizing, sealing or mapping failures; `Unsupported` where there are no child
21    /// processes.
22    pub fn create(name: &str, len: usize) -> io::Result<Self> {
23        imp::Memory::create(name, len).map(Self)
24    }
25
26    /// The first byte of this process's mapping, valid for [`Self::len`] bytes until the
27    /// memory drops. The child writes the same bytes, so read and write them only as the two
28    /// processes agree.
29    #[must_use]
30    pub fn as_ptr(&self) -> *mut u8 {
31        self.0.as_ptr()
32    }
33
34    /// The memory's size in bytes.
35    #[must_use]
36    pub fn len(&self) -> usize {
37        self.0.len()
38    }
39
40    /// Whether the memory has no bytes.
41    #[must_use]
42    pub fn is_empty(&self) -> bool {
43        self.len() == 0
44    }
45
46    pub fn hand_to(&self, command: &mut Command, flag: &str) {
47        self.0.hand_to(command, flag);
48    }
49
50    pub fn handed_over(&mut self) {
51        self.0.handed_over();
52    }
53}
54
55#[cfg(all(
56    unix,
57    any(
58        target_os = "linux",
59        target_os = "android",
60        target_os = "macos",
61        target_os = "ios",
62        target_os = "tvos",
63        target_os = "watchos",
64        target_os = "visionos"
65    )
66))]
67mod imp {
68    use std::io;
69    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
70    use std::process::Command;
71    use std::ptr::NonNull;
72
73    pub struct Memory {
74        base: NonNull<u8>,
75        len: usize,
76        descriptor: Option<OwnedFd>,
77    }
78
79    // SAFETY: the mapping is owned by this value and lives until it drops;
80    // what is read or written through it is the caller's agreement with the
81    // child, as `as_ptr` documents.
82    unsafe impl Send for Memory {}
83    // SAFETY: as above; `&Memory` hands out only the pointer.
84    unsafe impl Sync for Memory {}
85
86    impl Memory {
87        pub fn create(name: &str, len: usize) -> io::Result<Self> {
88            if len == 0 {
89                return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty memory"));
90            }
91            let descriptor = create_descriptor(name)?;
92            let size = libc::off_t::try_from(len).map_err(io::Error::other)?;
93            // SAFETY: an owned descriptor and a size that fits `off_t`.
94            if unsafe { libc::ftruncate(descriptor.as_raw_fd(), size) } != 0 {
95                return Err(io::Error::last_os_error());
96            }
97            seal(&descriptor)?;
98            // SAFETY: a fresh shared mapping of the whole object; nothing in
99            // this process aliases it.
100            let base = unsafe {
101                libc::mmap(
102                    std::ptr::null_mut(),
103                    len,
104                    libc::PROT_READ | libc::PROT_WRITE,
105                    libc::MAP_SHARED,
106                    descriptor.as_raw_fd(),
107                    0,
108                )
109            };
110            if base == libc::MAP_FAILED {
111                return Err(io::Error::last_os_error());
112            }
113            let base = NonNull::new(base.cast()).ok_or_else(|| io::Error::other("null mapping"))?;
114            Ok(Self {
115                base,
116                len,
117                descriptor: Some(descriptor),
118            })
119        }
120
121        pub const fn as_ptr(&self) -> *mut u8 {
122            self.base.as_ptr()
123        }
124
125        pub const fn len(&self) -> usize {
126            self.len
127        }
128
129        pub fn hand_to(&self, command: &mut Command, flag: &str) {
130            use std::os::unix::process::CommandExt;
131            let Some(fd) = self.descriptor.as_ref().map(AsRawFd::as_raw_fd) else {
132                return;
133            };
134            command.arg(format!("{flag}{fd}"));
135            // SAFETY: one async-signal-safe fcntl on a descriptor this value
136            // keeps open until the child has been spawned.
137            unsafe {
138                command.pre_exec(move || {
139                    if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
140                        return Err(io::Error::last_os_error());
141                    }
142                    Ok(())
143                });
144            }
145        }
146
147        pub fn handed_over(&mut self) {
148            self.descriptor = None;
149        }
150    }
151
152    impl Drop for Memory {
153        fn drop(&mut self) {
154            // SAFETY: the mapping `create` made, unmapped once.
155            unsafe { libc::munmap(self.base.as_ptr().cast(), self.len) };
156        }
157    }
158
159    #[cfg(any(target_os = "linux", target_os = "android"))]
160    fn create_descriptor(name: &str) -> io::Result<OwnedFd> {
161        let name = std::ffi::CString::new(name).map_err(io::Error::other)?;
162        // SAFETY: a NUL-terminated name and fixed flags.
163        let fd = unsafe {
164            libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING)
165        };
166        if fd < 0 {
167            return Err(io::Error::last_os_error());
168        }
169        // SAFETY: memfd_create returned a new descriptor nobody else owns.
170        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
171    }
172
173    // The child could otherwise shrink the memory under this process's mapping, which would
174    // then fault reading it.
175    #[cfg(any(target_os = "linux", target_os = "android"))]
176    fn seal(descriptor: &OwnedFd) -> io::Result<()> {
177        // SAFETY: fixed seals on an owned memfd.
178        let sealed = unsafe {
179            libc::fcntl(
180                descriptor.as_raw_fd(),
181                libc::F_ADD_SEALS,
182                libc::F_SEAL_SHRINK | libc::F_SEAL_GROW | libc::F_SEAL_SEAL,
183            )
184        };
185        if sealed != 0 {
186            return Err(io::Error::last_os_error());
187        }
188        Ok(())
189    }
190
191    #[cfg(any(
192        target_os = "macos",
193        target_os = "ios",
194        target_os = "tvos",
195        target_os = "watchos",
196        target_os = "visionos"
197    ))]
198    fn create_descriptor(_name: &str) -> io::Result<OwnedFd> {
199        use std::sync::atomic::{AtomicU64, Ordering};
200        static NEXT: AtomicU64 = AtomicU64::new(0);
201        for _ in 0..8 {
202            // Within macOS's 31 bytes for a shared memory name, which is
203            // gone again before the descriptor is handed on.
204            let name = format!(
205                "/tilo-m{}-{}",
206                std::process::id(),
207                NEXT.fetch_add(1, Ordering::Relaxed)
208            );
209            let name = std::ffi::CString::new(name).map_err(io::Error::other)?;
210            // SAFETY: a NUL-terminated name, fixed flags and mode.
211            let fd = unsafe {
212                libc::shm_open(
213                    name.as_ptr(),
214                    libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
215                    libc::c_uint::from(0o600u16),
216                )
217            };
218            if fd < 0 {
219                let error = io::Error::last_os_error();
220                if error.raw_os_error() == Some(libc::EEXIST) {
221                    continue;
222                }
223                return Err(error);
224            }
225            // SAFETY: shm_open returned a new descriptor nobody else owns.
226            let descriptor = unsafe { OwnedFd::from_raw_fd(fd) };
227            // SAFETY: the name this call created.
228            unsafe { libc::shm_unlink(name.as_ptr()) };
229            // SAFETY: an owned descriptor.
230            if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
231                return Err(io::Error::last_os_error());
232            }
233            return Ok(descriptor);
234        }
235        Err(io::Error::from(io::ErrorKind::AlreadyExists))
236    }
237
238    /// macOS sizes a shared memory object once: it cannot shrink later.
239    #[cfg(any(
240        target_os = "macos",
241        target_os = "ios",
242        target_os = "tvos",
243        target_os = "watchos",
244        target_os = "visionos"
245    ))]
246    #[allow(
247        clippy::unnecessary_wraps,
248        clippy::missing_const_for_fn,
249        reason = "the signature is shared with the Linux seal, which can fail"
250    )]
251    fn seal(_descriptor: &OwnedFd) -> io::Result<()> {
252        Ok(())
253    }
254}
255
256// Neither a memfd nor a POSIX shared memory object exists on a platform this file does
257// not name, so the memory says so.
258#[cfg(all(
259    unix,
260    not(any(
261        target_os = "linux",
262        target_os = "android",
263        target_os = "macos",
264        target_os = "ios",
265        target_os = "tvos",
266        target_os = "watchos",
267        target_os = "visionos"
268    ))
269))]
270mod imp {
271    use std::io;
272    use std::process::Command;
273
274    pub struct Memory(std::convert::Infallible);
275
276    impl Memory {
277        pub fn create(_name: &str, _len: usize) -> io::Result<Self> {
278            Err(io::ErrorKind::Unsupported.into())
279        }
280
281        pub const fn as_ptr(&self) -> *mut u8 {
282            match self.0 {}
283        }
284
285        pub const fn len(&self) -> usize {
286            match self.0 {}
287        }
288
289        pub const fn hand_to(&self, _command: &mut Command, _flag: &str) {
290            match self.0 {}
291        }
292
293        pub const fn handed_over(&self) {
294            match self.0 {}
295        }
296    }
297}
298
299#[cfg(not(unix))]
300mod imp {
301    use std::io;
302    use std::process::Command;
303
304    pub struct Memory(std::convert::Infallible);
305
306    impl Memory {
307        pub fn create(_name: &str, _len: usize) -> io::Result<Self> {
308            Err(io::ErrorKind::Unsupported.into())
309        }
310
311        pub const fn as_ptr(&self) -> *mut u8 {
312            match self.0 {}
313        }
314
315        pub const fn len(&self) -> usize {
316            match self.0 {}
317        }
318
319        pub const fn hand_to(&self, _command: &mut Command, _flag: &str) {
320            match self.0 {}
321        }
322
323        pub const fn handed_over(&self) {
324            match self.0 {}
325        }
326    }
327}
328
329#[cfg(all(test, unix))]
330mod tests {
331    use super::*;
332    use tilo_test_env::SpawnUnderEnvLock as _;
333
334    fn run_child(memory: &mut SharedMemory, script: &str) -> io::Result<std::process::ExitStatus> {
335        let mut command = Command::new("/bin/sh");
336        command.args([
337            "-c",
338            &format!("for argument; do fd=${{argument#--memory=}}; done\n{script}"),
339            "child",
340        ]);
341        memory.hand_to(&mut command, "--memory=");
342        let mut child = command.spawn_locked()?;
343        memory.handed_over();
344        child.wait()
345    }
346
347    #[test]
348    #[cfg(target_os = "linux")]
349    fn a_child_writes_into_the_memory_it_inherits() {
350        let mut memory = SharedMemory::create("tilo-process-test", 4096).unwrap();
351        let status = run_child(
352            &mut memory,
353            "printf '\\001\\002\\003\\004' | dd of=/dev/fd/$fd bs=1 seek=8 conv=notrunc status=none",
354        )
355        .unwrap();
356        assert!(status.success(), "{status}");
357        // SAFETY: in bounds, and the child has exited.
358        let written = unsafe { std::slice::from_raw_parts(memory.as_ptr(), 12) };
359        assert_eq!(written, [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4]);
360    }
361
362    tilo_test_env::scenario! {
363        fn shared_memory_is_inherited_once_and_never_empty;
364
365        phase a_child_inherits_the_memory_once;
366        {
367            let mut memory = SharedMemory::create("tilo-process-test", 4096).unwrap();
368            assert_eq!(memory.len(), 4096);
369            assert!(
370                run_child(&mut memory, "[ -e /dev/fd/$fd ]")
371                    .unwrap()
372                    .success()
373            );
374            let mut again = Command::new("/bin/true");
375            memory.hand_to(&mut again, "--memory=");
376            assert_eq!(again.get_args().count(), 0);
377        }
378
379        phase empty_memory_is_refused;
380        {
381            assert!(SharedMemory::create("tilo-process-test", 0).is_err());
382        }
383    }
384}