Debian Codegraph @

third_party/rust/audioipc2/src/shm.rs

raw
1 // Copyright © 2017 Mozilla Foundation
2 //
3 // This program is made available under an ISC-style license. See the
4 // accompanying file LICENSE for details.
5
6 #![allow(clippy::missing_safety_doc)]
7
8 use crate::errors::*;
9 use crate::PlatformHandle;
10 use std::{convert::TryInto, ffi::c_void, slice};
11
12 #[cfg(unix)]
13 pub use unix::SharedMem;
14 #[cfg(windows)]
15 pub use windows::SharedMem;
16
17 #[derive(Copy, Clone)]
18 struct SharedMemView {
19 ptr: *mut c_void,
20 size: usize,
21 }
22
23 unsafe impl Send for SharedMemView {}
24
25 impl SharedMemView {
26 pub unsafe fn get_slice(&self, size: usize) -> Result<&[u8]> {
27 let map = slice::from_raw_parts(self.ptr as _, self.size);
28 if size <= self.size {
29 Ok(&map[..size])
30 } else {
31 bail!("mmap size");
32 }
33 }
34
35 pub unsafe fn get_mut_slice(&mut self, size: usize) -> Result<&mut [u8]> {
36 let map = slice::from_raw_parts_mut(self.ptr as _, self.size);
37 if size <= self.size {
38 Ok(&mut map[..size])
39 } else {
40 bail!("mmap size")
41 }
42 }
43 }
44
45 #[cfg(unix)]
46 mod unix {
47 use super::*;
48 use memmap2::{MmapMut, MmapOptions};
49 use std::fs::File;
50 use std::os::unix::io::{AsRawFd, FromRawFd};
51
52 #[cfg(target_os = "android")]
53 fn open_shm_file(_id: &str, size: usize) -> Result<File> {
54 unsafe {
55 let fd = ashmem::ASharedMemory_create(std::ptr::null(), size);
56 if fd >= 0 {
57 // Drop PROT_EXEC
58 let r = ashmem::ASharedMemory_setProt(fd, libc::PROT_READ | libc::PROT_WRITE);
59 assert_eq!(r, 0);
60 return Ok(File::from_raw_fd(fd.try_into().unwrap()));
61 }
62 Err(std::io::Error::last_os_error().into())
63 }
64 }
65
66 #[cfg(not(target_os = "android"))]
67 fn open_shm_file(id: &str, size: usize) -> Result<File> {
68 let file = open_shm_file_impl(id)?;
69 allocate_file(&file, size)?;
70 Ok(file)
71 }
72
73 #[cfg(not(target_os = "android"))]
74 fn open_shm_file_impl(id: &str) -> Result<File> {
75 use std::env::temp_dir;
76 use std::fs::{remove_file, OpenOptions};
77
78 let id_cstring = std::ffi::CString::new(id).unwrap();
79
80 #[cfg(target_os = "linux")]
81 {
82 unsafe {
83 let r = libc::syscall(libc::SYS_memfd_create, id_cstring.as_ptr(), 0);
84 if r >= 0 {
85 return Ok(File::from_raw_fd(r.try_into().unwrap()));
86 }
87 }
88
89 let mut path = std::path::PathBuf::from("/dev/shm");
90 path.push(id);
91
92 if let Ok(file) = OpenOptions::new()
93 .read(true)
94 .write(true)
95 .create_new(true)
96 .open(&path)
97 {
98 let _ = remove_file(&path);
99 return Ok(file);
100 }
101 }
102
103 unsafe {
104 let fd = libc::shm_open(
105 id_cstring.as_ptr(),
106 libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
107 0o600,
108 );
109 if fd >= 0 {
110 libc::shm_unlink(id_cstring.as_ptr());
111 return Ok(File::from_raw_fd(fd));
112 }
113 }
114
115 let mut path = temp_dir();
116 path.push(id);
117
118 let file = OpenOptions::new()
119 .read(true)
120 .write(true)
121 .create_new(true)
122 .open(&path)?;
123
124 let _ = remove_file(&path);
125 Ok(file)
126 }
127
128 #[cfg(not(target_os = "android"))]
129 fn handle_enospc(s: &str) -> Result<()> {
130 let err = std::io::Error::last_os_error();
131 let errno = err.raw_os_error().unwrap_or(0);
132 assert_ne!(errno, 0);
133 debug!("allocate_file: {} failed errno={}", s, errno);
134 if errno == libc::ENOSPC {
135 return Err(err.into());
136 }
137 Ok(())
138 }
139
140 #[cfg(not(target_os = "android"))]
141 fn allocate_file(file: &File, size: usize) -> Result<()> {
142 // First, set the file size. This may create a sparse file on
143 // many systems, which can fail with SIGBUS when accessed via a
144 // mapping and the lazy backing allocation fails due to low disk
145 // space. To avoid this, try to force the entire file to be
146 // preallocated before mapping using OS-specific approaches below.
147
148 file.set_len(size.try_into().unwrap())?;
149
150 let fd = file.as_raw_fd();
151 let size: libc::off_t = size.try_into().unwrap();
152
153 // Try Linux-specific fallocate.
154 #[cfg(target_os = "linux")]
155 {
156 if unsafe { libc::fallocate(fd, 0, 0, size) } == 0 {
157 return Ok(());
158 }
159 handle_enospc("fallocate()")?;
160 }
161
162 // Try macOS-specific fcntl.
163 #[cfg(target_os = "macos")]
164 {
165 let params = libc::fstore_t {
166 fst_flags: libc::F_ALLOCATEALL,
167 fst_posmode: libc::F_PEOFPOSMODE,
168 fst_offset: 0,
169 fst_length: size,
170 fst_bytesalloc: 0,
171 };
172 if unsafe { libc::fcntl(fd, libc::F_PREALLOCATE, &params) } == 0 {
173 return Ok(());
174 }
175 handle_enospc("fcntl(F_PREALLOCATE)")?;
176 }
177
178 // Fall back to portable version, where available.
179 #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly"))]
180 {
181 if unsafe { libc::posix_fallocate(fd, 0, size) } == 0 {
182 return Ok(());
183 }
184 handle_enospc("posix_fallocate()")?;
185 }
186
187 Ok(())
188 }
189
190 pub struct SharedMem {
191 file: File,
192 _mmap: MmapMut,
193 view: SharedMemView,
194 }
195
196 impl SharedMem {
197 pub fn new(id: &str, size: usize) -> Result<SharedMem> {
198 let file = open_shm_file(id, size)?;
199 let mut mmap = unsafe { MmapOptions::new().len(size).map_mut(&file)? };
200 assert_eq!(mmap.len(), size);
201 let view = SharedMemView {
202 ptr: mmap.as_mut_ptr() as _,
203 size,
204 };
205 Ok(SharedMem {
206 file,
207 _mmap: mmap,
208 view,
209 })
210 }
211
212 pub unsafe fn make_handle(&self) -> Result<PlatformHandle> {
213 PlatformHandle::duplicate(self.file.as_raw_fd()).map_err(|e| e.into())
214 }
215
216 pub unsafe fn from(handle: PlatformHandle, size: usize) -> Result<SharedMem> {
217 let file = File::from_raw_fd(handle.into_raw());
218 let mut mmap = MmapOptions::new().len(size).map_mut(&file)?;
219 assert_eq!(mmap.len(), size);
220 let view = SharedMemView {
221 ptr: mmap.as_mut_ptr() as _,
222 size,
223 };
224 Ok(SharedMem {
225 file,
226 _mmap: mmap,
227 view,
228 })
229 }
230
231 pub unsafe fn get_slice(&self, size: usize) -> Result<&[u8]> {
232 self.view.get_slice(size)
233 }
234
235 pub unsafe fn get_mut_slice(&mut self, size: usize) -> Result<&mut [u8]> {
236 self.view.get_mut_slice(size)
237 }
238
239 pub fn get_size(&self) -> usize {
240 self.view.size
241 }
242 }
243 }
244
245 #[cfg(windows)]
246 mod windows {
247 use std::ptr;
248
249 use windows_sys::Win32::{
250 Foundation::{CloseHandle, FALSE, HANDLE, INVALID_HANDLE_VALUE},
251 System::Memory::{
252 CreateFileMappingA, MapViewOfFile, UnmapViewOfFile, FILE_MAP_ALL_ACCESS,
253 MEMORY_MAPPED_VIEW_ADDRESS, PAGE_READWRITE,
254 },
255 };
256
257 use crate::valid_handle;
258
259 use super::*;
260
261 pub struct SharedMem {
262 handle: HANDLE,
263 view: SharedMemView,
264 }
265
266 unsafe impl Send for SharedMem {}
267
268 impl Drop for SharedMem {
269 fn drop(&mut self) {
270 unsafe {
271 let ok = UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
272 Value: self.view.ptr,
273 });
274 assert_ne!(ok, FALSE);
275 let ok = CloseHandle(self.handle);
276 assert_ne!(ok, FALSE);
277 }
278 }
279 }
280
281 impl SharedMem {
282 pub fn new(_id: &str, size: usize) -> Result<SharedMem> {
283 unsafe {
284 let handle = CreateFileMappingA(
285 INVALID_HANDLE_VALUE,
286 ptr::null_mut(),
287 PAGE_READWRITE,
288 (size as u64 >> 32).try_into().unwrap(),
289 (size as u64 & (u32::MAX as u64)).try_into().unwrap(),
290 ptr::null(),
291 );
292 if !valid_handle(handle as _) {
293 return Err(std::io::Error::last_os_error().into());
294 }
295
296 let ptr = MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, size);
297 if !valid_handle(ptr.Value) {
298 return Err(std::io::Error::last_os_error().into());
299 }
300
301 Ok(SharedMem {
302 handle,
303 view: SharedMemView {
304 ptr: ptr.Value,
305 size,
306 },
307 })
308 }
309 }
310
311 pub unsafe fn make_handle(&self) -> Result<PlatformHandle> {
312 PlatformHandle::duplicate(self.handle as _).map_err(|e| e.into())
313 }
314
315 pub unsafe fn from(handle: PlatformHandle, size: usize) -> Result<SharedMem> {
316 let handle = handle.into_raw();
317 let ptr = MapViewOfFile(handle as _, FILE_MAP_ALL_ACCESS, 0, 0, size);
318 if !valid_handle(ptr.Value) {
319 return Err(std::io::Error::last_os_error().into());
320 }
321 Ok(SharedMem {
322 handle: handle as _,
323 view: SharedMemView {
324 ptr: ptr.Value,
325 size,
326 },
327 })
328 }
329
330 pub unsafe fn get_slice(&self, size: usize) -> Result<&[u8]> {
331 self.view.get_slice(size)
332 }
333
334 pub unsafe fn get_mut_slice(&mut self, size: usize) -> Result<&mut [u8]> {
335 self.view.get_mut_slice(size)
336 }
337
338 pub fn get_size(&self) -> usize {
339 self.view.size
340 }
341 }
342 }