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]
145pub fn pipe_fds() -> Option<(RawFd, RawFd)> {
146 let mut fds = [0_i32; 2];
147 let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
149 if rc != 0 {
150 return None;
151 }
152 match (fds.first().copied(), fds.get(1).copied()) {
153 (Some(r), Some(w)) => Some((r, w)),
154 _ => None,
155 }
156}
157
158fn set_nonblock(fd: RawFd) {
160 unsafe {
162 let fl = libc::fcntl(fd, libc::F_GETFL);
163 if fl >= 0 {
164 let _ = libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
165 }
166 }
167}
168
169#[must_use]
175pub fn socket(domain: libc::c_int, ty: libc::c_int, protocol: libc::c_int) -> Option<RawFd> {
176 let ty_plain = ty & 0xf;
179 let rc = unsafe { libc::socket(domain, ty_plain, protocol) };
180 if rc < 0 {
181 return None;
182 }
183 set_nonblock(rc);
184 unsafe {
186 let _ = libc::fcntl(rc, libc::F_SETFD, libc::FD_CLOEXEC);
187 }
188 Some(rc)
189}
190
191pub fn socketpair(
193 domain: libc::c_int,
194 ty: libc::c_int,
195 protocol: libc::c_int,
196) -> Option<(RawFd, RawFd)> {
197 let mut sv = [0_i32; 2];
198 let ty_plain = ty & 0xf;
199 let rc = unsafe { libc::socketpair(domain, ty_plain, protocol, sv.as_mut_ptr()) };
201 if rc != 0 {
202 return None;
203 }
204 set_nonblock(sv[0]);
205 set_nonblock(sv[1]);
206 unsafe {
208 let _ = libc::fcntl(sv[0], libc::F_SETFD, libc::FD_CLOEXEC);
209 let _ = libc::fcntl(sv[1], libc::F_SETFD, libc::FD_CLOEXEC);
210 }
211 Some((sv[0], sv[1]))
212}
213
214pub fn connect(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
216 let Some(len) = socklen_of(addr.len()) else {
217 return Err(libc::EINVAL);
218 };
219 let rc = unsafe { libc::connect(fd, addr.as_ptr().cast(), len) };
221 if rc == 0 { Ok(()) } else { Err(last_errno()) }
222}
223
224pub fn bind(fd: RawFd, addr: &[u8]) -> Result<(), i32> {
226 let Some(len) = socklen_of(addr.len()) else {
227 return Err(libc::EINVAL);
228 };
229 let rc = unsafe { libc::bind(fd, addr.as_ptr().cast(), len) };
231 if rc == 0 { Ok(()) } else { Err(last_errno()) }
232}
233
234pub fn listen(fd: RawFd, backlog: libc::c_int) -> Result<(), i32> {
236 let rc = unsafe { libc::listen(fd, backlog) };
238 if rc == 0 { Ok(()) } else { Err(last_errno()) }
239}
240
241pub fn accept(fd: RawFd) -> Result<RawFd, i32> {
243 let rc = unsafe { libc::accept(fd, ptr::null_mut(), ptr::null_mut()) };
245 if rc < 0 {
246 Err(last_errno())
247 } else {
248 set_nonblock(rc);
249 Ok(rc)
250 }
251}
252
253pub fn accept_addr(fd: RawFd, addr_out: &mut [u8]) -> Result<(RawFd, usize), i32> {
257 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
258 let rc = unsafe {
260 libc::accept(
261 fd,
262 addr_out.as_mut_ptr().cast(),
263 ptr::addr_of_mut!(alen),
264 )
265 };
266 if rc < 0 {
267 return Err(last_errno());
268 }
269 set_nonblock(rc);
270 let n = usize::try_from(alen).unwrap_or(0).min(addr_out.len());
271 Ok((rc, n))
272}
273
274pub fn setsockopt(
276 fd: RawFd,
277 level: libc::c_int,
278 optname: libc::c_int,
279 value: &[u8],
280) -> Result<(), i32> {
281 let Some(len) = socklen_of(value.len()) else {
282 return Err(libc::EINVAL);
283 };
284 let rc = unsafe {
286 libc::setsockopt(
287 fd,
288 level,
289 optname,
290 value.as_ptr().cast(),
291 len,
292 )
293 };
294 if rc == 0 { Ok(()) } else { Err(last_errno()) }
295}
296
297pub fn getsockopt(
299 fd: RawFd,
300 level: libc::c_int,
301 optname: libc::c_int,
302 value: &mut [u8],
303) -> Result<usize, i32> {
304 let mut len = socklen_of(value.len()).unwrap_or(0);
305 let rc = unsafe {
307 libc::getsockopt(
308 fd,
309 level,
310 optname,
311 value.as_mut_ptr().cast(),
312 ptr::addr_of_mut!(len),
313 )
314 };
315 if rc == 0 {
316 Ok(usize::try_from(len).unwrap_or(0).min(value.len()))
317 } else {
318 Err(last_errno())
319 }
320}
321
322pub fn shutdown(fd: RawFd, how: libc::c_int) -> Result<(), i32> {
324 let rc = unsafe { libc::shutdown(fd, how) };
326 if rc == 0 { Ok(()) } else { Err(last_errno()) }
327}
328
329pub fn sendto(
331 fd: RawFd,
332 buf: &[u8],
333 flags: libc::c_int,
334 addr: Option<&[u8]>,
335) -> Result<usize, i32> {
336 let (ap, alen) = if let Some(a) = addr {
337 let Some(len) = socklen_of(a.len()) else {
338 return Err(libc::EINVAL);
339 };
340 (a.as_ptr().cast(), len)
341 } else {
342 (ptr::null(), 0)
343 };
344 let n = unsafe { libc::sendto(fd, buf.as_ptr().cast(), buf.len(), flags, ap, alen) };
346 if n < 0 {
347 Err(last_errno())
348 } else {
349 usize::try_from(n).map_err(|_| libc::EIO)
350 }
351}
352
353pub fn recvfrom(
357 fd: RawFd,
358 buf: &mut [u8],
359 flags: libc::c_int,
360 addr_out: Option<&mut [u8]>,
361) -> Result<(usize, usize), i32> {
362 let (n, peer_len) = if let Some(a) = addr_out {
363 let mut alen = socklen_of(a.len()).unwrap_or(0);
364 let n = unsafe {
366 libc::recvfrom(
367 fd,
368 buf.as_mut_ptr().cast(),
369 buf.len(),
370 flags,
371 a.as_mut_ptr().cast(),
372 ptr::addr_of_mut!(alen),
373 )
374 };
375 (n, usize::try_from(alen).unwrap_or(0).min(a.len()))
376 } else {
377 let n = unsafe {
379 libc::recvfrom(
380 fd,
381 buf.as_mut_ptr().cast(),
382 buf.len(),
383 flags,
384 ptr::null_mut(),
385 ptr::null_mut(),
386 )
387 };
388 (n, 0)
389 };
390 if n < 0 {
391 Err(last_errno())
392 } else {
393 let nr = usize::try_from(n).map_err(|_| libc::EIO)?;
394 Ok((nr, peer_len))
395 }
396}
397
398pub fn getsockname(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
400 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
401 let rc = unsafe {
403 libc::getsockname(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
404 };
405 if rc == 0 {
406 Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
407 } else {
408 Err(last_errno())
409 }
410}
411
412pub fn getpeername(fd: RawFd, addr_out: &mut [u8]) -> Result<usize, i32> {
414 let mut alen = socklen_of(addr_out.len()).unwrap_or(0);
415 let rc = unsafe {
417 libc::getpeername(fd, addr_out.as_mut_ptr().cast(), ptr::addr_of_mut!(alen))
418 };
419 if rc == 0 {
420 Ok(usize::try_from(alen).unwrap_or(0).min(addr_out.len()))
421 } else {
422 Err(last_errno())
423 }
424}
425
426pub fn poll(fds: &mut [libc::pollfd], timeout: libc::c_int) -> Result<i32, i32> {
428 let nfds = libc::nfds_t::try_from(fds.len()).unwrap_or(0);
429 let rc = unsafe {
431 libc::poll(
432 if fds.is_empty() {
433 ptr::null_mut()
434 } else {
435 fds.as_mut_ptr()
436 },
437 nfds,
438 timeout,
439 )
440 };
441 if rc < 0 { Err(last_errno()) } else { Ok(rc) }
442}
443
444pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
446 let rc = unsafe { libc::lseek(fd, offset, whence) };
448 if rc < 0 { None } else { Some(rc) }
449}
450
451pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
453 let rc = unsafe { libc::fcntl(fd, cmd) };
455 if rc < 0 { None } else { Some(rc) }
456}
457
458pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
460 let rc = unsafe { libc::fcntl(fd, cmd, arg) };
462 if rc < 0 { None } else { Some(rc) }
463}
464
465pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
468 let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
470 if rc < 0 { None } else { Some(rc) }
471}
472
473pub fn open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
475 open_path(
476 path,
477 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
478 0,
479 )
480}
481
482pub fn openat(
484 dirfd: RawFd,
485 path: &std::ffi::CStr,
486 flags: libc::c_int,
487 mode: libc::c_uint,
488) -> Option<RawFd> {
489 let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
491 if rc < 0 { None } else { Some(rc) }
492}
493
494pub fn mkdirat(dirfd: RawFd, path: &std::ffi::CStr, mode: libc::mode_t) -> io::Result<()> {
496 let rc = unsafe { libc::mkdirat(dirfd, path.as_ptr(), mode) };
498 if rc == 0 {
499 return Ok(());
500 }
501 let err = io::Error::last_os_error();
502 if err.raw_os_error() == Some(libc::EEXIST) {
503 Ok(())
504 } else {
505 Err(err)
506 }
507}
508
509pub fn fstatat(dirfd: RawFd, path: &std::ffi::CStr, no_follow: bool) -> Option<libc::stat> {
511 let mut st: libc::stat = unsafe { std::mem::zeroed() };
512 let flags = if no_follow {
513 libc::AT_SYMLINK_NOFOLLOW
514 } else {
515 0
516 };
517 let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
519 if rc == 0 { Some(st) } else { None }
520}
521
522pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
524 let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
526 rc == 0
527}
528
529pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
531 if data.is_empty() {
532 return Ok(0);
533 }
534 let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
536 if n < 0 {
537 return Err(io::Error::last_os_error());
538 }
539 usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
540}
541
542pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
544 if buf.is_empty() {
545 return Ok(0);
546 }
547 let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
549 if n < 0 {
550 return Err(io::Error::last_os_error());
551 }
552 usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
553}
554
555pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
557 let mut st: libc::stat = unsafe { std::mem::zeroed() };
559 let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
560 if rc == 0 { Some(st) } else { None }
561}
562
563pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
565 let rc = unsafe { libc::ftruncate(fd, length) };
567 if rc == 0 { Some(()) } else { None }
568}
569
570pub fn fsync_fd(fd: RawFd) -> Option<()> {
572 let rc = unsafe { libc::fsync(fd) };
574 if rc == 0 { Some(()) } else { None }
575}
576
577pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
579 if buf.is_empty() {
580 return Ok(0);
581 }
582 let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
584 if n < 0 {
585 return Err(io::Error::last_os_error()
586 .raw_os_error()
587 .unwrap_or(libc::EIO));
588 }
589 usize::try_from(n).map_err(|_| libc::EIO)
590}
591
592pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
594 let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
596 if rc == 0 {
597 Ok(())
598 } else {
599 Err(io::Error::last_os_error()
600 .raw_os_error()
601 .unwrap_or(libc::EIO))
602 }
603}
604
605pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
607 let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
609 if rc == 0 {
610 Ok(())
611 } else {
612 Err(io::Error::last_os_error()
613 .raw_os_error()
614 .unwrap_or(libc::EIO))
615 }
616}
617
618pub fn gettimeofday() -> Option<libc::timeval> {
620 let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
622 let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
623 if rc == 0 { Some(tv) } else { None }
624}
625
626pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
628 let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
630 let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
631 if rc == 0 { Some(ts) } else { None }
632}
633
634#[must_use]
639pub fn mmap(
640 fixed_addr: Option<u64>,
641 len: usize,
642 prot: libc::c_int,
643 flags: libc::c_int,
644 fd: RawFd,
645 offset: i64,
646) -> Option<*mut u8> {
647 if len == 0 {
648 return None;
649 }
650 let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
651 let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
654 if raw == libc::MAP_FAILED {
655 None
656 } else {
657 Some(raw.cast())
658 }
659}
660
661pub fn munmap(ptr: *mut u8, len: usize) -> bool {
663 if ptr.is_null() || len == 0 {
664 return true;
665 }
666 let rc = unsafe { libc::munmap(ptr.cast(), len) };
668 rc == 0
669}
670
671pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
673 if ptr.is_null() || len == 0 {
674 return true;
675 }
676 let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
678 rc == 0
679}
680
681pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
683 if ptr.is_null() || len == 0 {
684 return true;
685 }
686 let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
688 rc == 0
689}
690
691#[must_use]
693pub fn ptr_addr_u64(p: *mut u8) -> u64 {
694 u64::try_from(p.addr()).unwrap_or(0)
695}
696
697#[must_use]
699pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
700 let u = usize::try_from(addr).unwrap_or(0);
701 ptr::with_exposed_provenance_mut::<u8>(u).cast()
702}
703
704#[derive(Debug)]
708pub struct HostDir {
709 ptr: *mut libc::DIR,
710}
711
712unsafe impl Send for HostDir {}
715unsafe impl Sync for HostDir {}
717
718impl HostDir {
719 pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
721 let dup = unsafe { libc::dup(host_fd) };
723 if dup < 0 {
724 return Err(last_errno_i32());
725 }
726 let dir = unsafe { libc::fdopendir(dup) };
728 if dir.is_null() {
729 let err = last_errno_i32();
730 unsafe {
732 libc::close(dup);
733 }
734 return Err(err);
735 }
736 Ok(Self { ptr: dir })
737 }
738
739 pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
741 use std::ffi::CStr;
742 loop {
743 let ent = unsafe { libc::readdir(self.ptr) };
745 if ent.is_null() {
746 return None;
747 }
748 let d_type = unsafe { (*ent).d_type };
750 let name_ptr = unsafe { (*ent).d_name.as_ptr() };
751 let name = unsafe { CStr::from_ptr(name_ptr) };
752 let bytes = name.to_bytes().to_vec();
753 if bytes.is_empty() {
754 continue;
755 }
756 return Some((bytes, d_type));
757 }
758 }
759}
760
761impl Drop for HostDir {
762 fn drop(&mut self) {
763 if !self.ptr.is_null() {
764 unsafe {
766 let _ = libc::closedir(self.ptr);
767 }
768 self.ptr = ptr::null_mut();
769 }
770 }
771}
772
773fn last_errno_i32() -> i32 {
774 let raw = io::Error::last_os_error()
775 .raw_os_error()
776 .unwrap_or(1)
777 .unsigned_abs();
778 i32::try_from(raw).unwrap_or(1)
779}