1use core::mem::{MaybeUninit, offset_of, size_of};
4
5use crate::errno::{EINVAL, ENAMETOOLONG, Errno, SysResult};
6use crate::fd::{AT_FDCWD, AT_REMOVEDIR, AT_SYMLINK_NOFOLLOW, RawFd};
7use crate::raw::{nr, syscall0, syscall1, syscall2, syscall3, syscall4, syscall5};
8
9pub const PATH_MAX: usize = 4096;
10
11pub const O_RDONLY: i32 = 0;
12pub const O_WRONLY: i32 = 1;
13pub const O_RDWR: i32 = 2;
14pub const O_ACCMODE: i32 = 3;
15
16pub const O_CREAT: i32 = 0x40;
17pub const O_EXCL: i32 = 0x80;
18pub const O_NOCTTY: i32 = 0x100;
19pub const O_TRUNC: i32 = 0x200;
20pub const O_APPEND: i32 = 0x400;
21pub const O_NONBLOCK: i32 = 0x800;
22pub const O_DSYNC: i32 = 0x1000;
23pub const O_DIRECT: i32 = 0x4000;
24pub const O_LARGEFILE: i32 = 0x8000;
25pub const O_DIRECTORY: i32 = 0x10000;
26pub const O_NOFOLLOW: i32 = 0x20000;
27pub const O_NOATIME: i32 = 0x40000;
28pub const O_CLOEXEC: i32 = 0x80000;
29pub const O_PATH: i32 = 0x200000;
30
31pub const SEEK_SET: i32 = 0;
32pub const SEEK_CUR: i32 = 1;
33pub const SEEK_END: i32 = 2;
34
35pub const F_OK: i32 = 0;
36pub const X_OK: i32 = 1;
37pub const W_OK: i32 = 2;
38pub const R_OK: i32 = 4;
39
40pub const S_IFMT: u32 = 0o17_0000;
41pub const S_IFSOCK: u32 = 0o14_0000;
42pub const S_IFLNK: u32 = 0o12_0000;
43pub const S_IFREG: u32 = 0o10_0000;
44pub const S_IFBLK: u32 = 0o06_0000;
45pub const S_IFDIR: u32 = 0o04_0000;
46pub const S_IFCHR: u32 = 0o02_0000;
47pub const S_IFIFO: u32 = 0o01_0000;
48
49pub const LOCK_SH: i32 = 1;
50pub const LOCK_EX: i32 = 2;
51pub const LOCK_NB: i32 = 4;
52pub const LOCK_UN: i32 = 8;
53
54pub const MS_RDONLY: u64 = 1;
55pub const MS_NOSUID: u64 = 2;
56pub const MS_NODEV: u64 = 4;
57pub const MS_NOEXEC: u64 = 8;
58pub const MS_SYNCHRONOUS: u64 = 16;
59pub const MS_REMOUNT: u64 = 32;
60pub const MS_NOATIME: u64 = 1024;
61pub const MS_BIND: u64 = 4096;
62pub const MS_MOVE: u64 = 8192;
63pub const MS_REC: u64 = 16384;
64
65pub const MNT_FORCE: i32 = 1;
66pub const MNT_DETACH: i32 = 2;
67pub const MNT_EXPIRE: i32 = 4;
68pub const UMOUNT_NOFOLLOW: i32 = 8;
69
70#[repr(C)]
72#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
73pub struct Stat {
74 pub st_dev: u64,
75 pub st_ino: u64,
76 pub st_mode: u32,
77 pub st_nlink: u32,
78 pub st_uid: u32,
79 pub st_gid: u32,
80 pub st_rdev: u64,
81 pub pad1: u64,
82 pub st_size: i64,
83 pub st_blksize: i32,
84 pub pad2: i32,
85 pub st_blocks: i64,
86 pub st_atime: i64,
87 pub st_atime_nsec: i64,
88 pub st_mtime: i64,
89 pub st_mtime_nsec: i64,
90 pub st_ctime: i64,
91 pub st_ctime_nsec: i64,
92 pub unused: [u32; 2],
93}
94
95const _: () = {
96 assert!(size_of::<Stat>() == 128);
97 assert!(offset_of!(Stat, st_size) == 48);
98 assert!(offset_of!(Stat, st_atime) == 72);
99};
100
101pub fn with_c_path<R>(path: &[u8], f: impl FnOnce(*const u8) -> SysResult<R>) -> SysResult<R> {
108 if path.is_empty() {
109 return Err(Errno(EINVAL));
110 }
111 if let Some((&last, prefix)) = path.split_last() {
112 if last == 0 {
113 if prefix.is_empty() || prefix.contains(&0) {
114 return Err(Errno(EINVAL));
115 }
116 if path.len() > PATH_MAX {
117 return Err(Errno(ENAMETOOLONG));
118 }
119 return f(path.as_ptr());
120 }
121 }
122 if path.contains(&0) {
123 return Err(Errno(EINVAL));
124 }
125 if path.len() >= PATH_MAX {
126 return Err(Errno(ENAMETOOLONG));
127 }
128 if path.len() < 256 {
129 let mut buf = [0u8; 256];
130 buf[..path.len()].copy_from_slice(path);
131 return f(buf.as_ptr());
132 }
133 with_c_path_long(path, f)
134}
135
136#[cold]
137fn with_c_path_long<R>(path: &[u8], f: impl FnOnce(*const u8) -> SysResult<R>) -> SysResult<R> {
138 let mut buf = [0u8; PATH_MAX];
139 buf[..path.len()].copy_from_slice(path);
140 f(buf.as_ptr())
141}
142
143pub unsafe fn cstr_slice<'a>(ptr: *const u8) -> SysResult<&'a [u8]> {
149 if ptr.is_null() {
150 return Err(Errno(EINVAL));
151 }
152 let mut len = 0usize;
153 while len < PATH_MAX {
154 let b = unsafe { *ptr.add(len) };
156 if b == 0 {
157 return Ok(unsafe { core::slice::from_raw_parts(ptr, len) });
159 }
160 len += 1;
161 }
162 Err(Errno(ENAMETOOLONG))
163}
164
165pub fn openat(dirfd: RawFd, path: &[u8], flags: i32, mode: u32) -> SysResult<RawFd> {
167 with_c_path(path, |c_path| {
168 let raw = unsafe {
170 syscall4(
171 nr::OPENAT,
172 dirfd as usize,
173 c_path as usize,
174 flags as u32 as usize,
175 mode as usize,
176 )?
177 };
178 Ok(raw as RawFd)
179 })
180}
181
182pub fn open(path: &[u8], flags: i32, mode: u32) -> SysResult<RawFd> {
184 openat(AT_FDCWD, path, flags, mode)
185}
186
187pub fn statat(dirfd: RawFd, path: &[u8], flags: i32) -> SysResult<Stat> {
189 with_c_path(path, |c_path| {
190 let mut st = MaybeUninit::<Stat>::zeroed();
191 unsafe {
193 syscall4(
194 nr::NEWFSTATAT,
195 dirfd as usize,
196 c_path as usize,
197 st.as_mut_ptr() as usize,
198 flags as u32 as usize,
199 )?;
200 Ok(st.assume_init())
201 }
202 })
203}
204
205pub fn stat(path: &[u8]) -> SysResult<Stat> {
207 statat(AT_FDCWD, path, 0)
208}
209
210pub fn lstat(path: &[u8]) -> SysResult<Stat> {
212 statat(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW)
213}
214
215pub fn fstat(fd: RawFd) -> SysResult<Stat> {
217 let mut st = MaybeUninit::<Stat>::zeroed();
218 unsafe {
220 syscall2(nr::FSTAT, fd as usize, st.as_mut_ptr() as usize)?;
221 Ok(st.assume_init())
222 }
223}
224
225pub fn lseek(fd: RawFd, offset: i64, whence: i32) -> SysResult<i64> {
227 let raw = unsafe {
229 syscall3(
230 nr::LSEEK,
231 fd as usize,
232 offset as usize,
233 whence as u32 as usize,
234 )?
235 };
236 Ok(raw as i64)
237}
238
239pub fn ftruncate(fd: RawFd, length: i64) -> SysResult<()> {
241 unsafe {
243 syscall2(nr::FTRUNCATE, fd as usize, length as usize)?;
244 }
245 Ok(())
246}
247
248pub fn fsync(fd: RawFd) -> SysResult<()> {
250 unsafe {
252 syscall1(nr::FSYNC, fd as usize)?;
253 }
254 Ok(())
255}
256
257pub fn fchmod(fd: RawFd, mode: u32) -> SysResult<()> {
259 unsafe {
261 syscall2(nr::FCHMOD, fd as usize, mode as usize)?;
262 }
263 Ok(())
264}
265
266pub fn mkdirat(dirfd: RawFd, path: &[u8], mode: u32) -> SysResult<()> {
268 with_c_path(path, |c_path| {
269 unsafe {
271 syscall3(nr::MKDIRAT, dirfd as usize, c_path as usize, mode as usize)?;
272 }
273 Ok(())
274 })
275}
276
277pub fn mkdir(path: &[u8], mode: u32) -> SysResult<()> {
279 mkdirat(AT_FDCWD, path, mode)
280}
281
282pub fn unlinkat(dirfd: RawFd, path: &[u8], flags: i32) -> SysResult<()> {
284 with_c_path(path, |c_path| {
285 unsafe {
287 syscall3(
288 nr::UNLINKAT,
289 dirfd as usize,
290 c_path as usize,
291 flags as u32 as usize,
292 )?;
293 }
294 Ok(())
295 })
296}
297
298pub fn unlink(path: &[u8]) -> SysResult<()> {
300 unlinkat(AT_FDCWD, path, 0)
301}
302
303pub fn rmdir(path: &[u8]) -> SysResult<()> {
305 unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
306}
307
308pub fn renameat(olddir: RawFd, oldpath: &[u8], newdir: RawFd, newpath: &[u8]) -> SysResult<()> {
310 with_c_path(oldpath, |c_old| {
311 with_c_path(newpath, |c_new| {
312 unsafe {
314 syscall4(
315 nr::RENAMEAT,
316 olddir as usize,
317 c_old as usize,
318 newdir as usize,
319 c_new as usize,
320 )?;
321 }
322 Ok(())
323 })
324 })
325}
326
327pub fn rename(oldpath: &[u8], newpath: &[u8]) -> SysResult<()> {
329 renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
330}
331
332pub fn linkat(
334 olddir: RawFd,
335 oldpath: &[u8],
336 newdir: RawFd,
337 newpath: &[u8],
338 flags: i32,
339) -> SysResult<()> {
340 with_c_path(oldpath, |c_old| {
341 with_c_path(newpath, |c_new| {
342 unsafe {
344 syscall5(
345 nr::LINKAT,
346 olddir as usize,
347 c_old as usize,
348 newdir as usize,
349 c_new as usize,
350 flags as u32 as usize,
351 )?;
352 }
353 Ok(())
354 })
355 })
356}
357
358pub fn link(oldpath: &[u8], newpath: &[u8]) -> SysResult<()> {
360 linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
361}
362
363pub fn readlinkat<'a>(dirfd: RawFd, path: &[u8], out: &'a mut [u8]) -> SysResult<&'a [u8]> {
365 if out.is_empty() {
366 return Err(Errno(EINVAL));
367 }
368 let n = with_c_path(path, |c_path| {
369 unsafe {
371 syscall4(
372 nr::READLINKAT,
373 dirfd as usize,
374 c_path as usize,
375 out.as_mut_ptr() as usize,
376 out.len(),
377 )
378 }
379 })?;
380 let len = n.min(out.len());
381 Ok(&out[..len])
382}
383
384pub fn readlink<'a>(path: &[u8], out: &'a mut [u8]) -> SysResult<&'a [u8]> {
386 readlinkat(AT_FDCWD, path, out)
387}
388
389pub fn faccessat(dirfd: RawFd, path: &[u8], mode: i32, flags: i32) -> SysResult<()> {
391 with_c_path(path, |c_path| {
392 unsafe {
394 syscall4(
395 nr::FACCESSAT,
396 dirfd as usize,
397 c_path as usize,
398 mode as u32 as usize,
399 flags as u32 as usize,
400 )?;
401 }
402 Ok(())
403 })
404}
405
406pub fn access(path: &[u8], mode: i32) -> SysResult<()> {
408 faccessat(AT_FDCWD, path, mode, 0)
409}
410
411pub fn flock(fd: RawFd, operation: i32) -> SysResult<()> {
413 unsafe {
415 syscall2(nr::FLOCK, fd as usize, operation as u32 as usize)?;
416 }
417 Ok(())
418}
419
420pub fn getcwd(out: &mut [u8]) -> SysResult<&[u8]> {
422 if out.is_empty() {
423 return Err(Errno(EINVAL));
424 }
425 let n = unsafe { syscall2(nr::GETCWD, out.as_mut_ptr() as usize, out.len())? };
427 let used = n.min(out.len());
428 let slice = &out[..used];
429 if let Some(pos) = slice.iter().position(|&b| b == 0) {
430 Ok(&slice[..pos])
431 } else {
432 Ok(slice)
433 }
434}
435
436pub fn chdir(path: &[u8]) -> SysResult<()> {
438 with_c_path(path, |c_path| {
439 unsafe {
441 syscall1(nr::CHDIR, c_path as usize)?;
442 }
443 Ok(())
444 })
445}
446
447fn with_opt_c_path<R>(
448 opt_path: Option<&[u8]>,
449 f: impl FnOnce(*const u8) -> SysResult<R>,
450) -> SysResult<R> {
451 match opt_path {
452 Some(path) => with_c_path(path, f),
453 None => f(core::ptr::null()),
454 }
455}
456
457pub fn mount(
459 source: Option<&[u8]>,
460 target: &[u8],
461 fstype: Option<&[u8]>,
462 flags: u64,
463 data: Option<&[u8]>,
464) -> SysResult<()> {
465 with_opt_c_path(source, |c_src| {
466 with_c_path(target, |c_target| {
467 with_opt_c_path(fstype, |c_fstype| {
468 with_opt_c_path(data, |c_data| {
469 unsafe {
471 syscall5(
472 nr::MOUNT,
473 c_src as usize,
474 c_target as usize,
475 c_fstype as usize,
476 flags as usize,
477 c_data as usize,
478 )?;
479 }
480 Ok(())
481 })
482 })
483 })
484 })
485}
486
487pub fn umount2(target: &[u8], flags: i32) -> SysResult<()> {
489 with_c_path(target, |c_target| {
490 unsafe {
492 syscall2(nr::UMOUNT2, c_target as usize, flags as u32 as usize)?;
493 }
494 Ok(())
495 })
496}
497
498pub fn chroot(path: &[u8]) -> SysResult<()> {
500 with_c_path(path, |c_path| {
501 unsafe {
503 syscall1(nr::CHROOT, c_path as usize)?;
504 }
505 Ok(())
506 })
507}
508
509pub fn sync_all_filesystems() {
511 let _ = unsafe { syscall0(nr::SYNC) };
513}
514
515pub fn getdents64(fd: RawFd, buf: &mut [u8]) -> SysResult<usize> {
517 unsafe {
519 syscall3(
520 nr::GETDENTS64,
521 fd as usize,
522 buf.as_mut_ptr() as usize,
523 buf.len(),
524 )
525 }
526}
527
528#[derive(Clone, Copy, Debug, Eq, PartialEq)]
530pub struct DirEntryRef<'a> {
531 pub ino: u64,
532 pub off: i64,
533 pub file_type: u8,
534 pub name: &'a [u8],
535}
536
537#[derive(Clone, Debug)]
539pub struct DirentIter<'a> {
540 buf: &'a [u8],
541 offset: usize,
542}
543
544#[must_use]
546pub fn parse_dirents(filled: &[u8]) -> DirentIter<'_> {
547 DirentIter {
548 buf: filled,
549 offset: 0,
550 }
551}
552
553impl<'a> Iterator for DirentIter<'a> {
554 type Item = DirEntryRef<'a>;
555
556 fn next(&mut self) -> Option<Self::Item> {
557 let rem = &self.buf[self.offset..];
558 if rem.len() < 19 {
559 self.offset = self.buf.len();
560 return None;
561 }
562 let ino = u64::from_ne_bytes([
563 rem[0], rem[1], rem[2], rem[3], rem[4], rem[5], rem[6], rem[7],
564 ]);
565 let off = i64::from_ne_bytes([
566 rem[8], rem[9], rem[10], rem[11], rem[12], rem[13], rem[14], rem[15],
567 ]);
568 let reclen = u16::from_ne_bytes([rem[16], rem[17]]) as usize;
569 if reclen < 19 || reclen > rem.len() {
570 self.offset = self.buf.len();
571 return None;
572 }
573 let file_type = rem[18];
574 let name_region = &rem[19..reclen];
575 let name_len = name_region
576 .iter()
577 .position(|&b| b == 0)
578 .unwrap_or(name_region.len());
579 self.offset += reclen;
580 Some(DirEntryRef {
581 ino,
582 off,
583 file_type,
584 name: &name_region[..name_len],
585 })
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592 use crate::raw::with_mock_syscall;
593
594 #[test]
595 fn stat_layout_matches_aarch64_abi() {
596 assert_eq!(size_of::<Stat>(), 128);
597 assert_eq!(offset_of!(Stat, st_dev), 0);
598 assert_eq!(offset_of!(Stat, st_ino), 8);
599 assert_eq!(offset_of!(Stat, st_mode), 16);
600 assert_eq!(offset_of!(Stat, st_nlink), 20);
601 assert_eq!(offset_of!(Stat, st_uid), 24);
602 assert_eq!(offset_of!(Stat, st_gid), 28);
603 assert_eq!(offset_of!(Stat, st_rdev), 32);
604 assert_eq!(offset_of!(Stat, st_size), 48);
605 assert_eq!(offset_of!(Stat, st_blksize), 56);
606 assert_eq!(offset_of!(Stat, st_blocks), 64);
607 assert_eq!(offset_of!(Stat, st_atime), 72);
608 assert_eq!(offset_of!(Stat, st_mtime), 88);
609 assert_eq!(offset_of!(Stat, st_ctime), 104);
610 }
611
612 #[test]
613 fn with_c_path_validates_and_avoids_copy_when_nul_terminated() {
614 assert_eq!(with_c_path(b"", |_| Ok(())), Err(Errno(EINVAL)));
615 assert_eq!(with_c_path(b"\0", |_| Ok(())), Err(Errno(EINVAL)));
616 assert_eq!(with_c_path(b"a\0b", |_| Ok(())), Err(Errno(EINVAL)));
617 assert_eq!(with_c_path(b"a\0b\0", |_| Ok(())), Err(Errno(EINVAL)));
618
619 let pre_nul = b"/etc/hosts\0";
620 let ptr_seen = with_c_path(pre_nul, Ok).unwrap();
621 assert_eq!(ptr_seen, pre_nul.as_ptr());
622
623 let slice_no_nul = b"/etc/hosts";
624 with_c_path(slice_no_nul, |p| {
625 assert_ne!(p, slice_no_nul.as_ptr());
626 let decoded = unsafe { cstr_slice(p)? };
627 assert_eq!(decoded, slice_no_nul);
628 Ok(())
629 })
630 .unwrap();
631
632 let too_long = [b'x'; PATH_MAX];
633 assert_eq!(with_c_path(&too_long, |_| Ok(())), Err(Errno(ENAMETOOLONG)));
634 }
635
636 #[test]
637 fn parse_dirents_decodes_records() {
638 let mut buf = [0u8; 48];
639 buf[0..8].copy_from_slice(&10u64.to_ne_bytes());
641 buf[8..16].copy_from_slice(&24i64.to_ne_bytes());
642 buf[16..18].copy_from_slice(&24u16.to_ne_bytes());
643 buf[18] = 4;
644 buf[19] = b'.';
645 buf[20] = 0;
646
647 buf[24..32].copy_from_slice(&42u64.to_ne_bytes());
649 buf[32..40].copy_from_slice(&48i64.to_ne_bytes());
650 buf[40..42].copy_from_slice(&24u16.to_ne_bytes());
651 buf[42] = 8;
652 buf[43..46].copy_from_slice(b"abc");
653 buf[46] = 0;
654
655 let mut iter = parse_dirents(&buf);
656 let first = iter.next().unwrap();
657 assert_eq!(
658 first,
659 DirEntryRef {
660 ino: 10,
661 off: 24,
662 file_type: 4,
663 name: b".",
664 }
665 );
666 let second = iter.next().unwrap();
667 assert_eq!(
668 second,
669 DirEntryRef {
670 ino: 42,
671 off: 48,
672 file_type: 8,
673 name: b"abc",
674 }
675 );
676 assert!(iter.next().is_none());
677 }
678
679 #[test]
680 fn getcwd_strips_trailing_nul() {
681 with_mock_syscall(
682 |nr, args| {
683 assert_eq!(nr, nr::GETCWD);
684 let out_ptr = args[0] as *mut u8;
685 let data = b"/work\0";
686 unsafe {
687 core::ptr::copy_nonoverlapping(data.as_ptr(), out_ptr, data.len());
688 }
689 Ok(data.len())
690 },
691 || {
692 let mut buf = [0u8; 32];
693 let path = getcwd(&mut buf).unwrap();
694 assert_eq!(path, b"/work");
695 },
696 );
697 }
698}