rustix/fs/
special.rs

1//! The `CWD` and `ABS` constants, representing the current working directory
2//! and absolute-only paths, respectively.
3//!
4//! # Safety
5//!
6//! This file uses `AT_FDCWD`, which is a raw file descriptor, but which is
7//! always valid, and `-EBADF`, which is an undocumented by commonly used
8//! convention of passing a value which will always fail if the accompanying
9//! path isn't absolute.
10
11#![allow(unsafe_code)]
12
13use crate::backend;
14use backend::c;
15use backend::fd::{BorrowedFd, RawFd};
16
17/// `AT_FDCWD`—A handle representing the current working directory.
18///
19/// This is a file descriptor which refers to the process current directory
20/// which can be used as the directory argument in `*at` functions such as
21/// [`openat`].
22///
23/// # References
24///  - [POSIX]
25///
26/// [`openat`]: crate::fs::openat
27/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/fcntl.h.html
28// SAFETY: `AT_FDCWD` is a reserved value that is never dynamically
29// allocated, so it'll remain valid for the duration of `'static`.
30#[cfg(not(target_os = "horizon"))]
31#[doc(alias = "AT_FDCWD")]
32pub const CWD: BorrowedFd<'static> =
33    unsafe { BorrowedFd::<'static>::borrow_raw(c::AT_FDCWD as RawFd) };
34
35/// `-EBADF`—A handle that requires paths to be absolute.
36///
37/// This is a file descriptor which refers to no directory, which can be used
38/// as the directory argument in `*at` functions such as [`openat`], which
39/// causes them to fail with [`BADF`] if the accompanying path is not absolute.
40///
41/// This corresponds to the undocumented by commonly used convention of
42/// passing `-EBADF` as the `dirfd` argument, which is ignored if the path is
43/// absolute, and evokes an `EBADF` error otherwise.
44///
45/// [`openat`]: crate::fs::openat
46/// [`BADF`]: crate::io::Errno::BADF
47// SAFETY: This `-EBADF` convention is commonly used, such as in lxc, so OS's
48// aren't going to break it.
49pub const ABS: BorrowedFd<'static> =
50    unsafe { BorrowedFd::<'static>::borrow_raw(c::EBADF.wrapping_neg() as RawFd) };
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use crate::fd::AsRawFd as _;
56
57    #[test]
58    fn test_cwd() {
59        assert!(CWD.as_raw_fd() != -1);
60        #[cfg(linux_kernel)]
61        #[cfg(feature = "io_uring")]
62        assert!(CWD.as_raw_fd() != crate::io_uring::IORING_REGISTER_FILES_SKIP.as_raw_fd());
63    }
64
65    #[test]
66    fn test_abs() {
67        assert!(ABS.as_raw_fd() < 0);
68        assert!(ABS.as_raw_fd() != -1);
69        assert!(ABS.as_raw_fd() != c::AT_FDCWD);
70        #[cfg(linux_kernel)]
71        #[cfg(feature = "io_uring")]
72        assert!(ABS.as_raw_fd() != crate::io_uring::IORING_REGISTER_FILES_SKIP.as_raw_fd());
73    }
74}