1use std::io;
4use std::ptr::NonNull;
5
6#[derive(Debug)]
7struct Mapping {
8 start: NonNull<u8>,
9 len: usize,
10}
11
12unsafe impl Send for Mapping {}
14unsafe impl Sync for Mapping {}
16
17impl Drop for Mapping {
18 fn drop(&mut self) {
19 platform::unmap(self.start, self.len);
20 }
21}
22
23#[derive(Debug)]
26pub struct SharedRegion {
27 mapping: Mapping,
28 share: platform::Share,
29}
30
31impl SharedRegion {
32 pub fn create(len: usize) -> io::Result<Self> {
38 if len == 0 {
39 return Err(io::Error::new(
40 io::ErrorKind::InvalidInput,
41 "a region of no bytes",
42 ));
43 }
44 let (mapping, share) = platform::create(len)?;
45 Ok(Self { mapping, share })
46 }
47
48 #[must_use]
50 pub const fn len(&self) -> usize {
51 self.mapping.len
52 }
53
54 #[must_use]
56 pub const fn is_empty(&self) -> bool {
57 self.mapping.len == 0
58 }
59
60 pub const fn as_mut_slice(&mut self) -> &mut [u8] {
62 unsafe { std::slice::from_raw_parts_mut(self.mapping.start.as_ptr(), self.mapping.len) }
64 }
65
66 #[cfg(unix)]
70 #[must_use]
71 pub fn descriptor(&self) -> std::os::fd::BorrowedFd<'_> {
72 use std::os::fd::AsFd;
73 self.share.reader.as_fd()
74 }
75
76 #[cfg(windows)]
83 pub fn share_with(&self, process: &std::process::Child) -> io::Result<u64> {
84 platform::share_with(&self.share, process)
85 }
86}
87
88#[derive(Debug)]
90pub struct MappedRegion {
91 mapping: Mapping,
92}
93
94impl MappedRegion {
95 #[cfg(unix)]
101 pub fn open(descriptor: std::os::fd::OwnedFd, len: usize) -> io::Result<Self> {
102 let mapping = platform::open(&descriptor, len)?;
103 drop(descriptor);
104 Ok(Self { mapping })
105 }
106
107 #[cfg(windows)]
113 pub fn open(handle: u64, len: usize) -> io::Result<Self> {
114 Ok(Self {
115 mapping: platform::open(handle, len)?,
116 })
117 }
118
119 #[must_use]
121 pub const fn len(&self) -> usize {
122 self.mapping.len
123 }
124
125 #[must_use]
127 pub const fn is_empty(&self) -> bool {
128 self.mapping.len == 0
129 }
130
131 #[must_use]
133 pub const fn as_slice(&self) -> &[u8] {
134 unsafe { std::slice::from_raw_parts(self.mapping.start.as_ptr(), self.mapping.len) }
137 }
138}
139
140fn empty_mapping(len: usize) -> io::Error {
141 io::Error::new(
142 io::ErrorKind::InvalidInput,
143 format!("a mapping of {len} bytes"),
144 )
145}
146
147#[cfg(unix)]
148mod unix {
149 use std::io;
150 use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
151 use std::ptr::NonNull;
152
153 use super::Mapping;
154
155 pub(super) fn map(
156 descriptor: BorrowedFd<'_>,
157 len: usize,
158 writable: bool,
159 ) -> io::Result<Mapping> {
160 if len == 0 {
161 return Err(super::empty_mapping(len));
162 }
163 let protection = if writable {
164 libc::PROT_READ | libc::PROT_WRITE
165 } else {
166 libc::PROT_READ
167 };
168 let start = unsafe {
170 libc::mmap(
171 std::ptr::null_mut(),
172 len,
173 protection,
174 libc::MAP_SHARED,
175 descriptor.as_raw_fd(),
176 0,
177 )
178 };
179 if start == libc::MAP_FAILED {
180 return Err(io::Error::last_os_error());
181 }
182 let start = NonNull::new(start.cast::<u8>()).ok_or_else(io::Error::last_os_error)?;
183 Ok(Mapping { start, len })
184 }
185
186 pub(super) fn unmap(start: NonNull<u8>, len: usize) {
187 unsafe { libc::munmap(start.as_ptr().cast(), len) };
189 }
190
191 pub(super) fn set_len(descriptor: BorrowedFd<'_>, len: usize) -> io::Result<()> {
192 let len = libc::off_t::try_from(len).map_err(io::Error::other)?;
193 if unsafe { libc::ftruncate(descriptor.as_raw_fd(), len) } != 0 {
195 return Err(io::Error::last_os_error());
196 }
197 Ok(())
198 }
199
200 pub(super) fn open(descriptor: &OwnedFd, len: usize) -> io::Result<Mapping> {
201 let mut status: libc::stat = unsafe { std::mem::zeroed() };
203 if unsafe { libc::fstat(descriptor.as_raw_fd(), &raw mut status) } != 0 {
205 return Err(io::Error::last_os_error());
206 }
207 if u64::try_from(status.st_size).unwrap_or(0) < u64::try_from(len).unwrap_or(u64::MAX) {
208 return Err(io::Error::new(
209 io::ErrorKind::InvalidData,
210 format!(
211 "a region of {} bytes, not the {len} it was sent for",
212 status.st_size
213 ),
214 ));
215 }
216 map(descriptor.as_fd(), len, false)
217 }
218}
219
220#[cfg(any(target_os = "linux", target_os = "android"))]
221mod platform {
222 use std::io;
223 use std::os::fd::{AsFd, FromRawFd, OwnedFd};
224
225 pub(super) use super::unix::{open, unmap};
226 use super::{Mapping, unix};
227
228 #[derive(Debug)]
229 pub(super) struct Share {
230 pub(super) reader: OwnedFd,
231 }
232
233 const SEALS: libc::c_int = libc::F_SEAL_SHRINK | libc::F_SEAL_GROW | libc::F_SEAL_SEAL;
234
235 pub(super) fn create(len: usize) -> io::Result<(Mapping, Share)> {
236 let descriptor = unsafe {
238 libc::memfd_create(
239 c"alpha2-frames".as_ptr(),
240 libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
241 )
242 };
243 if descriptor < 0 {
244 return Err(io::Error::last_os_error());
245 }
246 let descriptor = unsafe { OwnedFd::from_raw_fd(descriptor) };
248 unix::set_len(descriptor.as_fd(), len)?;
249 let mapping = unix::map(descriptor.as_fd(), len, true)?;
250 seal(&descriptor)?;
251 Ok((mapping, Share { reader: descriptor }))
252 }
253
254 fn seal(descriptor: &OwnedFd) -> io::Result<()> {
255 use std::os::fd::AsRawFd;
256 let add = |seals: libc::c_int| {
257 if unsafe { libc::fcntl(descriptor.as_raw_fd(), libc::F_ADD_SEALS, seals) } == 0 {
259 Ok(())
260 } else {
261 Err(io::Error::last_os_error())
262 }
263 };
264 match add(SEALS | libc::F_SEAL_FUTURE_WRITE) {
266 Err(error) if error.raw_os_error() == Some(libc::EINVAL) => add(SEALS),
267 sealed => sealed,
268 }
269 }
270}
271
272#[cfg(target_vendor = "apple")]
273mod platform {
274 use std::ffi::CStr;
275 use std::io;
276 use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
277
278 pub(super) use super::unix::{open, unmap};
279 use super::{Mapping, unix};
280
281 #[derive(Debug)]
282 pub(super) struct Share {
283 pub(super) reader: OwnedFd,
284 }
285
286 const NAME_ATTEMPTS: usize = 8;
287
288 pub(super) fn create(len: usize) -> io::Result<(Mapping, Share)> {
289 let mut last = io::Error::from(io::ErrorKind::AlreadyExists);
290 for _ in 0..NAME_ATTEMPTS {
291 let mut random = [0_u8; 8];
292 unsafe { libc::arc4random_buf(random.as_mut_ptr().cast(), random.len()) };
294 let name = format!("/a2f-{:016x}\0", u64::from_ne_bytes(random));
295 let name = CStr::from_bytes_with_nul(name.as_bytes()).map_err(io::Error::other)?;
296 match create_named(name, len) {
297 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => last = error,
298 made => return made,
299 }
300 }
301 Err(last)
302 }
303
304 fn shm_open(name: &CStr, flags: libc::c_int) -> io::Result<OwnedFd> {
305 let mode = libc::c_uint::from(0o600_u16);
306 let descriptor = unsafe { libc::shm_open(name.as_ptr(), flags, mode) };
308 if descriptor < 0 {
309 return Err(io::Error::last_os_error());
310 }
311 let descriptor = unsafe { OwnedFd::from_raw_fd(descriptor) };
313 if unsafe { libc::fcntl(descriptor.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
315 return Err(io::Error::last_os_error());
316 }
317 Ok(descriptor)
318 }
319
320 pub(super) fn create_named(name: &CStr, len: usize) -> io::Result<(Mapping, Share)> {
321 let writer = shm_open(name, libc::O_CREAT | libc::O_EXCL | libc::O_RDWR)?;
322 let made = (|| {
323 let reader = shm_open(name, libc::O_RDONLY)?;
324 unix::set_len(writer.as_fd(), len)?;
325 let mapping = unix::map(writer.as_fd(), len, true)?;
326 Ok((mapping, Share { reader }))
327 })();
328 unsafe { libc::shm_unlink(name.as_ptr()) };
330 made
331 }
332}
333
334#[cfg(all(
335 unix,
336 not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))
337))]
338mod platform {
339 use std::io;
340 use std::os::fd::OwnedFd;
341
342 use super::Mapping;
343 pub(super) use super::unix::{open, unmap};
344
345 #[derive(Debug)]
346 pub(super) struct Share {
347 pub(super) reader: OwnedFd,
348 }
349
350 pub(super) fn create(_len: usize) -> io::Result<(Mapping, Share)> {
351 Err(io::Error::from(io::ErrorKind::Unsupported))
352 }
353}
354
355#[cfg(windows)]
356mod platform {
357 use std::io;
358 use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
359 use std::ptr::NonNull;
360
361 use windows_sys::Win32::Foundation::{
362 CloseHandle, DuplicateHandle, HANDLE, INVALID_HANDLE_VALUE,
363 };
364 use windows_sys::Win32::System::Memory::{
365 CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS,
366 MapViewOfFile, PAGE_READWRITE, UnmapViewOfFile,
367 };
368 use windows_sys::Win32::System::Threading::GetCurrentProcess;
369
370 use super::Mapping;
371
372 #[derive(Debug)]
373 pub(super) struct Share {
374 section: OwnedHandle,
375 }
376
377 fn view(section: HANDLE, access: u32, len: usize) -> io::Result<Mapping> {
378 if len == 0 {
379 return Err(super::empty_mapping(len));
380 }
381 let view = unsafe { MapViewOfFile(section, access, 0, 0, len) };
383 let start = NonNull::new(view.Value.cast::<u8>()).ok_or_else(io::Error::last_os_error)?;
384 Ok(Mapping { start, len })
385 }
386
387 pub(super) fn create(len: usize) -> io::Result<(Mapping, Share)> {
388 let size = u64::try_from(len).map_err(io::Error::other)?;
389 let high = u32::try_from(size >> 32).map_err(io::Error::other)?;
390 let low = u32::try_from(size & u64::from(u32::MAX)).map_err(io::Error::other)?;
391 let section = unsafe {
394 CreateFileMappingW(
395 INVALID_HANDLE_VALUE,
396 std::ptr::null(),
397 PAGE_READWRITE,
398 high,
399 low,
400 std::ptr::null(),
401 )
402 };
403 if section.is_null() {
404 return Err(io::Error::last_os_error());
405 }
406 let section = unsafe { OwnedHandle::from_raw_handle(section) };
408 let mapping = view(section.as_raw_handle(), FILE_MAP_WRITE, len)?;
409 Ok((mapping, Share { section }))
410 }
411
412 pub(super) fn share_with(share: &Share, process: &std::process::Child) -> io::Result<u64> {
413 let mut duplicated: HANDLE = std::ptr::null_mut();
414 let done = unsafe {
416 DuplicateHandle(
417 GetCurrentProcess(),
418 share.section.as_raw_handle(),
419 process.as_raw_handle(),
420 &raw mut duplicated,
421 FILE_MAP_READ,
422 0,
423 0,
424 )
425 };
426 if done == 0 {
427 return Err(io::Error::last_os_error());
428 }
429 u64::try_from(duplicated.addr()).map_err(io::Error::other)
430 }
431
432 pub(super) fn open(handle: u64, len: usize) -> io::Result<Mapping> {
433 let handle: HANDLE =
434 std::ptr::without_provenance_mut(usize::try_from(handle).map_err(io::Error::other)?);
435 let mapped = view(handle, FILE_MAP_READ, len);
436 unsafe { CloseHandle(handle) };
438 mapped
439 }
440
441 pub(super) fn unmap(start: NonNull<u8>, _len: usize) {
442 unsafe {
444 UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
445 Value: start.as_ptr().cast(),
446 })
447 };
448 }
449}
450
451#[cfg(test)]
452#[path = "shared_region_tests.rs"]
453mod tests;