1#![allow(unsafe_code)]
7
8use std::io;
9use std::os::fd::RawFd;
10use std::ptr;
11
12#[cfg(target_os = "linux")]
14pub const MAP_FIXED_NOREPLACE: libc::c_int = 0x100_000;
15
16#[must_use]
18pub fn fixed_map_flag() -> libc::c_int {
19 #[cfg(target_os = "linux")]
20 {
21 MAP_FIXED_NOREPLACE
22 }
23 #[cfg(not(target_os = "linux"))]
24 {
25 libc::MAP_FIXED
26 }
27}
28
29#[must_use]
31pub fn page_size() -> Option<usize> {
32 let raw = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
34 if raw <= 0 {
35 return None;
36 }
37 usize::try_from(raw).ok()
38}
39
40#[must_use]
42pub fn phys_pages() -> Option<u64> {
43 let raw = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
45 if raw <= 0 {
46 return None;
47 }
48 u64::try_from(raw).ok()
49}
50
51#[must_use]
53pub fn phys_mem_bytes() -> u64 {
54 match (phys_pages(), page_size()) {
55 (Some(pages), Some(page)) => {
56 let s = u64::try_from(page).unwrap_or(0);
57 pages.saturating_mul(s).max(64 * 1024 * 1024)
58 }
59 _ => 8 * 1024 * 1024 * 1024, }
61}
62
63pub fn close_fd(fd: RawFd) {
65 unsafe {
67 let _ = libc::close(fd);
68 }
69}
70
71#[must_use]
73pub fn dup_fd(fd: RawFd) -> Option<RawFd> {
74 let rc = unsafe { libc::dup(fd) };
76 if rc < 0 { None } else { Some(rc) }
77}
78
79pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
81 let rc = unsafe { libc::lseek(fd, offset, whence) };
83 if rc < 0 { None } else { Some(rc) }
84}
85
86pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
88 let rc = unsafe { libc::fcntl(fd, cmd) };
90 if rc < 0 { None } else { Some(rc) }
91}
92
93pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
95 let rc = unsafe { libc::fcntl(fd, cmd, arg) };
97 if rc < 0 { None } else { Some(rc) }
98}
99
100pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
103 let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
105 if rc < 0 { None } else { Some(rc) }
106}
107
108pub fn openat(
110 dirfd: RawFd,
111 path: &std::ffi::CStr,
112 flags: libc::c_int,
113 mode: libc::c_uint,
114) -> Option<RawFd> {
115 let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
117 if rc < 0 { None } else { Some(rc) }
118}
119
120pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
122 if data.is_empty() {
123 return Ok(0);
124 }
125 let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
127 if n < 0 {
128 return Err(io::Error::last_os_error());
129 }
130 usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
131}
132
133pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
135 if buf.is_empty() {
136 return Ok(0);
137 }
138 let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
140 if n < 0 {
141 return Err(io::Error::last_os_error());
142 }
143 usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
144}
145
146pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
148 let mut st: libc::stat = unsafe { std::mem::zeroed() };
150 let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
151 if rc == 0 { Some(st) } else { None }
152}
153
154pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
156 let rc = unsafe { libc::ftruncate(fd, length) };
158 if rc == 0 { Some(()) } else { None }
159}
160
161pub fn fsync_fd(fd: RawFd) -> Option<()> {
163 let rc = unsafe { libc::fsync(fd) };
165 if rc == 0 { Some(()) } else { None }
166}
167
168pub fn gettimeofday() -> Option<libc::timeval> {
170 let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
172 let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
173 if rc == 0 { Some(tv) } else { None }
174}
175
176pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
178 let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
180 let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
181 if rc == 0 { Some(ts) } else { None }
182}
183
184#[must_use]
189pub fn mmap(
190 fixed_addr: Option<u64>,
191 len: usize,
192 prot: libc::c_int,
193 flags: libc::c_int,
194 fd: RawFd,
195 offset: i64,
196) -> Option<*mut u8> {
197 if len == 0 {
198 return None;
199 }
200 let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
201 let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
204 if raw == libc::MAP_FAILED {
205 None
206 } else {
207 Some(raw.cast())
208 }
209}
210
211pub fn munmap(ptr: *mut u8, len: usize) -> bool {
213 if ptr.is_null() || len == 0 {
214 return true;
215 }
216 let rc = unsafe { libc::munmap(ptr.cast(), len) };
218 rc == 0
219}
220
221pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
223 if ptr.is_null() || len == 0 {
224 return true;
225 }
226 let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
228 rc == 0
229}
230
231pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
233 if ptr.is_null() || len == 0 {
234 return true;
235 }
236 let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
238 rc == 0
239}
240
241#[must_use]
243pub fn ptr_addr_u64(p: *mut u8) -> u64 {
244 u64::try_from(p.addr()).unwrap_or(0)
245}
246
247#[must_use]
249pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
250 let u = usize::try_from(addr).unwrap_or(0);
251 ptr::with_exposed_provenance_mut::<u8>(u).cast()
252}
253
254#[derive(Debug)]
258pub struct HostDir {
259 ptr: *mut libc::DIR,
260}
261
262unsafe impl Send for HostDir {}
265unsafe impl Sync for HostDir {}
267
268impl HostDir {
269 pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
271 let dup = unsafe { libc::dup(host_fd) };
273 if dup < 0 {
274 return Err(last_errno_i32());
275 }
276 let dir = unsafe { libc::fdopendir(dup) };
278 if dir.is_null() {
279 let err = last_errno_i32();
280 unsafe {
282 libc::close(dup);
283 }
284 return Err(err);
285 }
286 Ok(Self { ptr: dir })
287 }
288
289 pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
291 use std::ffi::CStr;
292 loop {
293 let ent = unsafe { libc::readdir(self.ptr) };
295 if ent.is_null() {
296 return None;
297 }
298 let d_type = unsafe { (*ent).d_type };
300 let name_ptr = unsafe { (*ent).d_name.as_ptr() };
301 let name = unsafe { CStr::from_ptr(name_ptr) };
302 let bytes = name.to_bytes().to_vec();
303 if bytes.is_empty() {
304 continue;
305 }
306 return Some((bytes, d_type));
307 }
308 }
309}
310
311impl Drop for HostDir {
312 fn drop(&mut self) {
313 if !self.ptr.is_null() {
314 unsafe {
316 let _ = libc::closedir(self.ptr);
317 }
318 self.ptr = ptr::null_mut();
319 }
320 }
321}
322
323fn last_errno_i32() -> i32 {
324 let raw = io::Error::last_os_error()
325 .raw_os_error()
326 .unwrap_or(1)
327 .unsigned_abs();
328 i32::try_from(raw).unwrap_or(1)
329}