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 open_directory(path: &std::ffi::CStr) -> Option<RawFd> {
110 open_path(
111 path,
112 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
113 0,
114 )
115}
116
117pub fn openat(
119 dirfd: RawFd,
120 path: &std::ffi::CStr,
121 flags: libc::c_int,
122 mode: libc::c_uint,
123) -> Option<RawFd> {
124 let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
126 if rc < 0 { None } else { Some(rc) }
127}
128
129pub fn fstatat(
131 dirfd: RawFd,
132 path: &std::ffi::CStr,
133 no_follow: bool,
134) -> Option<libc::stat> {
135 let mut st: libc::stat = unsafe { std::mem::zeroed() };
136 let flags = if no_follow {
137 libc::AT_SYMLINK_NOFOLLOW
138 } else {
139 0
140 };
141 let rc = unsafe { libc::fstatat(dirfd, path.as_ptr(), std::ptr::addr_of_mut!(st), flags) };
143 if rc == 0 { Some(st) } else { None }
144}
145
146pub fn faccessat_ok(dirfd: RawFd, path: &std::ffi::CStr) -> bool {
148 let rc = unsafe { libc::faccessat(dirfd, path.as_ptr(), libc::F_OK, 0) };
150 rc == 0
151}
152
153pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
155 if data.is_empty() {
156 return Ok(0);
157 }
158 let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
160 if n < 0 {
161 return Err(io::Error::last_os_error());
162 }
163 usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
164}
165
166pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
168 if buf.is_empty() {
169 return Ok(0);
170 }
171 let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
173 if n < 0 {
174 return Err(io::Error::last_os_error());
175 }
176 usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
177}
178
179pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
181 let mut st: libc::stat = unsafe { std::mem::zeroed() };
183 let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
184 if rc == 0 { Some(st) } else { None }
185}
186
187pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
189 let rc = unsafe { libc::ftruncate(fd, length) };
191 if rc == 0 { Some(()) } else { None }
192}
193
194pub fn fsync_fd(fd: RawFd) -> Option<()> {
196 let rc = unsafe { libc::fsync(fd) };
198 if rc == 0 { Some(()) } else { None }
199}
200
201pub fn readlink_path(path: &std::ffi::CStr, buf: &mut [u8]) -> Result<usize, i32> {
203 if buf.is_empty() {
204 return Ok(0);
205 }
206 let n = unsafe { libc::readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
208 if n < 0 {
209 return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO));
210 }
211 usize::try_from(n).map_err(|_| libc::EIO)
212}
213
214pub fn symlink_path(target: &std::ffi::CStr, linkpath: &std::ffi::CStr) -> Result<(), i32> {
216 let rc = unsafe { libc::symlink(target.as_ptr(), linkpath.as_ptr()) };
218 if rc == 0 {
219 Ok(())
220 } else {
221 Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO))
222 }
223}
224
225pub fn link_path(existing: &std::ffi::CStr, newpath: &std::ffi::CStr) -> Result<(), i32> {
227 let rc = unsafe { libc::link(existing.as_ptr(), newpath.as_ptr()) };
229 if rc == 0 {
230 Ok(())
231 } else {
232 Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO))
233 }
234}
235
236pub fn gettimeofday() -> Option<libc::timeval> {
238 let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
240 let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
241 if rc == 0 { Some(tv) } else { None }
242}
243
244pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
246 let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
248 let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
249 if rc == 0 { Some(ts) } else { None }
250}
251
252#[must_use]
257pub fn mmap(
258 fixed_addr: Option<u64>,
259 len: usize,
260 prot: libc::c_int,
261 flags: libc::c_int,
262 fd: RawFd,
263 offset: i64,
264) -> Option<*mut u8> {
265 if len == 0 {
266 return None;
267 }
268 let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
269 let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
272 if raw == libc::MAP_FAILED {
273 None
274 } else {
275 Some(raw.cast())
276 }
277}
278
279pub fn munmap(ptr: *mut u8, len: usize) -> bool {
281 if ptr.is_null() || len == 0 {
282 return true;
283 }
284 let rc = unsafe { libc::munmap(ptr.cast(), len) };
286 rc == 0
287}
288
289pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
291 if ptr.is_null() || len == 0 {
292 return true;
293 }
294 let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
296 rc == 0
297}
298
299pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
301 if ptr.is_null() || len == 0 {
302 return true;
303 }
304 let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
306 rc == 0
307}
308
309#[must_use]
311pub fn ptr_addr_u64(p: *mut u8) -> u64 {
312 u64::try_from(p.addr()).unwrap_or(0)
313}
314
315#[must_use]
317pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
318 let u = usize::try_from(addr).unwrap_or(0);
319 ptr::with_exposed_provenance_mut::<u8>(u).cast()
320}
321
322#[derive(Debug)]
326pub struct HostDir {
327 ptr: *mut libc::DIR,
328}
329
330unsafe impl Send for HostDir {}
333unsafe impl Sync for HostDir {}
335
336impl HostDir {
337 pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
339 let dup = unsafe { libc::dup(host_fd) };
341 if dup < 0 {
342 return Err(last_errno_i32());
343 }
344 let dir = unsafe { libc::fdopendir(dup) };
346 if dir.is_null() {
347 let err = last_errno_i32();
348 unsafe {
350 libc::close(dup);
351 }
352 return Err(err);
353 }
354 Ok(Self { ptr: dir })
355 }
356
357 pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
359 use std::ffi::CStr;
360 loop {
361 let ent = unsafe { libc::readdir(self.ptr) };
363 if ent.is_null() {
364 return None;
365 }
366 let d_type = unsafe { (*ent).d_type };
368 let name_ptr = unsafe { (*ent).d_name.as_ptr() };
369 let name = unsafe { CStr::from_ptr(name_ptr) };
370 let bytes = name.to_bytes().to_vec();
371 if bytes.is_empty() {
372 continue;
373 }
374 return Some((bytes, d_type));
375 }
376 }
377}
378
379impl Drop for HostDir {
380 fn drop(&mut self) {
381 if !self.ptr.is_null() {
382 unsafe {
384 let _ = libc::closedir(self.ptr);
385 }
386 self.ptr = ptr::null_mut();
387 }
388 }
389}
390
391fn last_errno_i32() -> i32 {
392 let raw = io::Error::last_os_error()
393 .raw_os_error()
394 .unwrap_or(1)
395 .unsigned_abs();
396 i32::try_from(raw).unwrap_or(1)
397}