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
254pub fn stat_path(path: &std::ffi::CStr) -> Option<libc::stat> {
258 let mut st: libc::stat = unsafe { std::mem::zeroed() };
260 let rc = unsafe { libc::stat(path.as_ptr(), std::ptr::addr_of_mut!(st)) };
261 if rc == 0 { Some(st) } else { None }
262}
263
264pub fn lstat_path(path: &std::ffi::CStr) -> Option<libc::stat> {
266 let mut st: libc::stat = unsafe { std::mem::zeroed() };
268 let rc = unsafe { libc::lstat(path.as_ptr(), std::ptr::addr_of_mut!(st)) };
269 if rc == 0 { Some(st) } else { None }
270}
271
272pub fn fstatat_path(
274 dirfd: RawFd,
275 path: &std::ffi::CStr,
276 flags: libc::c_int,
277) -> Option<libc::stat> {
278 let mut st: libc::stat = unsafe { std::mem::zeroed() };
280 let rc = unsafe {
281 libc::fstatat(
282 dirfd,
283 path.as_ptr(),
284 std::ptr::addr_of_mut!(st),
285 flags,
286 )
287 };
288 if rc == 0 { Some(st) } else { None }
289}
290
291pub fn access_path(path: &std::ffi::CStr, mode: libc::c_int) -> bool {
293 let rc = unsafe { libc::access(path.as_ptr(), mode) };
295 rc == 0
296}
297
298pub fn unlink_path(path: &std::ffi::CStr) -> Result<(), i32> {
300 let rc = unsafe { libc::unlink(path.as_ptr()) };
302 if rc == 0 {
303 Ok(())
304 } else {
305 Err(last_errno_i32())
306 }
307}
308
309pub fn mkdir_path(path: &std::ffi::CStr, mode: libc::mode_t) -> Result<(), i32> {
311 let rc = unsafe { libc::mkdir(path.as_ptr(), mode) };
313 if rc == 0 {
314 Ok(())
315 } else {
316 Err(last_errno_i32())
317 }
318}
319
320pub fn rmdir_path(path: &std::ffi::CStr) -> Result<(), i32> {
322 let rc = unsafe { libc::rmdir(path.as_ptr()) };
324 if rc == 0 {
325 Ok(())
326 } else {
327 Err(last_errno_i32())
328 }
329}
330
331pub fn rename_path(from: &std::ffi::CStr, to: &std::ffi::CStr) -> Result<(), i32> {
333 let rc = unsafe { libc::rename(from.as_ptr(), to.as_ptr()) };
335 if rc == 0 {
336 Ok(())
337 } else {
338 Err(last_errno_i32())
339 }
340}
341
342#[derive(Debug)]
346pub struct HostDir {
347 ptr: *mut libc::DIR,
348}
349
350unsafe impl Send for HostDir {}
352unsafe impl Sync for HostDir {}
354
355impl HostDir {
356 pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
358 let dup = unsafe { libc::dup(host_fd) };
360 if dup < 0 {
361 return Err(last_errno_i32());
362 }
363 let dir = unsafe { libc::fdopendir(dup) };
365 if dir.is_null() {
366 let err = last_errno_i32();
367 unsafe {
369 libc::close(dup);
370 }
371 return Err(err);
372 }
373 Ok(Self { ptr: dir })
374 }
375
376 pub fn read_next_into(&mut self, name_out: &mut [u8]) -> Option<u8> {
380 use std::ffi::CStr;
381 if name_out.is_empty() {
382 return None;
383 }
384 loop {
385 let ent = unsafe { libc::readdir(self.ptr) };
387 if ent.is_null() {
388 return None;
389 }
390 let d_type = unsafe { (*ent).d_type };
392 let name_ptr = unsafe { (*ent).d_name.as_ptr() };
393 let name = unsafe { CStr::from_ptr(name_ptr) };
394 let bytes = name.to_bytes();
395 if bytes.is_empty() {
396 continue;
397 }
398 let max = name_out.len().saturating_sub(1);
399 let n = bytes.len().min(max);
400 if let (Some(dst), Some(src)) = (name_out.get_mut(..n), bytes.get(..n)) {
401 dst.copy_from_slice(src);
402 }
403 if let Some(slot) = name_out.get_mut(n) {
404 *slot = 0;
405 }
406 if let Some(tail) = name_out.get_mut(n.saturating_add(1)..) {
408 tail.fill(0);
409 }
410 return Some(d_type);
411 }
412 }
413}
414
415impl Drop for HostDir {
416 fn drop(&mut self) {
417 if !self.ptr.is_null() {
418 unsafe {
420 let _ = libc::closedir(self.ptr);
421 }
422 self.ptr = ptr::null_mut();
423 }
424 }
425}
426
427fn last_errno_i32() -> i32 {
428 let raw = io::Error::last_os_error()
429 .raw_os_error()
430 .unwrap_or(1)
431 .unsigned_abs();
432 i32::try_from(raw).unwrap_or(1)
433}