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        // The system call itself, not libc's wrapper: Android's libc has the wrapper only from
163        // API 30, and the phone runs from API 29, whose kernels all have the call.
164        // SAFETY: a NUL-terminated name and fixed flags.
165        let fd = unsafe {
166            libc::syscall(
167                libc::SYS_memfd_create,
168                name.as_ptr(),
169                libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
170            )
171        };
172        if fd < 0 {
173            return Err(io::Error::last_os_error());
174        }
175        let fd = libc::c_int::try_from(fd).map_err(io::Error::other)?;
176        // SAFETY: memfd_create returned a new descriptor nobody else owns.
177        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
178    }
179
180    // The child could otherwise shrink the memory under this process's mapping, which would
181    // then fault reading it.
182    #[cfg(any(target_os = "linux", target_os = "android"))]
183    fn seal(descriptor: &OwnedFd) -> io::Result<()> {
184        // SAFETY: fixed seals on an owned memfd.
185        let sealed = unsafe {
186            libc::fcntl(
187                descriptor.as_raw_fd(),
188                libc::F_ADD_SEALS,
189                libc::F_SEAL_SHRINK | libc::F_SEAL_GROW | libc::F_SEAL_SEAL,
190            )
191        };
192        if sealed != 0 {
193            return Err(io::Error::last_os_error());
194        }
195        Ok(())
196    }
197
198    #[cfg(any(
199        target_os = "macos",
200        target_os = "ios",
201        target_os = "tvos",
202        target_os = "watchos",
203        target_os = "visionos"
204    ))]
205    fn create_descriptor(_name: &str) -> io::Result<OwnedFd> {
206        use std::sync::atomic::{AtomicU64, Ordering};
207        static NEXT: AtomicU64 = AtomicU64::new(0);
208        for _ in 0..8 {
209            // Within macOS's 31 bytes for a shared memory name, which is
210            // gone again before the descriptor is handed on.
211            let name = format!(
212                "/tilo-m{}-{}",
213                std::process::id(),
214                NEXT.fetch_add(1, Ordering::Relaxed)
215            );
216            let name = std::ffi::CString::new(name).map_err(io::Error::other)?;
217            // SAFETY: a NUL-terminated name, fixed flags and mode.
218            let fd = unsafe {
219                libc::shm_open(
220                    name.as_ptr(),
221                    libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
222                    libc::c_uint::from(0o600u16),
223                )
224            };
225            if fd < 0 {
226                let error = io::Error::last_os_error();
227                if error.raw_os_error() == Some(libc::EEXIST) {
228                    continue;
229                }
230                return Err(error);
231            }
232            // SAFETY: shm_open returned a new descriptor nobody else owns.
233            let descriptor = unsafe { OwnedFd::from_raw_fd(fd) };
234            // SAFETY: the name this call created.
235            unsafe { libc::shm_unlink(name.as_ptr()) };
236            // SAFETY: an owned descriptor.
237            if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
238                return Err(io::Error::last_os_error());
239            }
240            return Ok(descriptor);
241        }
242        Err(io::Error::from(io::ErrorKind::AlreadyExists))
243    }
244
245    /// macOS sizes a shared memory object once: it cannot shrink later.
246    #[cfg(any(
247        target_os = "macos",
248        target_os = "ios",
249        target_os = "tvos",
250        target_os = "watchos",
251        target_os = "visionos"
252    ))]
253    #[allow(
254        clippy::unnecessary_wraps,
255        clippy::missing_const_for_fn,
256        reason = "the signature is shared with the Linux seal, which can fail"
257    )]
258    fn seal(_descriptor: &OwnedFd) -> io::Result<()> {
259        Ok(())
260    }
261}
262
263// Neither a memfd nor a POSIX shared memory object exists on a platform this file does
264// not name, so the memory says so.
265#[cfg(all(
266    unix,
267    not(any(
268        target_os = "linux",
269        target_os = "android",
270        target_os = "macos",
271        target_os = "ios",
272        target_os = "tvos",
273        target_os = "watchos",
274        target_os = "visionos"
275    ))
276))]
277mod imp {
278    use std::io;
279    use std::process::Command;
280
281    pub struct Memory(std::convert::Infallible);
282
283    impl Memory {
284        pub fn create(_name: &str, _len: usize) -> io::Result<Self> {
285            Err(io::ErrorKind::Unsupported.into())
286        }
287
288        pub const fn as_ptr(&self) -> *mut u8 {
289            match self.0 {}
290        }
291
292        pub const fn len(&self) -> usize {
293            match self.0 {}
294        }
295
296        pub const fn hand_to(&self, _command: &mut Command, _flag: &str) {
297            match self.0 {}
298        }
299
300        pub const fn handed_over(&self) {
301            match self.0 {}
302        }
303    }
304}
305
306#[cfg(not(unix))]
307mod imp {
308    use std::io;
309    use std::process::Command;
310
311    pub struct Memory(std::convert::Infallible);
312
313    impl Memory {
314        pub fn create(_name: &str, _len: usize) -> io::Result<Self> {
315            Err(io::ErrorKind::Unsupported.into())
316        }
317
318        pub const fn as_ptr(&self) -> *mut u8 {
319            match self.0 {}
320        }
321
322        pub const fn len(&self) -> usize {
323            match self.0 {}
324        }
325
326        pub const fn hand_to(&self, _command: &mut Command, _flag: &str) {
327            match self.0 {}
328        }
329
330        pub const fn handed_over(&self) {
331            match self.0 {}
332        }
333    }
334}
335
336#[cfg(all(test, unix))]
337mod tests {
338    use super::*;
339    use tilo_test_env::SpawnUnderEnvLock as _;
340
341    fn run_child(memory: &mut SharedMemory, script: &str) -> io::Result<std::process::ExitStatus> {
342        let mut command = Command::new("/bin/sh");
343        command.args([
344            "-c",
345            &format!("for argument; do fd=${{argument#--memory=}}; done\n{script}"),
346            "child",
347        ]);
348        memory.hand_to(&mut command, "--memory=");
349        let mut child = command.spawn_locked()?;
350        memory.handed_over();
351        child.wait()
352    }
353
354    #[test]
355    #[cfg(target_os = "linux")]
356    fn a_child_writes_into_the_memory_it_inherits() {
357        let mut memory = SharedMemory::create("tilo-process-test", 4096).unwrap();
358        let status = run_child(
359            &mut memory,
360            "printf '\\001\\002\\003\\004' | dd of=/dev/fd/$fd bs=1 seek=8 conv=notrunc status=none",
361        )
362        .unwrap();
363        assert!(status.success(), "{status}");
364        // SAFETY: in bounds, and the child has exited.
365        let written = unsafe { std::slice::from_raw_parts(memory.as_ptr(), 12) };
366        assert_eq!(written, [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4]);
367    }
368
369    tilo_test_env::scenario! {
370        fn shared_memory_is_inherited_once_and_never_empty;
371
372        phase a_child_inherits_the_memory_once;
373        {
374            let mut memory = SharedMemory::create("tilo-process-test", 4096).unwrap();
375            assert_eq!(memory.len(), 4096);
376            assert!(
377                run_child(&mut memory, "[ -e /dev/fd/$fd ]")
378                    .unwrap()
379                    .success()
380            );
381            let mut again = Command::new("/bin/true");
382            memory.hand_to(&mut again, "--memory=");
383            assert_eq!(again.get_args().count(), 0);
384        }
385
386        phase empty_memory_is_refused;
387        {
388            assert!(SharedMemory::create("tilo-process-test", 0).is_err());
389        }
390    }
391}