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, 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
54#[repr(C)]
56#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
57pub struct Stat {
58 pub st_dev: u64,
59 pub st_ino: u64,
60 pub st_mode: u32,
61 pub st_nlink: u32,
62 pub st_uid: u32,
63 pub st_gid: u32,
64 pub st_rdev: u64,
65 pub pad1: u64,
66 pub st_size: i64,
67 pub st_blksize: i32,
68 pub pad2: i32,
69 pub st_blocks: i64,
70 pub st_atime: i64,
71 pub st_atime_nsec: i64,
72 pub st_mtime: i64,
73 pub st_mtime_nsec: i64,
74 pub st_ctime: i64,
75 pub st_ctime_nsec: i64,
76 pub unused: [u32; 2],
77}
78
79const _: () = {
80 assert!(size_of::<Stat>() == 128);
81 assert!(offset_of!(Stat, st_size) == 48);
82 assert!(offset_of!(Stat, st_atime) == 72);
83};
84
85pub fn with_c_path<R>(path: &[u8], f: impl FnOnce(*const u8) -> SysResult<R>) -> SysResult<R> {
92 if path.is_empty() {
93 return Err(Errno(EINVAL));
94 }
95 if let Some((&last, prefix)) = path.split_last() {
96 if last == 0 {
97 if prefix.is_empty() || prefix.contains(&0) {
98 return Err(Errno(EINVAL));
99 }
100 if path.len() > PATH_MAX {
101 return Err(Errno(ENAMETOOLONG));
102 }
103 return f(path.as_ptr());
104 }
105 }
106 if path.contains(&0) {
107 return Err(Errno(EINVAL));
108 }
109 if path.len() >= PATH_MAX {
110 return Err(Errno(ENAMETOOLONG));
111 }
112 if path.len() < 256 {
113 let mut buf = [0u8; 256];
114 buf[..path.len()].copy_from_slice(path);
115 return f(buf.as_ptr());
116 }
117 with_c_path_long(path, f)
118}
119
120#[cold]
121fn with_c_path_long<R>(path: &[u8], f: impl FnOnce(*const u8) -> SysResult<R>) -> SysResult<R> {
122 let mut buf = [0u8; PATH_MAX];
123 buf[..path.len()].copy_from_slice(path);
124 f(buf.as_ptr())
125}
126
127pub unsafe fn cstr_slice<'a>(ptr: *const u8) -> SysResult<&'a [u8]> {
133 if ptr.is_null() {
134 return Err(Errno(EINVAL));
135 }
136 let mut len = 0usize;
137 while len < PATH_MAX {
138 let b = unsafe { *ptr.add(len) };
140 if b == 0 {
141 return Ok(unsafe { core::slice::from_raw_parts(ptr, len) });
143 }
144 len += 1;
145 }
146 Err(Errno(ENAMETOOLONG))
147}
148
149pub fn openat(dirfd: RawFd, path: &[u8], flags: i32, mode: u32) -> SysResult<RawFd> {
151 with_c_path(path, |c_path| {
152 let raw = unsafe {
154 syscall4(
155 nr::OPENAT,
156 dirfd as usize,
157 c_path as usize,
158 flags as u32 as usize,
159 mode as usize,
160 )?
161 };
162 Ok(raw as RawFd)
163 })
164}
165
166pub fn open(path: &[u8], flags: i32, mode: u32) -> SysResult<RawFd> {
168 openat(AT_FDCWD, path, flags, mode)
169}
170
171pub fn statat(dirfd: RawFd, path: &[u8], flags: i32) -> SysResult<Stat> {
173 with_c_path(path, |c_path| {
174 let mut st = MaybeUninit::<Stat>::zeroed();
175 unsafe {
177 syscall4(
178 nr::NEWFSTATAT,
179 dirfd as usize,
180 c_path as usize,
181 st.as_mut_ptr() as usize,
182 flags as u32 as usize,
183 )?;
184 Ok(st.assume_init())
185 }
186 })
187}
188
189pub fn stat(path: &[u8]) -> SysResult<Stat> {
191 statat(AT_FDCWD, path, 0)
192}
193
194pub fn lstat(path: &[u8]) -> SysResult<Stat> {
196 statat(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW)
197}
198
199pub fn fstat(fd: RawFd) -> SysResult<Stat> {
201 let mut st = MaybeUninit::<Stat>::zeroed();
202 unsafe {
204 syscall2(nr::FSTAT, fd as usize, st.as_mut_ptr() as usize)?;
205 Ok(st.assume_init())
206 }
207}
208
209pub fn lseek(fd: RawFd, offset: i64, whence: i32) -> SysResult<i64> {
211 let raw = unsafe {
213 syscall3(
214 nr::LSEEK,
215 fd as usize,
216 offset as usize,
217 whence as u32 as usize,
218 )?
219 };
220 Ok(raw as i64)
221}
222
223pub fn ftruncate(fd: RawFd, length: i64) -> SysResult<()> {
225 unsafe {
227 syscall2(nr::FTRUNCATE, fd as usize, length as usize)?;
228 }
229 Ok(())
230}
231
232pub fn fsync(fd: RawFd) -> SysResult<()> {
234 unsafe {
236 syscall1(nr::FSYNC, fd as usize)?;
237 }
238 Ok(())
239}
240
241pub fn fchmod(fd: RawFd, mode: u32) -> SysResult<()> {
243 unsafe {
245 syscall2(nr::FCHMOD, fd as usize, mode as usize)?;
246 }
247 Ok(())
248}
249
250pub fn mkdirat(dirfd: RawFd, path: &[u8], mode: u32) -> SysResult<()> {
252 with_c_path(path, |c_path| {
253 unsafe {
255 syscall3(nr::MKDIRAT, dirfd as usize, c_path as usize, mode as usize)?;
256 }
257 Ok(())
258 })
259}
260
261pub fn mkdir(path: &[u8], mode: u32) -> SysResult<()> {
263 mkdirat(AT_FDCWD, path, mode)
264}
265
266pub fn unlinkat(dirfd: RawFd, path: &[u8], flags: i32) -> SysResult<()> {
268 with_c_path(path, |c_path| {
269 unsafe {
271 syscall3(
272 nr::UNLINKAT,
273 dirfd as usize,
274 c_path as usize,
275 flags as u32 as usize,
276 )?;
277 }
278 Ok(())
279 })
280}
281
282pub fn unlink(path: &[u8]) -> SysResult<()> {
284 unlinkat(AT_FDCWD, path, 0)
285}
286
287pub fn rmdir(path: &[u8]) -> SysResult<()> {
289 unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
290}
291
292pub fn renameat(olddir: RawFd, oldpath: &[u8], newdir: RawFd, newpath: &[u8]) -> SysResult<()> {
294 with_c_path(oldpath, |c_old| {
295 with_c_path(newpath, |c_new| {
296 unsafe {
298 syscall4(
299 nr::RENAMEAT,
300 olddir as usize,
301 c_old as usize,
302 newdir as usize,
303 c_new as usize,
304 )?;
305 }
306 Ok(())
307 })
308 })
309}
310
311pub fn rename(oldpath: &[u8], newpath: &[u8]) -> SysResult<()> {
313 renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
314}
315
316pub fn linkat(
318 olddir: RawFd,
319 oldpath: &[u8],
320 newdir: RawFd,
321 newpath: &[u8],
322 flags: i32,
323) -> SysResult<()> {
324 with_c_path(oldpath, |c_old| {
325 with_c_path(newpath, |c_new| {
326 unsafe {
328 syscall5(
329 nr::LINKAT,
330 olddir as usize,
331 c_old as usize,
332 newdir as usize,
333 c_new as usize,
334 flags as u32 as usize,
335 )?;
336 }
337 Ok(())
338 })
339 })
340}
341
342pub fn link(oldpath: &[u8], newpath: &[u8]) -> SysResult<()> {
344 linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
345}
346
347pub fn readlinkat<'a>(dirfd: RawFd, path: &[u8], out: &'a mut [u8]) -> SysResult<&'a [u8]> {
349 if out.is_empty() {
350 return Err(Errno(EINVAL));
351 }
352 let n = with_c_path(path, |c_path| {
353 unsafe {
355 syscall4(
356 nr::READLINKAT,
357 dirfd as usize,
358 c_path as usize,
359 out.as_mut_ptr() as usize,
360 out.len(),
361 )
362 }
363 })?;
364 let len = n.min(out.len());
365 Ok(&out[..len])
366}
367
368pub fn readlink<'a>(path: &[u8], out: &'a mut [u8]) -> SysResult<&'a [u8]> {
370 readlinkat(AT_FDCWD, path, out)
371}
372
373pub fn faccessat(dirfd: RawFd, path: &[u8], mode: i32, flags: i32) -> SysResult<()> {
375 with_c_path(path, |c_path| {
376 unsafe {
378 syscall4(
379 nr::FACCESSAT,
380 dirfd as usize,
381 c_path as usize,
382 mode as u32 as usize,
383 flags as u32 as usize,
384 )?;
385 }
386 Ok(())
387 })
388}
389
390pub fn access(path: &[u8], mode: i32) -> SysResult<()> {
392 faccessat(AT_FDCWD, path, mode, 0)
393}
394
395pub fn flock(fd: RawFd, operation: i32) -> SysResult<()> {
397 unsafe {
399 syscall2(nr::FLOCK, fd as usize, operation as u32 as usize)?;
400 }
401 Ok(())
402}
403
404pub fn getcwd(out: &mut [u8]) -> SysResult<&[u8]> {
406 if out.is_empty() {
407 return Err(Errno(EINVAL));
408 }
409 let n = unsafe { syscall2(nr::GETCWD, out.as_mut_ptr() as usize, out.len())? };
411 let used = n.min(out.len());
412 let slice = &out[..used];
413 if let Some(pos) = slice.iter().position(|&b| b == 0) {
414 Ok(&slice[..pos])
415 } else {
416 Ok(slice)
417 }
418}
419
420pub fn chdir(path: &[u8]) -> SysResult<()> {
422 with_c_path(path, |c_path| {
423 unsafe {
425 syscall1(nr::CHDIR, c_path as usize)?;
426 }
427 Ok(())
428 })
429}
430
431pub fn getdents64(fd: RawFd, buf: &mut [u8]) -> SysResult<usize> {
433 unsafe {
435 syscall3(
436 nr::GETDENTS64,
437 fd as usize,
438 buf.as_mut_ptr() as usize,
439 buf.len(),
440 )
441 }
442}
443
444#[derive(Clone, Copy, Debug, Eq, PartialEq)]
446pub struct DirEntryRef<'a> {
447 pub ino: u64,
448 pub off: i64,
449 pub file_type: u8,
450 pub name: &'a [u8],
451}
452
453#[derive(Clone, Debug)]
455pub struct DirentIter<'a> {
456 buf: &'a [u8],
457 offset: usize,
458}
459
460#[must_use]
462pub fn parse_dirents(filled: &[u8]) -> DirentIter<'_> {
463 DirentIter {
464 buf: filled,
465 offset: 0,
466 }
467}
468
469impl<'a> Iterator for DirentIter<'a> {
470 type Item = DirEntryRef<'a>;
471
472 fn next(&mut self) -> Option<Self::Item> {
473 let rem = &self.buf[self.offset..];
474 if rem.len() < 19 {
475 self.offset = self.buf.len();
476 return None;
477 }
478 let ino = u64::from_ne_bytes([
479 rem[0], rem[1], rem[2], rem[3], rem[4], rem[5], rem[6], rem[7],
480 ]);
481 let off = i64::from_ne_bytes([
482 rem[8], rem[9], rem[10], rem[11], rem[12], rem[13], rem[14], rem[15],
483 ]);
484 let reclen = u16::from_ne_bytes([rem[16], rem[17]]) as usize;
485 if reclen < 19 || reclen > rem.len() {
486 self.offset = self.buf.len();
487 return None;
488 }
489 let file_type = rem[18];
490 let name_region = &rem[19..reclen];
491 let name_len = name_region
492 .iter()
493 .position(|&b| b == 0)
494 .unwrap_or(name_region.len());
495 self.offset += reclen;
496 Some(DirEntryRef {
497 ino,
498 off,
499 file_type,
500 name: &name_region[..name_len],
501 })
502 }
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508 use crate::raw::with_mock_syscall;
509
510 #[test]
511 fn stat_layout_matches_aarch64_abi() {
512 assert_eq!(size_of::<Stat>(), 128);
513 assert_eq!(offset_of!(Stat, st_dev), 0);
514 assert_eq!(offset_of!(Stat, st_ino), 8);
515 assert_eq!(offset_of!(Stat, st_mode), 16);
516 assert_eq!(offset_of!(Stat, st_nlink), 20);
517 assert_eq!(offset_of!(Stat, st_uid), 24);
518 assert_eq!(offset_of!(Stat, st_gid), 28);
519 assert_eq!(offset_of!(Stat, st_rdev), 32);
520 assert_eq!(offset_of!(Stat, st_size), 48);
521 assert_eq!(offset_of!(Stat, st_blksize), 56);
522 assert_eq!(offset_of!(Stat, st_blocks), 64);
523 assert_eq!(offset_of!(Stat, st_atime), 72);
524 assert_eq!(offset_of!(Stat, st_mtime), 88);
525 assert_eq!(offset_of!(Stat, st_ctime), 104);
526 }
527
528 #[test]
529 fn with_c_path_validates_and_avoids_copy_when_nul_terminated() {
530 assert_eq!(with_c_path(b"", |_| Ok(())), Err(Errno(EINVAL)));
531 assert_eq!(with_c_path(b"\0", |_| Ok(())), Err(Errno(EINVAL)));
532 assert_eq!(with_c_path(b"a\0b", |_| Ok(())), Err(Errno(EINVAL)));
533 assert_eq!(with_c_path(b"a\0b\0", |_| Ok(())), Err(Errno(EINVAL)));
534
535 let pre_nul = b"/etc/hosts\0";
536 let ptr_seen = with_c_path(pre_nul, Ok).unwrap();
537 assert_eq!(ptr_seen, pre_nul.as_ptr());
538
539 let slice_no_nul = b"/etc/hosts";
540 with_c_path(slice_no_nul, |p| {
541 assert_ne!(p, slice_no_nul.as_ptr());
542 let decoded = unsafe { cstr_slice(p)? };
543 assert_eq!(decoded, slice_no_nul);
544 Ok(())
545 })
546 .unwrap();
547
548 let too_long = [b'x'; PATH_MAX];
549 assert_eq!(with_c_path(&too_long, |_| Ok(())), Err(Errno(ENAMETOOLONG)));
550 }
551
552 #[test]
553 fn parse_dirents_decodes_records() {
554 let mut buf = [0u8; 48];
555 buf[0..8].copy_from_slice(&10u64.to_ne_bytes());
557 buf[8..16].copy_from_slice(&24i64.to_ne_bytes());
558 buf[16..18].copy_from_slice(&24u16.to_ne_bytes());
559 buf[18] = 4;
560 buf[19] = b'.';
561 buf[20] = 0;
562
563 buf[24..32].copy_from_slice(&42u64.to_ne_bytes());
565 buf[32..40].copy_from_slice(&48i64.to_ne_bytes());
566 buf[40..42].copy_from_slice(&24u16.to_ne_bytes());
567 buf[42] = 8;
568 buf[43..46].copy_from_slice(b"abc");
569 buf[46] = 0;
570
571 let mut iter = parse_dirents(&buf);
572 let first = iter.next().unwrap();
573 assert_eq!(
574 first,
575 DirEntryRef {
576 ino: 10,
577 off: 24,
578 file_type: 4,
579 name: b".",
580 }
581 );
582 let second = iter.next().unwrap();
583 assert_eq!(
584 second,
585 DirEntryRef {
586 ino: 42,
587 off: 48,
588 file_type: 8,
589 name: b"abc",
590 }
591 );
592 assert!(iter.next().is_none());
593 }
594
595 #[test]
596 fn getcwd_strips_trailing_nul() {
597 with_mock_syscall(
598 |nr, args| {
599 assert_eq!(nr, nr::GETCWD);
600 let out_ptr = args[0] as *mut u8;
601 let data = b"/work\0";
602 unsafe {
603 core::ptr::copy_nonoverlapping(data.as_ptr(), out_ptr, data.len());
604 }
605 Ok(data.len())
606 },
607 || {
608 let mut buf = [0u8; 32];
609 let path = getcwd(&mut buf).unwrap();
610 assert_eq!(path, b"/work");
611 },
612 );
613 }
614}