1#![allow(unsafe_code)]
9
10pub mod fat_thin;
11
12use std::fs::File;
13use std::io;
14use std::os::fd::{AsRawFd, RawFd};
15use std::path::Path;
16use std::ptr;
17
18#[cfg(target_os = "linux")]
20pub const MAP_FIXED_NOREPLACE: libc::c_int = 0x100_000;
21
22#[must_use]
24pub fn fixed_map_flag() -> libc::c_int {
25 #[cfg(target_os = "linux")]
26 {
27 MAP_FIXED_NOREPLACE
28 }
29 #[cfg(not(target_os = "linux"))]
30 {
31 libc::MAP_FIXED
32 }
33}
34
35#[must_use]
37pub fn page_size() -> Option<usize> {
38 let raw = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
40 if raw <= 0 {
41 return None;
42 }
43 usize::try_from(raw).ok()
44}
45
46#[must_use]
48pub fn phys_pages() -> Option<u64> {
49 let raw = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
51 if raw <= 0 {
52 return None;
53 }
54 u64::try_from(raw).ok()
55}
56
57#[must_use]
59pub fn phys_mem_bytes() -> u64 {
60 match (phys_pages(), page_size()) {
61 (Some(pages), Some(page)) => {
62 let s = u64::try_from(page).unwrap_or(0);
63 pages.saturating_mul(s).max(64 * 1024 * 1024)
64 }
65 _ => 8 * 1024 * 1024 * 1024, }
67}
68
69pub fn close_fd(fd: RawFd) {
71 unsafe {
73 let _ = libc::close(fd);
74 }
75}
76
77#[must_use]
79pub fn dup_fd(fd: RawFd) -> Option<RawFd> {
80 let rc = unsafe { libc::dup(fd) };
82 if rc < 0 { None } else { Some(rc) }
83}
84
85#[must_use]
87pub fn dup2_fd(old: RawFd, new: RawFd) -> Option<RawFd> {
88 let rc = unsafe { libc::dup2(old, new) };
90 if rc < 0 { None } else { Some(rc) }
91}
92
93pub fn fork_process() -> Result<i32, i32> {
95 let rc = unsafe { libc::fork() };
97 if rc < 0 {
98 Err(last_errno())
99 } else {
100 Ok(rc)
101 }
102}
103
104pub fn wait_pid(pid: i32, options: i32) -> Result<(i32, i32), i32> {
107 let mut status: libc::c_int = 0;
108 let rc = unsafe { libc::waitpid(pid, &raw mut status, options) };
110 if rc < 0 {
111 Err(last_errno())
112 } else {
113 Ok((rc, status))
114 }
115}
116
117pub unsafe fn execve_host(
124 path: &std::ffi::CStr,
125 argv: &[*const libc::c_char],
126 envp: &[*const libc::c_char],
127) -> i32 {
128 let rc = unsafe { libc::execve(path.as_ptr(), argv.as_ptr().cast(), envp.as_ptr().cast()) };
130 let _ = rc;
131 last_errno()
132}
133
134pub unsafe fn posix_spawn_host(
145 path: &std::ffi::CStr,
146 argv: &[*const libc::c_char],
147 envp: &[*const libc::c_char],
148) -> Result<i32, i32> {
149 let mut pid: libc::pid_t = 0;
150 let rc = unsafe {
153 libc::posix_spawn(
154 &raw mut pid,
155 path.as_ptr(),
156 core::ptr::null(),
157 core::ptr::null(),
158 argv.as_ptr().cast_mut().cast(),
159 envp.as_ptr().cast_mut().cast(),
160 )
161 };
162 if rc != 0 {
163 Err(rc)
164 } else {
165 Ok(pid)
166 }
167}
168
169fn last_errno() -> i32 {
170 io::Error::last_os_error()
171 .raw_os_error()
172 .unwrap_or(libc::EIO)
173}
174
175fn socklen_of(len: usize) -> Option<libc::socklen_t> {
176 libc::socklen_t::try_from(len).ok()
177}
178
179#[must_use]
191pub fn pipe_fds() -> Option<(RawFd, RawFd)> {
192 let mut fds = [0_i32; 2];
193 #[cfg(target_os = "linux")]
195 {
196 let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) };
198 if rc != 0 {
199 return None;
200 }
201 }
202 #[cfg(not(target_os = "linux"))]
203 {
204 let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
206 if rc != 0 {
207 return None;
208 }
209 for fd in fds {
210 set_nonblock(fd);
211 unsafe {
213 let _ = libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
214 }
215 }
216 }
217 match (fds.first().copied(), fds.get(1).copied()) {
218 (Some(r), Some(w)) => Some((r, w)),
219 _ => None,
220 }
221}
222
223#[must_use]
226pub fn poll_fd_readable(fd: RawFd, timeout_ms: i32) -> bool {
227 poll_fd(fd, libc::POLLIN, timeout_ms)
228}
229
230#[must_use]
232pub fn poll_fd_writable(fd: RawFd, timeout_ms: i32) -> bool {
233 poll_fd(fd, libc::POLLOUT, timeout_ms)
234}
235
236#[must_use]
238pub fn poll_fd_io(fd: RawFd, timeout_ms: i32) -> bool {
239 poll_fd(fd, libc::POLLIN | libc::POLLOUT, timeout_ms)
240}
241
242fn poll_fd(fd: RawFd, events: libc::c_short, timeout_ms: i32) -> bool {
243 let mut pfd = libc::pollfd {
244 fd,
245 events,
246 revents: 0,
247 };
248 loop {
249 let rc = unsafe { libc::poll(&raw mut pfd, 1, timeout_ms) };
251 if rc < 0 {
252 let err = io::Error::last_os_error()
253 .raw_os_error()
254 .unwrap_or(0);
255 if err == libc::EINTR {
256 continue;
257 }
258 return false;
259 }
260 if rc == 0 {
261 return false;
262 }
263 let interest = events | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL;
264 return pfd.revents & interest != 0;
265 }
266}
267
268fn set_nonblock(fd: RawFd) {
270 unsafe {
272 let fl = libc::fcntl(fd, libc::F_GETFL);
273 if fl >= 0 {
274 let _ = libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
275 }
276 }
277}
278
279pub fn clear_nonblock(fd: RawFd) {
281 unsafe {
283 let fl = libc::fcntl(fd, libc::F_GETFL);
284 if fl >= 0 {
285 let _ = libc::fcntl(fd, libc::F_SETFL, fl & !libc::O_NONBLOCK);
286 }
287 }
288}
289
290#[must_use]
292pub fn fd_is_fifo(fd: RawFd) -> bool {
293 unsafe {
295 let mut st: libc::stat = core::mem::zeroed();
296 if libc::fstat(fd, &raw mut st) != 0 {
297 return false;
298 }
299 (st.st_mode & libc::S_IFMT) == libc::S_IFIFO
300 }
301}
302
303#[must_use]
309pub fn socket(domain: libc::c_int, ty: libc::c_int, protocol: libc::c_int) -> Option<RawFd> {
310 let ty_plain = ty & 0xf;
313 let rc = unsafe { libc::socket(domain, ty_plain, protocol) };
314 if rc < 0 {
315 return None;
316 }
317 set_nonblock(rc);
318 unsafe {
320 let _ = libc::fcntl(rc, libc::F_SETFD, libc::FD_CLOEXEC);
321 }
322 Some(rc)
323}
324
325pub fn socketpair(
327 domain: libc::c_int,
328 ty: libc::c_int,
329 protocol: libc::c_int,
330) -> Option<(RawFd, RawFd)> {
331 let mut sv = [0_i32; 2];
332 let ty_plain = ty & 0xf;
333 let rc = unsafe { libc::socketpair(domain, ty_plain, protocol, sv.as_mut_ptr()) };
335 if rc != 0 {
336 return None;
337 }
338 set_nonblock(sv[0]);
339 set_nonblock(sv[1]);
340 unsafe {
342 let _ = libc::fcntl(sv[0], libc::F_SETFD, libc::FD_CLOEXEC);
343 let _ = libc::fcntl(sv[1], libc::F_SETFD, libc::FD_CLOEXEC);
344 }
345 Some((sv[0], sv[1]))
346}
347
348pub fn connect(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
350 let Some(len) = socklen_of(addr.len()) else {
351 return Err(libc::EINVAL);
352 };
353 let rc = unsafe { libc::connect(fd, addr.as_ptr().cast(), len) };
355 if rc == 0 { Ok(()) } else { Err(last_errno()) }
356}
357
358pub fn bind(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
360 let Some(len) = socklen_of(addr.len()) else {
361 return Err(libc::EINVAL);
362 };
363 let rc = unsafe { libc::bind(fd, addr.as_ptr().cast(), len) };
365 if rc == 0 { Ok(()) } else { Err(last_errno()) }
366}
367
368pub fn listen(fd: RawFd, backlog: libc::c_int) -> Result<(), i32> {
370 let rc = unsafe { libc::listen(fd, backlog) };
372 if rc == 0 { Ok(()) } else { Err(last_errno()) }
373}
374
375pub fn accept(fd: RawFd) -> Result<RawFd, i32> {
377 let rc = unsafe { libc::accept(fd, ptr::null_mut(), ptr::null_mut()) };
379 if rc < 0 {
380 Err(last_errno())
381 } else {
382 set_nonblock(rc);
383 Ok(rc)
384 }
385}
386
387pub fn accept_addr(fd: RawFd, addr_out: &mut [u8]) -> Result<(RawFd, usize), i32> {
391 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
392 let rc = unsafe {
394 libc::accept(
395 fd,
396 addr_out.as_mut_ptr().cast(),
397 ptr::addr_of_mut!(alen),
398 )
399 };
400 if rc < 0 {
401 return Err(last_errno());
402 }
403 set_nonblock(rc);
404 let n = usize::try_from(alen).unwrap_or(0).min(addr_out.len());
405 Ok((rc, n))
406}
407
408pub fn setsockopt(
410 fd: RawFd,
411 level: libc::c_int,
412 optname: libc::c_int,
413 value: &[u8],
414) -> Result<(), i32> {
415 let Some(len) = socklen_of(value.len()) else {
416 return Err(libc::EINVAL);
417 };
418 let rc = unsafe {
420 libc::setsockopt(
421 fd,
422 level,
423 optname,
424 value.as_ptr().cast(),
425 len,
426 )
427 };
428 if rc == 0 { Ok(()) } else { Err(last_errno()) }
429}
430
431pub fn getsockopt(
433 fd: RawFd,
434 level: libc::c_int,
435 optname: libc::c_int,
436 value: &mut [u8],
437) -> Result<usize, i32> {
438 let mut len = socklen_of(value.len()).unwrap_or(0);
439 let rc = unsafe {
441 libc::getsockopt(
442 fd,
443 level,
444 optname,
445 value.as_mut_ptr().cast(),
446 ptr::addr_of_mut!(len),
447 )
448 };
449 if rc == 0 {
450 Ok(usize::try_from(len).unwrap_or(0).min(value.len()))
451 } else {
452 Err(last_errno())
453 }
454}
455
456pub fn shutdown(fd: RawFd, how: libc::c_int) -> Result<(), i32> {
458 let rc = unsafe { libc::shutdown(fd, how) };
460 if rc == 0 { Ok(()) } else { Err(last_errno()) }
461}
462
463pub fn sendto(
465 fd: RawFd,
466 buf: &[u8],
467 flags: libc::c_int,
468 addr: Option<&[u8]>,
469) -> Result<usize, i32> {
470 let (ap, alen) = if let Some(a) = addr {
471 let Some(len) = socklen_of(a.len()) else {
472 return Err(libc::EINVAL);
473 };
474 (a.as_ptr().cast(), len)
475 } else {
476 (ptr::null(), 0)
477 };
478 let n = unsafe { libc::sendto(fd, buf.as_ptr().cast(), buf.len(), flags, ap, alen) };
480 if n < 0 {
481 Err(last_errno())
482 } else {
483 usize::try_from(n).map_err(|_| libc::EIO)
484 }
485}
486
487pub fn recvfrom(
491 fd: RawFd,
492 buf: &mut [u8],
493 flags: libc::c_int,
494 addr_out: Option<&mut [u8]>,
495) -> Result<(usize, usize), i32> {
496 let (n, peer_len) = if let Some(a) = addr_out {
497 let mut alen = socklen_of(a.len()).unwrap_or(0);
498 let n = unsafe {
500 libc::recvfrom(
501 fd,
502 buf.as_mut_ptr().cast(),
503 buf.len(),
504 flags,
505 a.as_mut_ptr().cast(),
506 ptr::addr_of_mut!(alen),
507 )
508 };
509 (n, usize::try_from(alen).unwrap_or(0).min(a.len()))
510 } else {
511 let n = unsafe {
513 libc::recvfrom(
514 fd,
515 buf.as_mut_ptr().cast(),
516 buf.len(),
517 flags,
518 ptr::null_mut(),
519 ptr::null_mut(),
520 )
521 };
522 (n, 0)
523 };
524 if n < 0 {
525 Err(last_errno())
526 } else {
527 let nr = usize::try_from(n).map_err(|_| libc::EIO)?;
528 Ok((nr, peer_len))
529 }
530}
531
532pub fn getsockname(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
534 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
535 let rc = unsafe {
537 libc::getsockname(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
538 };
539 if rc == 0 {
540 Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
541 } else {
542 Err(last_errno())
543 }
544}
545
546pub fn getpeername(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
548 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
549 let rc = unsafe {
551 libc::getpeername(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
552 };
553 if rc == 0 {
554 Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
555 } else {
556 Err(last_errno())
557 }
558}
559
560pub fn poll(fds: &mut [libc::pollfd], timeout: libc::c_int) -> Result<i32, i32> {
562 let nfds = libc::nfds_t::try_from(fds.len()).unwrap_or(0);
563 let rc = unsafe {
565 libc::poll(
566 if fds.is_empty() {
567 ptr::null_mut()
568 } else {
569 fds.as_mut_ptr()
570 },
571 nfds,
572 timeout,
573 )
574 };
575 if rc < 0 { Err(last_errno()) } else { Ok(rc) }
576}
577
578pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
580 let rc = unsafe { libc::lseek(fd, offset, whence) };
582 if rc < 0 { None } else { Some(rc) }
583}
584
585pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
587 let rc = unsafe { libc::fcntl(fd, cmd) };
589 if rc < 0 { None } else { Some(rc) }
590}
591
592pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
594 let rc = unsafe { libc::fcntl(fd, cmd, arg) };
596 if rc < 0 { None } else { Some(rc) }
597}
598
599pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
602 let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
604 if rc < 0 { None } else { Some(rc) }
605}
606
607pub fn open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
609 open_path(
610 path,
611 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
612 0,
613 )
614}
615
616pub fn openat(
618 dirfd: RawFd,
619 path: &std::ffi::CStr,
620 flags: libc::c_int,
621 mode: libc::c_uint,
622) -> Option<RawFd> {
623 let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
625 if rc < 0 { None } else { Some(rc) }
626}
627
628pub fn mkdirat(dirfd: RawFd, path: &std::ffi::CStr, mode: libc::mode_t) -> io::Result<()> {
630 let rc = unsafe { libc::mkdirat(dirfd, path.as_ptr(), mode) };
632 if rc == 0 {
633 return Ok(());
634 }
635 let err = io::Error::last_os_error();
636 if err.raw_os_error() == Some(libc::EEXIST) {
637 Ok(())
638 } else {
639 Err(err)
640 }
641}
642
643pub fn fstatat(dirfd: RawFd, path: &std::ffi::CStr, no_follow: bool) -> Option<libc::stat> {
645 let mut st: libc::stat = unsafe { std::mem::zeroed() };
646 let flags = if no_follow {
647 libc::AT_SYMLINK_NOFOLLOW
648 } else {
649 0
650 };
651 let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
653 if rc == 0 { Some(st) } else { None }
654}
655
656pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
658 let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
660 rc == 0
661}
662
663pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
665 if data.is_empty() {
666 return Ok(0);
667 }
668 let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
670 if n < 0 {
671 return Err(io::Error::last_os_error());
672 }
673 usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
674}
675
676pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
678 if buf.is_empty() {
679 return Ok(0);
680 }
681 let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
683 if n < 0 {
684 return Err(io::Error::last_os_error());
685 }
686 usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
687}
688
689pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
691 let mut st: libc::stat = unsafe { std::mem::zeroed() };
693 let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
694 if rc == 0 { Some(st) } else { None }
695}
696
697pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
699 let rc = unsafe { libc::ftruncate(fd, length) };
701 if rc == 0 { Some(()) } else { None }
702}
703
704pub fn fchmod_fd(fd: RawFd, mode: u32) -> Option<()> {
706 let mode = libc::mode_t::try_from(mode).unwrap_or(0);
707 let rc = unsafe { libc::fchmod(fd, mode) };
709 if rc == 0 { Some(()) } else { None }
710}
711
712pub fn fsync_fd(fd: RawFd) -> Option<()> {
714 let rc = unsafe { libc::fsync(fd) };
716 if rc == 0 { Some(()) } else { None }
717}
718
719pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
721 if buf.is_empty() {
722 return Ok(0);
723 }
724 let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
726 if n < 0 {
727 return Err(io::Error::last_os_error()
728 .raw_os_error()
729 .unwrap_or(libc::EIO));
730 }
731 usize::try_from(n).map_err(|_| libc::EIO)
732}
733
734pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
736 let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
738 if rc == 0 {
739 Ok(())
740 } else {
741 Err(io::Error::last_os_error()
742 .raw_os_error()
743 .unwrap_or(libc::EIO))
744 }
745}
746
747pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
749 let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
751 if rc == 0 {
752 Ok(())
753 } else {
754 Err(io::Error::last_os_error()
755 .raw_os_error()
756 .unwrap_or(libc::EIO))
757 }
758}
759
760pub fn gettimeofday() -> Option<libc::timeval> {
762 let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
764 let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
765 if rc == 0 { Some(tv) } else { None }
766}
767
768pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
770 let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
772 let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
773 if rc == 0 { Some(ts) } else { None }
774}
775
776pub struct MappedFile {
784 ptr: *mut u8,
785 len: usize,
786}
787
788impl std::fmt::Debug for MappedFile {
789 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
790 f.debug_struct("MappedFile")
791 .field("len", &self.len)
792 .finish_non_exhaustive()
793 }
794}
795
796unsafe impl Send for MappedFile {}
798
799impl MappedFile {
800 pub fn open(path: &Path) -> io::Result<Self> {
803 let file = File::open(path)?;
804 let len_u64 = file.metadata()?.len();
805 let len = usize::try_from(len_u64).map_err(|_| {
806 io::Error::new(io::ErrorKind::InvalidData, "file too large to map")
807 })?;
808 if len == 0 {
809 return Ok(Self {
810 ptr: ptr::null_mut(),
811 len: 0,
812 });
813 }
814 let fd = file.as_raw_fd();
815 let Some(base) = mmap(
818 None,
819 len,
820 libc::PROT_READ,
821 libc::MAP_PRIVATE,
822 fd,
823 0,
824 ) else {
825 return Err(io::Error::last_os_error());
826 };
827 Ok(Self { ptr: base, len })
829 }
830
831 #[must_use]
833 pub fn as_slice(&self) -> &[u8] {
834 if self.ptr.is_null() || self.len == 0 {
835 return &[];
836 }
837 unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
839 }
840
841 #[must_use]
843 pub const fn len(&self) -> usize {
844 self.len
845 }
846
847 #[must_use]
849 pub const fn is_empty(&self) -> bool {
850 self.len == 0
851 }
852}
853
854impl Drop for MappedFile {
855 fn drop(&mut self) {
856 if !self.ptr.is_null() && self.len > 0 {
857 let _ = munmap(self.ptr, self.len);
858 self.ptr = ptr::null_mut();
859 self.len = 0;
860 }
861 }
862}
863
864#[must_use]
869pub fn mmap(
870 fixed_addr: Option<u64>,
871 len: usize,
872 prot: libc::c_int,
873 flags: libc::c_int,
874 fd: RawFd,
875 offset: i64,
876) -> Option<*mut u8> {
877 if len == 0 {
878 return None;
879 }
880 let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
881 let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
884 if raw == libc::MAP_FAILED {
885 None
886 } else {
887 Some(raw.cast())
888 }
889}
890
891pub fn munmap(ptr: *mut u8, len: usize) -> bool {
893 if ptr.is_null() || len == 0 {
894 return true;
895 }
896 let rc = unsafe { libc::munmap(ptr.cast(), len) };
898 rc == 0
899}
900
901pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
903 if ptr.is_null() || len == 0 {
904 return true;
905 }
906 let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
908 rc == 0
909}
910
911pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
913 if ptr.is_null() || len == 0 {
914 return true;
915 }
916 let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
918 rc == 0
919}
920
921#[must_use]
923pub fn ptr_addr_u64(p: *mut u8) -> u64 {
924 u64::try_from(p.addr()).unwrap_or(0)
925}
926
927#[must_use]
929pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
930 let u = usize::try_from(addr).unwrap_or(0);
931 ptr::with_exposed_provenance_mut::<u8>(u).cast()
932}
933
934#[derive(Debug)]
938pub struct HostDir {
939 ptr: *mut libc::DIR,
940}
941
942unsafe impl Send for HostDir {}
945unsafe impl Sync for HostDir {}
947
948impl HostDir {
949 pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
951 let dup = unsafe { libc::dup(host_fd) };
953 if dup < 0 {
954 return Err(last_errno_i32());
955 }
956 let dir = unsafe { libc::fdopendir(dup) };
958 if dir.is_null() {
959 let err = last_errno_i32();
960 unsafe {
962 libc::close(dup);
963 }
964 return Err(err);
965 }
966 Ok(Self { ptr: dir })
967 }
968
969 pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
971 use std::ffi::CStr;
972 loop {
973 let ent = unsafe { libc::readdir(self.ptr) };
975 if ent.is_null() {
976 return None;
977 }
978 let d_type = unsafe { (*ent).d_type };
980 let name_ptr = unsafe { (*ent).d_name.as_ptr() };
981 let name = unsafe { CStr::from_ptr(name_ptr) };
982 let bytes = name.to_bytes().to_vec();
983 if bytes.is_empty() {
984 continue;
985 }
986 return Some((bytes, d_type));
987 }
988 }
989}
990
991impl Drop for HostDir {
992 fn drop(&mut self) {
993 if !self.ptr.is_null() {
994 unsafe {
996 let _ = libc::closedir(self.ptr);
997 }
998 self.ptr = ptr::null_mut();
999 }
1000 }
1001}
1002
1003fn last_errno_i32() -> i32 {
1004 let raw = io::Error::last_os_error()
1005 .raw_os_error()
1006 .unwrap_or(1)
1007 .unsigned_abs();
1008 i32::try_from(raw).unwrap_or(1)
1009}