1#![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#[cfg(not(any(target_os = "linux", target_os = "android")))]
39const MAX_PAGE: usize = 16 * 1024;
40
41#[cfg(unix)]
42pub fn create(name: &str, len: u64) -> io::Result<File> {
45 sys::create(name, len)
46}
47
48#[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#[cfg(unix)]
67pub fn seal_sizes(file: &File) -> io::Result<()> {
68 sys::seal_sizes(file)
69}
70
71pub 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 #[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 #[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 let map = unsafe { MmapOptions::new().map_copy_read_only(&file) }?;
120 Ok(Self::view(map, len))
121 }
122
123 #[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 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 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 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 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 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 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#[cfg(unix)]
271pub fn map_shared(file: &File) -> io::Result<Mmap> {
272 unsafe { Mmap::map(file) }
275}
276
277#[cfg(unix)]
278pub fn map_writable(file: &File) -> io::Result<MmapMut> {
279 unsafe { MmapOptions::new().map_mut(file) }
283}
284
285#[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 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 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 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 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 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 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 const MAX_NAME: usize = 31;
371 pub const NAME_PREFIX: &str = "/tilo-";
374
375 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 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 let fd = unsafe { OwnedFd::from_raw_fd(raw) };
402 unsafe { libc::shm_unlink(cpath.as_ptr()) };
405 set_cloexec(&fd)?;
406 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 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 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 #[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 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}