1use std::io;
11use std::process::Command;
12
13pub struct SharedMemory(imp::Memory);
14
15impl SharedMemory {
16 pub fn create(name: &str, len: usize) -> io::Result<Self> {
23 imp::Memory::create(name, len).map(Self)
24 }
25
26 #[must_use]
30 pub fn as_ptr(&self) -> *mut u8 {
31 self.0.as_ptr()
32 }
33
34 #[must_use]
36 pub fn len(&self) -> usize {
37 self.0.len()
38 }
39
40 #[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 unsafe impl Send for Memory {}
83 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 if unsafe { libc::ftruncate(descriptor.as_raw_fd(), size) } != 0 {
95 return Err(io::Error::last_os_error());
96 }
97 seal(&descriptor)?;
98 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 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 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 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 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
178 }
179
180 #[cfg(any(target_os = "linux", target_os = "android"))]
183 fn seal(descriptor: &OwnedFd) -> io::Result<()> {
184 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 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 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 let descriptor = unsafe { OwnedFd::from_raw_fd(fd) };
234 unsafe { libc::shm_unlink(name.as_ptr()) };
236 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 #[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#[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 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}