forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

shm_mapping.rs63 lines, 2.0 KiBHistoryRawDownload
1use std::os::fd::BorrowedFd;
2use std::{ptr, slice};
3
4use anyhow::{ensure, Context as _};
5use smithay::reexports::rustix::mm::{mmap, munmap, MapFlags, ProtFlags};
6
7/// Owns a mapping of a sealed, fixed-size memfd. No references into it escape.
8#[derive(Debug)]
9pub(super) struct ShmMapping {
10 address: *mut std::ffi::c_void,
11 len: usize,
12}
13
14impl ShmMapping {
15 /// # Safety
16 ///
17 /// The file must contain at least `len` initialized bytes and must not shrink
18 /// while mapped. Access through other mappings must be synchronized with
19 /// calls to `copy_frame` and `clear` for the lifetime of this mapping.
20 pub(super) unsafe fn new(fd: BorrowedFd<'_>, len: usize) -> anyhow::Result<Self> {
21 ensure!(
22 len > 0 && len <= isize::MAX as usize,
23 "invalid mapping length"
24 );
25 let address = unsafe {
26 mmap(
27 ptr::null_mut(),
28 len,
29 ProtFlags::READ | ProtFlags::WRITE,
30 MapFlags::SHARED,
31 fd,
32 0,
33 )
34 }
35 .context("error mapping SHM buffer")?;
36 Ok(Self { address, len })
37 }
38
39 pub(super) fn copy_frame(&self, bytes: &[u8]) {
40 let _span = tracy_client::span!();
41
42 // SAFETY: The constructor's contract keeps the memory valid and ensures
43 // exclusive access during this write. No references into the mapping escape.
44 let buffer = unsafe { slice::from_raw_parts_mut(self.address.cast::<u8>(), self.len) };
45 buffer.copy_from_slice(bytes);
46 }
47
48 pub(super) fn clear(&self) {
49 let _span = tracy_client::span!();
50
51 // SAFETY: As in copy_frame, the mapping is valid and exclusively accessed.
52 let buffer = unsafe { slice::from_raw_parts_mut(self.address.cast::<u8>(), self.len) };
53 buffer.fill(0);
54 }
55}
56
57impl Drop for ShmMapping {
58 fn drop(&mut self) {
59 if let Err(err) = unsafe { munmap(self.address, self.len) } {
60 warn!("error unmapping SHM buffer: {err}");
61 }
62 }
63}