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
79#[must_use]
81pub fn dup2_fd(old: RawFd, new: RawFd) -> Option<RawFd> {
82 let rc = unsafe { libc::dup2(old, new) };
84 if rc < 0 { None } else { Some(rc) }
85}
86
87pub fn fork_process() -> Result<i32, i32> {
89 let rc = unsafe { libc::fork() };
91 if rc < 0 {
92 Err(last_errno())
93 } else {
94 Ok(rc)
95 }
96}
97
98pub fn wait_pid(pid: i32, options: i32) -> Result<(i32, i32), i32> {
101 let mut status: libc::c_int = 0;
102 let rc = unsafe { libc::waitpid(pid, &raw mut status, options) };
104 if rc < 0 {
105 Err(last_errno())
106 } else {
107 Ok((rc, status))
108 }
109}
110
111pub unsafe fn execve_host(
118 path: &std::ffi::CStr,
119 argv: &[*const libc::c_char],
120 envp: &[*const libc::c_char],
121) -> i32 {
122 let rc = unsafe { libc::execve(path.as_ptr(), argv.as_ptr().cast(), envp.as_ptr().cast()) };
124 let _ = rc;
125 last_errno()
126}
127
128fn last_errno() -> i32 {
129 io::Error::last_os_error()
130 .raw_os_error()
131 .unwrap_or(libc::EIO)
132}
133
134fn socklen_of(len: usize) -> Option<libc::socklen_t> {
135 libc::socklen_t::try_from(len).ok()
136}
137
138#[must_use]
150pub fn pipe_fds() -> Option<(RawFd, RawFd)> {
151 let mut fds = [0_i32; 2];
152 #[cfg(target_os = "linux")]
154 {
155 let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) };
157 if rc != 0 {
158 return None;
159 }
160 }
161 #[cfg(not(target_os = "linux"))]
162 {
163 let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
165 if rc != 0 {
166 return None;
167 }
168 for fd in fds {
169 set_nonblock(fd);
170 unsafe {
172 let _ = libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
173 }
174 }
175 }
176 match (fds.first().copied(), fds.get(1).copied()) {
177 (Some(r), Some(w)) => Some((r, w)),
178 _ => None,
179 }
180}
181
182#[must_use]
185pub fn poll_fd_readable(fd: RawFd, timeout_ms: i32) -> bool {
186 poll_fd(fd, libc::POLLIN, timeout_ms)
187}
188
189#[must_use]
191pub fn poll_fd_writable(fd: RawFd, timeout_ms: i32) -> bool {
192 poll_fd(fd, libc::POLLOUT, timeout_ms)
193}
194
195#[must_use]
197pub fn poll_fd_io(fd: RawFd, timeout_ms: i32) -> bool {
198 poll_fd(fd, libc::POLLIN | libc::POLLOUT, timeout_ms)
199}
200
201fn poll_fd(fd: RawFd, events: libc::c_short, timeout_ms: i32) -> bool {
202 let mut pfd = libc::pollfd {
203 fd,
204 events,
205 revents: 0,
206 };
207 loop {
208 let rc = unsafe { libc::poll(&raw mut pfd, 1, timeout_ms) };
210 if rc < 0 {
211 let err = io::Error::last_os_error()
212 .raw_os_error()
213 .unwrap_or(0);
214 if err == libc::EINTR {
215 continue;
216 }
217 return false;
218 }
219 if rc == 0 {
220 return false;
221 }
222 let interest = events | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL;
223 return pfd.revents & interest != 0;
224 }
225}
226
227fn set_nonblock(fd: RawFd) {
229 unsafe {
231 let fl = libc::fcntl(fd, libc::F_GETFL);
232 if fl >= 0 {
233 let _ = libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
234 }
235 }
236}
237
238pub fn clear_nonblock(fd: RawFd) {
240 unsafe {
242 let fl = libc::fcntl(fd, libc::F_GETFL);
243 if fl >= 0 {
244 let _ = libc::fcntl(fd, libc::F_SETFL, fl & !libc::O_NONBLOCK);
245 }
246 }
247}
248
249#[must_use]
251pub fn fd_is_fifo(fd: RawFd) -> bool {
252 unsafe {
254 let mut st: libc::stat = core::mem::zeroed();
255 if libc::fstat(fd, &raw mut st) != 0 {
256 return false;
257 }
258 (st.st_mode & libc::S_IFMT) == libc::S_IFIFO
259 }
260}
261
262#[must_use]
268pub fn socket(domain: libc::c_int, ty: libc::c_int, protocol: libc::c_int) -> Option<RawFd> {
269 let ty_plain = ty & 0xf;
272 let rc = unsafe { libc::socket(domain, ty_plain, protocol) };
273 if rc < 0 {
274 return None;
275 }
276 set_nonblock(rc);
277 unsafe {
279 let _ = libc::fcntl(rc, libc::F_SETFD, libc::FD_CLOEXEC);
280 }
281 Some(rc)
282}
283
284pub fn socketpair(
286 domain: libc::c_int,
287 ty: libc::c_int,
288 protocol: libc::c_int,
289) -> Option<(RawFd, RawFd)> {
290 let mut sv = [0_i32; 2];
291 let ty_plain = ty & 0xf;
292 let rc = unsafe { libc::socketpair(domain, ty_plain, protocol, sv.as_mut_ptr()) };
294 if rc != 0 {
295 return None;
296 }
297 set_nonblock(sv[0]);
298 set_nonblock(sv[1]);
299 unsafe {
301 let _ = libc::fcntl(sv[0], libc::F_SETFD, libc::FD_CLOEXEC);
302 let _ = libc::fcntl(sv[1], libc::F_SETFD, libc::FD_CLOEXEC);
303 }
304 Some((sv[0], sv[1]))
305}
306
307pub fn connect(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
309 let Some(len) = socklen_of(addr.len()) else {
310 return Err(libc::EINVAL);
311 };
312 let rc = unsafe { libc::connect(fd, addr.as_ptr().cast(), len) };
314 if rc == 0 { Ok(()) } else { Err(last_errno()) }
315}
316
317pub fn bind(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
319 let Some(len) = socklen_of(addr.len()) else {
320 return Err(libc::EINVAL);
321 };
322 let rc = unsafe { libc::bind(fd, addr.as_ptr().cast(), len) };
324 if rc == 0 { Ok(()) } else { Err(last_errno()) }
325}
326
327pub fn listen(fd: RawFd, backlog: libc::c_int) -> Result<(), i32> {
329 let rc = unsafe { libc::listen(fd, backlog) };
331 if rc == 0 { Ok(()) } else { Err(last_errno()) }
332}
333
334pub fn accept(fd: RawFd) -> Result<RawFd, i32> {
336 let rc = unsafe { libc::accept(fd, ptr::null_mut(), ptr::null_mut()) };
338 if rc < 0 {
339 Err(last_errno())
340 } else {
341 set_nonblock(rc);
342 Ok(rc)
343 }
344}
345
346pub fn accept_addr(fd: RawFd, addr_out: &mut [u8]) -> Result<(RawFd, usize), i32> {
350 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
351 let rc = unsafe {
353 libc::accept(
354 fd,
355 addr_out.as_mut_ptr().cast(),
356 ptr::addr_of_mut!(alen),
357 )
358 };
359 if rc < 0 {
360 return Err(last_errno());
361 }
362 set_nonblock(rc);
363 let n = usize::try_from(alen).unwrap_or(0).min(addr_out.len());
364 Ok((rc, n))
365}
366
367pub fn setsockopt(
369 fd: RawFd,
370 level: libc::c_int,
371 optname: libc::c_int,
372 value: &[u8],
373) -> Result<(), i32> {
374 let Some(len) = socklen_of(value.len()) else {
375 return Err(libc::EINVAL);
376 };
377 let rc = unsafe {
379 libc::setsockopt(
380 fd,
381 level,
382 optname,
383 value.as_ptr().cast(),
384 len,
385 )
386 };
387 if rc == 0 { Ok(()) } else { Err(last_errno()) }
388}
389
390pub fn getsockopt(
392 fd: RawFd,
393 level: libc::c_int,
394 optname: libc::c_int,
395 value: &mut [u8],
396) -> Result<usize, i32> {
397 let mut len = socklen_of(value.len()).unwrap_or(0);
398 let rc = unsafe {
400 libc::getsockopt(
401 fd,
402 level,
403 optname,
404 value.as_mut_ptr().cast(),
405 ptr::addr_of_mut!(len),
406 )
407 };
408 if rc == 0 {
409 Ok(usize::try_from(len).unwrap_or(0).min(value.len()))
410 } else {
411 Err(last_errno())
412 }
413}
414
415pub fn shutdown(fd: RawFd, how: libc::c_int) -> Result<(), i32> {
417 let rc = unsafe { libc::shutdown(fd, how) };
419 if rc == 0 { Ok(()) } else { Err(last_errno()) }
420}
421
422pub fn sendto(
424 fd: RawFd,
425 buf: &[u8],
426 flags: libc::c_int,
427 addr: Option<&[u8]>,
428) -> Result<usize, i32> {
429 let (ap, alen) = if let Some(a) = addr {
430 let Some(len) = socklen_of(a.len()) else {
431 return Err(libc::EINVAL);
432 };
433 (a.as_ptr().cast(), len)
434 } else {
435 (ptr::null(), 0)
436 };
437 let n = unsafe { libc::sendto(fd, buf.as_ptr().cast(), buf.len(), flags, ap, alen) };
439 if n < 0 {
440 Err(last_errno())
441 } else {
442 usize::try_from(n).map_err(|_| libc::EIO)
443 }
444}
445
446pub fn recvfrom(
450 fd: RawFd,
451 buf: &mut [u8],
452 flags: libc::c_int,
453 addr_out: Option<&mut [u8]>,
454) -> Result<(usize, usize), i32> {
455 let (n, peer_len) = if let Some(a) = addr_out {
456 let mut alen = socklen_of(a.len()).unwrap_or(0);
457 let n = unsafe {
459 libc::recvfrom(
460 fd,
461 buf.as_mut_ptr().cast(),
462 buf.len(),
463 flags,
464 a.as_mut_ptr().cast(),
465 ptr::addr_of_mut!(alen),
466 )
467 };
468 (n, usize::try_from(alen).unwrap_or(0).min(a.len()))
469 } else {
470 let n = unsafe {
472 libc::recvfrom(
473 fd,
474 buf.as_mut_ptr().cast(),
475 buf.len(),
476 flags,
477 ptr::null_mut(),
478 ptr::null_mut(),
479 )
480 };
481 (n, 0)
482 };
483 if n < 0 {
484 Err(last_errno())
485 } else {
486 let nr = usize::try_from(n).map_err(|_| libc::EIO)?;
487 Ok((nr, peer_len))
488 }
489}
490
491pub fn getsockname(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
493 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
494 let rc = unsafe {
496 libc::getsockname(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
497 };
498 if rc == 0 {
499 Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
500 } else {
501 Err(last_errno())
502 }
503}
504
505pub fn getpeername(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
507 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
508 let rc = unsafe {
510 libc::getpeername(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
511 };
512 if rc == 0 {
513 Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
514 } else {
515 Err(last_errno())
516 }
517}
518
519pub fn poll(fds: &mut [libc::pollfd], timeout: libc::c_int) -> Result<i32, i32> {
521 let nfds = libc::nfds_t::try_from(fds.len()).unwrap_or(0);
522 let rc = unsafe {
524 libc::poll(
525 if fds.is_empty() {
526 ptr::null_mut()
527 } else {
528 fds.as_mut_ptr()
529 },
530 nfds,
531 timeout,
532 )
533 };
534 if rc < 0 { Err(last_errno()) } else { Ok(rc) }
535}
536
537pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
539 let rc = unsafe { libc::lseek(fd, offset, whence) };
541 if rc < 0 { None } else { Some(rc) }
542}
543
544pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
546 let rc = unsafe { libc::fcntl(fd, cmd) };
548 if rc < 0 { None } else { Some(rc) }
549}
550
551pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
553 let rc = unsafe { libc::fcntl(fd, cmd, arg) };
555 if rc < 0 { None } else { Some(rc) }
556}
557
558pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
561 let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
563 if rc < 0 { None } else { Some(rc) }
564}
565
566pub fn open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
568 open_path(
569 path,
570 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
571 0,
572 )
573}
574
575pub fn openat(
577 dirfd: RawFd,
578 path: &std::ffi::CStr,
579 flags: libc::c_int,
580 mode: libc::c_uint,
581) -> Option<RawFd> {
582 let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
584 if rc < 0 { None } else { Some(rc) }
585}
586
587pub fn mkdirat(dirfd: RawFd, path: &std::ffi::CStr, mode: libc::mode_t) -> io::Result<()> {
589 let rc = unsafe { libc::mkdirat(dirfd, path.as_ptr(), mode) };
591 if rc == 0 {
592 return Ok(());
593 }
594 let err = io::Error::last_os_error();
595 if err.raw_os_error() == Some(libc::EEXIST) {
596 Ok(())
597 } else {
598 Err(err)
599 }
600}
601
602pub fn fstatat(dirfd: RawFd, path: &std::ffi::CStr, no_follow: bool) -> Option<libc::stat> {
604 let mut st: libc::stat = unsafe { std::mem::zeroed() };
605 let flags = if no_follow {
606 libc::AT_SYMLINK_NOFOLLOW
607 } else {
608 0
609 };
610 let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
612 if rc == 0 { Some(st) } else { None }
613}
614
615pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
617 let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
619 rc == 0
620}
621
622pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
624 if data.is_empty() {
625 return Ok(0);
626 }
627 let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
629 if n < 0 {
630 return Err(io::Error::last_os_error());
631 }
632 usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
633}
634
635pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
637 if buf.is_empty() {
638 return Ok(0);
639 }
640 let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
642 if n < 0 {
643 return Err(io::Error::last_os_error());
644 }
645 usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
646}
647
648pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
650 let mut st: libc::stat = unsafe { std::mem::zeroed() };
652 let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
653 if rc == 0 { Some(st) } else { None }
654}
655
656pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
658 let rc = unsafe { libc::ftruncate(fd, length) };
660 if rc == 0 { Some(()) } else { None }
661}
662
663pub fn fsync_fd(fd: RawFd) -> Option<()> {
665 let rc = unsafe { libc::fsync(fd) };
667 if rc == 0 { Some(()) } else { None }
668}
669
670pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
672 if buf.is_empty() {
673 return Ok(0);
674 }
675 let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
677 if n < 0 {
678 return Err(io::Error::last_os_error()
679 .raw_os_error()
680 .unwrap_or(libc::EIO));
681 }
682 usize::try_from(n).map_err(|_| libc::EIO)
683}
684
685pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
687 let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
689 if rc == 0 {
690 Ok(())
691 } else {
692 Err(io::Error::last_os_error()
693 .raw_os_error()
694 .unwrap_or(libc::EIO))
695 }
696}
697
698pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
700 let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
702 if rc == 0 {
703 Ok(())
704 } else {
705 Err(io::Error::last_os_error()
706 .raw_os_error()
707 .unwrap_or(libc::EIO))
708 }
709}
710
711pub fn gettimeofday() -> Option<libc::timeval> {
713 let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
715 let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
716 if rc == 0 { Some(tv) } else { None }
717}
718
719pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
721 let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
723 let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
724 if rc == 0 { Some(ts) } else { None }
725}
726
727#[must_use]
732pub fn mmap(
733 fixed_addr: Option<u64>,
734 len: usize,
735 prot: libc::c_int,
736 flags: libc::c_int,
737 fd: RawFd,
738 offset: i64,
739) -> Option<*mut u8> {
740 if len == 0 {
741 return None;
742 }
743 let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
744 let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
747 if raw == libc::MAP_FAILED {
748 None
749 } else {
750 Some(raw.cast())
751 }
752}
753
754pub fn munmap(ptr: *mut u8, len: usize) -> bool {
756 if ptr.is_null() || len == 0 {
757 return true;
758 }
759 let rc = unsafe { libc::munmap(ptr.cast(), len) };
761 rc == 0
762}
763
764pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
766 if ptr.is_null() || len == 0 {
767 return true;
768 }
769 let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
771 rc == 0
772}
773
774pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
776 if ptr.is_null() || len == 0 {
777 return true;
778 }
779 let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
781 rc == 0
782}
783
784#[must_use]
786pub fn ptr_addr_u64(p: *mut u8) -> u64 {
787 u64::try_from(p.addr()).unwrap_or(0)
788}
789
790#[must_use]
792pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
793 let u = usize::try_from(addr).unwrap_or(0);
794 ptr::with_exposed_provenance_mut::<u8>(u).cast()
795}
796
797#[derive(Debug)]
801pub struct HostDir {
802 ptr: *mut libc::DIR,
803}
804
805unsafe impl Send for HostDir {}
808unsafe impl Sync for HostDir {}
810
811impl HostDir {
812 pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
814 let dup = unsafe { libc::dup(host_fd) };
816 if dup < 0 {
817 return Err(last_errno_i32());
818 }
819 let dir = unsafe { libc::fdopendir(dup) };
821 if dir.is_null() {
822 let err = last_errno_i32();
823 unsafe {
825 libc::close(dup);
826 }
827 return Err(err);
828 }
829 Ok(Self { ptr: dir })
830 }
831
832 pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
834 use std::ffi::CStr;
835 loop {
836 let ent = unsafe { libc::readdir(self.ptr) };
838 if ent.is_null() {
839 return None;
840 }
841 let d_type = unsafe { (*ent).d_type };
843 let name_ptr = unsafe { (*ent).d_name.as_ptr() };
844 let name = unsafe { CStr::from_ptr(name_ptr) };
845 let bytes = name.to_bytes().to_vec();
846 if bytes.is_empty() {
847 continue;
848 }
849 return Some((bytes, d_type));
850 }
851 }
852}
853
854impl Drop for HostDir {
855 fn drop(&mut self) {
856 if !self.ptr.is_null() {
857 unsafe {
859 let _ = libc::closedir(self.ptr);
860 }
861 self.ptr = ptr::null_mut();
862 }
863 }
864}
865
866fn last_errno_i32() -> i32 {
867 let raw = io::Error::last_os_error()
868 .raw_os_error()
869 .unwrap_or(1)
870 .unsigned_abs();
871 i32::try_from(raw).unwrap_or(1)
872}