1#![allow(unsafe_code)]
7
8use std::fs::File;
9use std::io;
10use std::os::fd::{AsRawFd, RawFd};
11use std::path::Path;
12use std::ptr;
13
14#[cfg(target_os = "linux")]
16pub const MAP_FIXED_NOREPLACE: libc::c_int = 0x100_000;
17
18#[must_use]
20pub fn fixed_map_flag() -> libc::c_int {
21 #[cfg(target_os = "linux")]
22 {
23 MAP_FIXED_NOREPLACE
24 }
25 #[cfg(not(target_os = "linux"))]
26 {
27 libc::MAP_FIXED
28 }
29}
30
31#[must_use]
33pub fn page_size() -> Option<usize> {
34 let raw = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
36 if raw <= 0 {
37 return None;
38 }
39 usize::try_from(raw).ok()
40}
41
42#[must_use]
44pub fn phys_pages() -> Option<u64> {
45 let raw = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
47 if raw <= 0 {
48 return None;
49 }
50 u64::try_from(raw).ok()
51}
52
53#[must_use]
55pub fn phys_mem_bytes() -> u64 {
56 match (phys_pages(), page_size()) {
57 (Some(pages), Some(page)) => {
58 let s = u64::try_from(page).unwrap_or(0);
59 pages.saturating_mul(s).max(64 * 1024 * 1024)
60 }
61 _ => 8 * 1024 * 1024 * 1024, }
63}
64
65pub fn close_fd(fd: RawFd) {
67 unsafe {
69 let _ = libc::close(fd);
70 }
71}
72
73#[must_use]
75pub fn dup_fd(fd: RawFd) -> Option<RawFd> {
76 let rc = unsafe { libc::dup(fd) };
78 if rc < 0 { None } else { Some(rc) }
79}
80
81#[must_use]
83pub fn dup2_fd(old: RawFd, new: RawFd) -> Option<RawFd> {
84 let rc = unsafe { libc::dup2(old, new) };
86 if rc < 0 { None } else { Some(rc) }
87}
88
89pub fn fork_process() -> Result<i32, i32> {
91 let rc = unsafe { libc::fork() };
93 if rc < 0 {
94 Err(last_errno())
95 } else {
96 Ok(rc)
97 }
98}
99
100pub fn wait_pid(pid: i32, options: i32) -> Result<(i32, i32), i32> {
103 let mut status: libc::c_int = 0;
104 let rc = unsafe { libc::waitpid(pid, &raw mut status, options) };
106 if rc < 0 {
107 Err(last_errno())
108 } else {
109 Ok((rc, status))
110 }
111}
112
113pub unsafe fn execve_host(
120 path: &std::ffi::CStr,
121 argv: &[*const libc::c_char],
122 envp: &[*const libc::c_char],
123) -> i32 {
124 let rc = unsafe { libc::execve(path.as_ptr(), argv.as_ptr().cast(), envp.as_ptr().cast()) };
126 let _ = rc;
127 last_errno()
128}
129
130pub unsafe fn posix_spawn_host(
141 path: &std::ffi::CStr,
142 argv: &[*const libc::c_char],
143 envp: &[*const libc::c_char],
144) -> Result<i32, i32> {
145 let mut pid: libc::pid_t = 0;
146 let rc = unsafe {
149 libc::posix_spawn(
150 &raw mut pid,
151 path.as_ptr(),
152 core::ptr::null(),
153 core::ptr::null(),
154 argv.as_ptr().cast_mut().cast(),
155 envp.as_ptr().cast_mut().cast(),
156 )
157 };
158 if rc != 0 {
159 Err(rc)
160 } else {
161 Ok(pid)
162 }
163}
164
165fn last_errno() -> i32 {
166 io::Error::last_os_error()
167 .raw_os_error()
168 .unwrap_or(libc::EIO)
169}
170
171fn socklen_of(len: usize) -> Option<libc::socklen_t> {
172 libc::socklen_t::try_from(len).ok()
173}
174
175#[must_use]
187pub fn pipe_fds() -> Option<(RawFd, RawFd)> {
188 let mut fds = [0_i32; 2];
189 #[cfg(target_os = "linux")]
191 {
192 let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) };
194 if rc != 0 {
195 return None;
196 }
197 }
198 #[cfg(not(target_os = "linux"))]
199 {
200 let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
202 if rc != 0 {
203 return None;
204 }
205 for fd in fds {
206 set_nonblock(fd);
207 unsafe {
209 let _ = libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
210 }
211 }
212 }
213 match (fds.first().copied(), fds.get(1).copied()) {
214 (Some(r), Some(w)) => Some((r, w)),
215 _ => None,
216 }
217}
218
219#[must_use]
222pub fn poll_fd_readable(fd: RawFd, timeout_ms: i32) -> bool {
223 poll_fd(fd, libc::POLLIN, timeout_ms)
224}
225
226#[must_use]
228pub fn poll_fd_writable(fd: RawFd, timeout_ms: i32) -> bool {
229 poll_fd(fd, libc::POLLOUT, timeout_ms)
230}
231
232#[must_use]
234pub fn poll_fd_io(fd: RawFd, timeout_ms: i32) -> bool {
235 poll_fd(fd, libc::POLLIN | libc::POLLOUT, timeout_ms)
236}
237
238fn poll_fd(fd: RawFd, events: libc::c_short, timeout_ms: i32) -> bool {
239 let mut pfd = libc::pollfd {
240 fd,
241 events,
242 revents: 0,
243 };
244 loop {
245 let rc = unsafe { libc::poll(&raw mut pfd, 1, timeout_ms) };
247 if rc < 0 {
248 let err = io::Error::last_os_error()
249 .raw_os_error()
250 .unwrap_or(0);
251 if err == libc::EINTR {
252 continue;
253 }
254 return false;
255 }
256 if rc == 0 {
257 return false;
258 }
259 let interest = events | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL;
260 return pfd.revents & interest != 0;
261 }
262}
263
264fn set_nonblock(fd: RawFd) {
266 unsafe {
268 let fl = libc::fcntl(fd, libc::F_GETFL);
269 if fl >= 0 {
270 let _ = libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
271 }
272 }
273}
274
275pub fn clear_nonblock(fd: RawFd) {
277 unsafe {
279 let fl = libc::fcntl(fd, libc::F_GETFL);
280 if fl >= 0 {
281 let _ = libc::fcntl(fd, libc::F_SETFL, fl & !libc::O_NONBLOCK);
282 }
283 }
284}
285
286#[must_use]
288pub fn fd_is_fifo(fd: RawFd) -> bool {
289 unsafe {
291 let mut st: libc::stat = core::mem::zeroed();
292 if libc::fstat(fd, &raw mut st) != 0 {
293 return false;
294 }
295 (st.st_mode & libc::S_IFMT) == libc::S_IFIFO
296 }
297}
298
299#[must_use]
305pub fn socket(domain: libc::c_int, ty: libc::c_int, protocol: libc::c_int) -> Option<RawFd> {
306 let ty_plain = ty & 0xf;
309 let rc = unsafe { libc::socket(domain, ty_plain, protocol) };
310 if rc < 0 {
311 return None;
312 }
313 set_nonblock(rc);
314 unsafe {
316 let _ = libc::fcntl(rc, libc::F_SETFD, libc::FD_CLOEXEC);
317 }
318 Some(rc)
319}
320
321pub fn socketpair(
323 domain: libc::c_int,
324 ty: libc::c_int,
325 protocol: libc::c_int,
326) -> Option<(RawFd, RawFd)> {
327 let mut sv = [0_i32; 2];
328 let ty_plain = ty & 0xf;
329 let rc = unsafe { libc::socketpair(domain, ty_plain, protocol, sv.as_mut_ptr()) };
331 if rc != 0 {
332 return None;
333 }
334 set_nonblock(sv[0]);
335 set_nonblock(sv[1]);
336 unsafe {
338 let _ = libc::fcntl(sv[0], libc::F_SETFD, libc::FD_CLOEXEC);
339 let _ = libc::fcntl(sv[1], libc::F_SETFD, libc::FD_CLOEXEC);
340 }
341 Some((sv[0], sv[1]))
342}
343
344pub fn connect(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
346 let Some(len) = socklen_of(addr.len()) else {
347 return Err(libc::EINVAL);
348 };
349 let rc = unsafe { libc::connect(fd, addr.as_ptr().cast(), len) };
351 if rc == 0 { Ok(()) } else { Err(last_errno()) }
352}
353
354pub fn bind(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
356 let Some(len) = socklen_of(addr.len()) else {
357 return Err(libc::EINVAL);
358 };
359 let rc = unsafe { libc::bind(fd, addr.as_ptr().cast(), len) };
361 if rc == 0 { Ok(()) } else { Err(last_errno()) }
362}
363
364pub fn listen(fd: RawFd, backlog: libc::c_int) -> Result<(), i32> {
366 let rc = unsafe { libc::listen(fd, backlog) };
368 if rc == 0 { Ok(()) } else { Err(last_errno()) }
369}
370
371pub fn accept(fd: RawFd) -> Result<RawFd, i32> {
373 let rc = unsafe { libc::accept(fd, ptr::null_mut(), ptr::null_mut()) };
375 if rc < 0 {
376 Err(last_errno())
377 } else {
378 set_nonblock(rc);
379 Ok(rc)
380 }
381}
382
383pub fn accept_addr(fd: RawFd, addr_out: &mut [u8]) -> Result<(RawFd, usize), i32> {
387 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
388 let rc = unsafe {
390 libc::accept(
391 fd,
392 addr_out.as_mut_ptr().cast(),
393 ptr::addr_of_mut!(alen),
394 )
395 };
396 if rc < 0 {
397 return Err(last_errno());
398 }
399 set_nonblock(rc);
400 let n = usize::try_from(alen).unwrap_or(0).min(addr_out.len());
401 Ok((rc, n))
402}
403
404pub fn setsockopt(
406 fd: RawFd,
407 level: libc::c_int,
408 optname: libc::c_int,
409 value: &[u8],
410) -> Result<(), i32> {
411 let Some(len) = socklen_of(value.len()) else {
412 return Err(libc::EINVAL);
413 };
414 let rc = unsafe {
416 libc::setsockopt(
417 fd,
418 level,
419 optname,
420 value.as_ptr().cast(),
421 len,
422 )
423 };
424 if rc == 0 { Ok(()) } else { Err(last_errno()) }
425}
426
427pub fn getsockopt(
429 fd: RawFd,
430 level: libc::c_int,
431 optname: libc::c_int,
432 value: &mut [u8],
433) -> Result<usize, i32> {
434 let mut len = socklen_of(value.len()).unwrap_or(0);
435 let rc = unsafe {
437 libc::getsockopt(
438 fd,
439 level,
440 optname,
441 value.as_mut_ptr().cast(),
442 ptr::addr_of_mut!(len),
443 )
444 };
445 if rc == 0 {
446 Ok(usize::try_from(len).unwrap_or(0).min(value.len()))
447 } else {
448 Err(last_errno())
449 }
450}
451
452pub fn shutdown(fd: RawFd, how: libc::c_int) -> Result<(), i32> {
454 let rc = unsafe { libc::shutdown(fd, how) };
456 if rc == 0 { Ok(()) } else { Err(last_errno()) }
457}
458
459pub fn sendto(
461 fd: RawFd,
462 buf: &[u8],
463 flags: libc::c_int,
464 addr: Option<&[u8]>,
465) -> Result<usize, i32> {
466 let (ap, alen) = if let Some(a) = addr {
467 let Some(len) = socklen_of(a.len()) else {
468 return Err(libc::EINVAL);
469 };
470 (a.as_ptr().cast(), len)
471 } else {
472 (ptr::null(), 0)
473 };
474 let n = unsafe { libc::sendto(fd, buf.as_ptr().cast(), buf.len(), flags, ap, alen) };
476 if n < 0 {
477 Err(last_errno())
478 } else {
479 usize::try_from(n).map_err(|_| libc::EIO)
480 }
481}
482
483pub fn recvfrom(
487 fd: RawFd,
488 buf: &mut [u8],
489 flags: libc::c_int,
490 addr_out: Option<&mut [u8]>,
491) -> Result<(usize, usize), i32> {
492 let (n, peer_len) = if let Some(a) = addr_out {
493 let mut alen = socklen_of(a.len()).unwrap_or(0);
494 let n = unsafe {
496 libc::recvfrom(
497 fd,
498 buf.as_mut_ptr().cast(),
499 buf.len(),
500 flags,
501 a.as_mut_ptr().cast(),
502 ptr::addr_of_mut!(alen),
503 )
504 };
505 (n, usize::try_from(alen).unwrap_or(0).min(a.len()))
506 } else {
507 let n = unsafe {
509 libc::recvfrom(
510 fd,
511 buf.as_mut_ptr().cast(),
512 buf.len(),
513 flags,
514 ptr::null_mut(),
515 ptr::null_mut(),
516 )
517 };
518 (n, 0)
519 };
520 if n < 0 {
521 Err(last_errno())
522 } else {
523 let nr = usize::try_from(n).map_err(|_| libc::EIO)?;
524 Ok((nr, peer_len))
525 }
526}
527
528pub fn getsockname(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
530 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
531 let rc = unsafe {
533 libc::getsockname(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
534 };
535 if rc == 0 {
536 Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
537 } else {
538 Err(last_errno())
539 }
540}
541
542pub fn getpeername(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
544 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
545 let rc = unsafe {
547 libc::getpeername(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
548 };
549 if rc == 0 {
550 Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
551 } else {
552 Err(last_errno())
553 }
554}
555
556pub fn poll(fds: &mut [libc::pollfd], timeout: libc::c_int) -> Result<i32, i32> {
558 let nfds = libc::nfds_t::try_from(fds.len()).unwrap_or(0);
559 let rc = unsafe {
561 libc::poll(
562 if fds.is_empty() {
563 ptr::null_mut()
564 } else {
565 fds.as_mut_ptr()
566 },
567 nfds,
568 timeout,
569 )
570 };
571 if rc < 0 { Err(last_errno()) } else { Ok(rc) }
572}
573
574pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
576 let rc = unsafe { libc::lseek(fd, offset, whence) };
578 if rc < 0 { None } else { Some(rc) }
579}
580
581pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
583 let rc = unsafe { libc::fcntl(fd, cmd) };
585 if rc < 0 { None } else { Some(rc) }
586}
587
588pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
590 let rc = unsafe { libc::fcntl(fd, cmd, arg) };
592 if rc < 0 { None } else { Some(rc) }
593}
594
595pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
598 let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
600 if rc < 0 { None } else { Some(rc) }
601}
602
603pub fn open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
605 open_path(
606 path,
607 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
608 0,
609 )
610}
611
612pub fn openat(
614 dirfd: RawFd,
615 path: &std::ffi::CStr,
616 flags: libc::c_int,
617 mode: libc::c_uint,
618) -> Option<RawFd> {
619 let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
621 if rc < 0 { None } else { Some(rc) }
622}
623
624pub fn mkdirat(dirfd: RawFd, path: &std::ffi::CStr, mode: libc::mode_t) -> io::Result<()> {
626 let rc = unsafe { libc::mkdirat(dirfd, path.as_ptr(), mode) };
628 if rc == 0 {
629 return Ok(());
630 }
631 let err = io::Error::last_os_error();
632 if err.raw_os_error() == Some(libc::EEXIST) {
633 Ok(())
634 } else {
635 Err(err)
636 }
637}
638
639pub fn fstatat(dirfd: RawFd, path: &std::ffi::CStr, no_follow: bool) -> Option<libc::stat> {
641 let mut st: libc::stat = unsafe { std::mem::zeroed() };
642 let flags = if no_follow {
643 libc::AT_SYMLINK_NOFOLLOW
644 } else {
645 0
646 };
647 let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
649 if rc == 0 { Some(st) } else { None }
650}
651
652pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
654 let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
656 rc == 0
657}
658
659pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
661 if data.is_empty() {
662 return Ok(0);
663 }
664 let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
666 if n < 0 {
667 return Err(io::Error::last_os_error());
668 }
669 usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
670}
671
672pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
674 if buf.is_empty() {
675 return Ok(0);
676 }
677 let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
679 if n < 0 {
680 return Err(io::Error::last_os_error());
681 }
682 usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
683}
684
685pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
687 let mut st: libc::stat = unsafe { std::mem::zeroed() };
689 let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
690 if rc == 0 { Some(st) } else { None }
691}
692
693pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
695 let rc = unsafe { libc::ftruncate(fd, length) };
697 if rc == 0 { Some(()) } else { None }
698}
699
700pub fn fchmod_fd(fd: RawFd, mode: u32) -> Option<()> {
702 let mode = libc::mode_t::try_from(mode).unwrap_or(0);
703 let rc = unsafe { libc::fchmod(fd, mode) };
705 if rc == 0 { Some(()) } else { None }
706}
707
708pub fn fsync_fd(fd: RawFd) -> Option<()> {
710 let rc = unsafe { libc::fsync(fd) };
712 if rc == 0 { Some(()) } else { None }
713}
714
715pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
717 if buf.is_empty() {
718 return Ok(0);
719 }
720 let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
722 if n < 0 {
723 return Err(io::Error::last_os_error()
724 .raw_os_error()
725 .unwrap_or(libc::EIO));
726 }
727 usize::try_from(n).map_err(|_| libc::EIO)
728}
729
730pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
732 let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
734 if rc == 0 {
735 Ok(())
736 } else {
737 Err(io::Error::last_os_error()
738 .raw_os_error()
739 .unwrap_or(libc::EIO))
740 }
741}
742
743pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
745 let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
747 if rc == 0 {
748 Ok(())
749 } else {
750 Err(io::Error::last_os_error()
751 .raw_os_error()
752 .unwrap_or(libc::EIO))
753 }
754}
755
756pub fn gettimeofday() -> Option<libc::timeval> {
758 let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
760 let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
761 if rc == 0 { Some(tv) } else { None }
762}
763
764pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
766 let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
768 let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
769 if rc == 0 { Some(ts) } else { None }
770}
771
772pub struct MappedFile {
780 ptr: *mut u8,
781 len: usize,
782}
783
784impl std::fmt::Debug for MappedFile {
785 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
786 f.debug_struct("MappedFile")
787 .field("len", &self.len)
788 .finish_non_exhaustive()
789 }
790}
791
792unsafe impl Send for MappedFile {}
794
795impl MappedFile {
796 pub fn open(path: &Path) -> io::Result<Self> {
799 let file = File::open(path)?;
800 let len_u64 = file.metadata()?.len();
801 let len = usize::try_from(len_u64).map_err(|_| {
802 io::Error::new(io::ErrorKind::InvalidData, "file too large to map")
803 })?;
804 if len == 0 {
805 return Ok(Self {
806 ptr: ptr::null_mut(),
807 len: 0,
808 });
809 }
810 let fd = file.as_raw_fd();
811 let Some(base) = mmap(
814 None,
815 len,
816 libc::PROT_READ,
817 libc::MAP_PRIVATE,
818 fd,
819 0,
820 ) else {
821 return Err(io::Error::last_os_error());
822 };
823 Ok(Self { ptr: base, len })
825 }
826
827 #[must_use]
829 pub fn as_slice(&self) -> &[u8] {
830 if self.ptr.is_null() || self.len == 0 {
831 return &[];
832 }
833 unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
835 }
836
837 #[must_use]
839 pub const fn len(&self) -> usize {
840 self.len
841 }
842
843 #[must_use]
845 pub const fn is_empty(&self) -> bool {
846 self.len == 0
847 }
848}
849
850impl Drop for MappedFile {
851 fn drop(&mut self) {
852 if !self.ptr.is_null() && self.len > 0 {
853 let _ = munmap(self.ptr, self.len);
854 self.ptr = ptr::null_mut();
855 self.len = 0;
856 }
857 }
858}
859
860#[must_use]
865pub fn mmap(
866 fixed_addr: Option<u64>,
867 len: usize,
868 prot: libc::c_int,
869 flags: libc::c_int,
870 fd: RawFd,
871 offset: i64,
872) -> Option<*mut u8> {
873 if len == 0 {
874 return None;
875 }
876 let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
877 let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
880 if raw == libc::MAP_FAILED {
881 None
882 } else {
883 Some(raw.cast())
884 }
885}
886
887pub fn munmap(ptr: *mut u8, len: usize) -> bool {
889 if ptr.is_null() || len == 0 {
890 return true;
891 }
892 let rc = unsafe { libc::munmap(ptr.cast(), len) };
894 rc == 0
895}
896
897pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
899 if ptr.is_null() || len == 0 {
900 return true;
901 }
902 let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
904 rc == 0
905}
906
907pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
909 if ptr.is_null() || len == 0 {
910 return true;
911 }
912 let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
914 rc == 0
915}
916
917#[must_use]
919pub fn ptr_addr_u64(p: *mut u8) -> u64 {
920 u64::try_from(p.addr()).unwrap_or(0)
921}
922
923#[must_use]
925pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
926 let u = usize::try_from(addr).unwrap_or(0);
927 ptr::with_exposed_provenance_mut::<u8>(u).cast()
928}
929
930#[derive(Debug)]
934pub struct HostDir {
935 ptr: *mut libc::DIR,
936}
937
938unsafe impl Send for HostDir {}
941unsafe impl Sync for HostDir {}
943
944impl HostDir {
945 pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
947 let dup = unsafe { libc::dup(host_fd) };
949 if dup < 0 {
950 return Err(last_errno_i32());
951 }
952 let dir = unsafe { libc::fdopendir(dup) };
954 if dir.is_null() {
955 let err = last_errno_i32();
956 unsafe {
958 libc::close(dup);
959 }
960 return Err(err);
961 }
962 Ok(Self { ptr: dir })
963 }
964
965 pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
967 use std::ffi::CStr;
968 loop {
969 let ent = unsafe { libc::readdir(self.ptr) };
971 if ent.is_null() {
972 return None;
973 }
974 let d_type = unsafe { (*ent).d_type };
976 let name_ptr = unsafe { (*ent).d_name.as_ptr() };
977 let name = unsafe { CStr::from_ptr(name_ptr) };
978 let bytes = name.to_bytes().to_vec();
979 if bytes.is_empty() {
980 continue;
981 }
982 return Some((bytes, d_type));
983 }
984 }
985}
986
987impl Drop for HostDir {
988 fn drop(&mut self) {
989 if !self.ptr.is_null() {
990 unsafe {
992 let _ = libc::closedir(self.ptr);
993 }
994 self.ptr = ptr::null_mut();
995 }
996 }
997}
998
999fn last_errno_i32() -> i32 {
1000 let raw = io::Error::last_os_error()
1001 .raw_os_error()
1002 .unwrap_or(1)
1003 .unsigned_abs();
1004 i32::try_from(raw).unwrap_or(1)
1005}