Skip to main content

dope_sys/io/file/
raw.rs

1use std::{
2    mem::MaybeUninit,
3    os::fd::{AsRawFd, BorrowedFd, OwnedFd, RawFd},
4    slice,
5};
6
7use o3::{
8    base::num::bounded,
9    buffer::bytes::{self, bounded::MAX},
10};
11
12use crate::{Errno, io, kernel};
13use io::{
14    fd,
15    file::{self, metadata::Metadata, watch},
16};
17use kernel::errno;
18
19/// # Safety
20/// Descriptors stay fixed until owner drop; names retain exclusive storage through borrowing.
21/// Watches retain registration; events borrow only admitted records.
22pub unsafe trait Directory: kernel::raw::Source {
23    type Stream;
24    type Watch;
25    type Events<'a>: Iterator<Item = watch::Event<'a>>;
26
27    /// # Safety
28    /// Bytes contain complete initialized native records for this watch,
29    /// including nonzero event masks.
30    unsafe fn watch_events<'a>(watch: &Self::Watch, bytes: &'a [u8]) -> Self::Events<'a>;
31
32    fn open_dir<E: From<Errno>>(path: &std::ffi::CStr) -> Result<Self::Stream, file::OpenError<E>>
33    where
34        Self: file::File,
35    {
36        let file = Self::open(
37            path,
38            file::Open::DIRECTORY | file::Open::CLOSE_ON_EXEC,
39            file::Mode::new(0),
40        )
41        .map_err(file::OpenError::Syscall)?;
42        Self::from_fd(file)
43    }
44
45    fn from_fd<E: From<Errno>>(file: OwnedFd) -> Result<Self::Stream, file::OpenError<E>>;
46    fn descriptor(stream: &Self::Stream) -> kernel::raw::Descriptor;
47    fn next(stream: &mut Self::Stream) -> Result<Option<file::Entry<'_>>, Errno>;
48}
49
50/// # Safety
51/// Each decoded success retains the uniquely transferred descriptor until
52/// delivery or reclamation.
53pub unsafe trait Completion {
54    type Outcome;
55    type Invalid;
56
57    /// # Safety
58    /// A successful outcome transfers one live descriptor from a completed
59    /// open operation. Its descriptor has not been decoded or reclaimed before.
60    unsafe fn open(outcome: Self::Outcome) -> Result<Result<OwnedFd, Errno>, Self::Invalid>;
61}
62
63pub(super) fn parent(dir: Option<BorrowedFd<'_>>) -> RawFd {
64    dir.as_ref().map_or(libc::AT_FDCWD, AsRawFd::as_raw_fd)
65}
66
67unsafe fn completed<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
68    result: libc::c_int,
69    output: &MaybeUninit<libc::stat>,
70) -> Result<Metadata, E> {
71    // SAFETY: the caller pairs one stat call's unchanged status with its destination.
72    unsafe {
73        io::raw::status::<S, E>(result)?;
74        Ok(Metadata::new(output.assume_init_ref()))
75    }
76}
77
78pub(super) fn unlink_at<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
79    dir: Option<BorrowedFd<'_>>,
80    path: &std::ffi::CStr,
81    flags: libc::c_int,
82) -> Result<(), E> {
83    // SAFETY: both calls borrow the terminated path and any supplied parent through their status.
84    unsafe {
85        let result = match (dir, flags) {
86            (None, 0) => libc::unlink(path.as_ptr()),
87            (dir, flags) => libc::unlinkat(parent(dir), path.as_ptr(), flags),
88        };
89        io::raw::status::<S, E>(result)
90    }
91}
92
93pub(super) fn entries<S: Directory>(
94    stream: &mut S::Stream,
95) -> (BorrowedFd<'_>, file::Entries<'_, S>) {
96    let fd = S::descriptor(stream);
97    // SAFETY: the descriptor is fixed until stream drop; this loan keeps its owner live.
98    (
99        unsafe { BorrowedFd::borrow_raw(fd.get()) },
100        file::Entries(stream),
101    )
102}
103
104pub(super) fn open<S: errno::Source + ?Sized, E: From<Errno>>(
105    parent: Option<BorrowedFd<'_>>,
106    path: &std::ffi::CStr,
107    flags: file::Open,
108    mode: file::Mode,
109) -> Result<OwnedFd, E> {
110    let flags = flags.raw();
111    let mode = mode.raw() as libc::mode_t as libc::c_uint;
112    // SAFETY: the terminated path and optional parent stay borrowed; success transfers the new descriptor.
113    unsafe {
114        let result = match parent {
115            Some(dir) => libc::openat(dir.as_raw_fd(), path.as_ptr(), flags, mode),
116            None => libc::open(path.as_ptr(), flags, mode),
117        };
118        <OwnedFd as fd::raw::Adopt>::try_adopt::<S, E>(result)
119    }
120}
121
122pub(super) fn stat<S: errno::Source + ?Sized, E: From<Errno>, const NO_FOLLOW: bool>(
123    dir: Option<BorrowedFd<'_>>,
124    path: &std::ffi::CStr,
125) -> Result<Metadata, E> {
126    let mut output = MaybeUninit::uninit();
127    // SAFETY: each call borrows the path and initializes this output only on success.
128    unsafe {
129        let result = if NO_FOLLOW {
130            libc::fstatat(
131                parent(dir),
132                path.as_ptr(),
133                output.as_mut_ptr(),
134                libc::AT_SYMLINK_NOFOLLOW,
135            )
136        } else {
137            libc::stat(path.as_ptr(), output.as_mut_ptr())
138        };
139        completed::<S, E>(result, &output)
140    }
141}
142
143pub(super) fn rename<S: errno::Source + ?Sized, E: From<Errno>>(
144    dir: Option<BorrowedFd<'_>>,
145    old: &std::ffi::CStr,
146    new: &std::ffi::CStr,
147) -> Result<(), E> {
148    // SAFETY: both terminated names and the common parent, when present, outlive the call.
149    unsafe {
150        let result = match dir {
151            Some(dir) => {
152                libc::renameat(dir.as_raw_fd(), old.as_ptr(), dir.as_raw_fd(), new.as_ptr())
153            }
154            None => libc::rename(old.as_ptr(), new.as_ptr()),
155        };
156        io::raw::status::<S, E>(result)
157    }
158}
159
160pub(super) fn read<'a, S: kernel::raw::Source + ?Sized, E: From<Errno>>(
161    file: BorrowedFd<'_>,
162    output: &'a mut [MaybeUninit<u8>],
163    offset: file::Offset,
164) -> Result<&'a mut [u8], E> {
165    // SAFETY: pread initializes the returned prefix only, retains the descriptor and accepts this off_t.
166    unsafe {
167        let count = libc::pread(
168            file.as_raw_fd(),
169            output.as_mut_ptr().cast(),
170            output.len(),
171            offset.get() as libc::off_t,
172        );
173        Ok(io::raw::Buffer::try_native::<S, E>(output, count)?.assume_init_mut())
174    }
175}
176
177pub(super) fn metadata<S: errno::Source + ?Sized, E: From<Errno>>(
178    file: BorrowedFd<'_>,
179) -> Result<Metadata, E> {
180    let mut output = MaybeUninit::uninit();
181    // SAFETY: only a successful fstat initializes this destination.
182    unsafe {
183        let result = libc::fstat(file.as_raw_fd(), output.as_mut_ptr());
184        completed::<S, E>(result, &output)
185    }
186}
187
188pub(super) fn mkdir<S: errno::Source + ?Sized, E: From<Errno>>(
189    path: &std::ffi::CStr,
190    mode: file::Mode,
191) -> Result<(), E> {
192    // SAFETY: the path is terminated and remains borrowed through the native result.
193    unsafe { io::raw::status::<S, E>(libc::mkdir(path.as_ptr(), mode.raw() as libc::mode_t)) }
194}
195
196pub(super) fn try_lock<S: errno::Source + ?Sized, E: From<Errno>>(
197    file: BorrowedFd<'_>,
198) -> Result<(), E> {
199    // SAFETY: this nonblocking exclusive admission borrows the descriptor and captures the exact errno.
200    unsafe { io::raw::status::<S, E>(libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB)) }
201}
202
203pub(super) fn sync<S: errno::Source + ?Sized, E: From<Errno>>(
204    file: BorrowedFd<'_>,
205) -> Result<(), E> {
206    // SAFETY: fsync borrows the descriptor and returns zero or -1 with errno.
207    unsafe { io::raw::status::<S, E>(libc::fsync(file.as_raw_fd())) }
208}
209
210pub(super) fn truncate<S: errno::Source + ?Sized, E: From<Errno>>(
211    file: BorrowedFd<'_>,
212    len: i64,
213) -> Result<(), E> {
214    // SAFETY: ftruncate borrows the descriptor and returns zero or -1 with errno.
215    unsafe { io::raw::status::<S, E>(libc::ftruncate(file.as_raw_fd(), len)) }
216}
217
218pub(super) fn read_at<'a, S: errno::Source + ?Sized, E: From<Errno>>(
219    file: BorrowedFd<'_>,
220    output: &'a mut [u8],
221    offset: file::Offset,
222) -> Result<&'a mut [u8], E> {
223    // SAFETY: pread writes only initialized bytes and cannot invalidate the rest of the original slice.
224    let output = unsafe { slice::from_raw_parts_mut(output.as_mut_ptr().cast(), output.len()) };
225    read::<S, E>(file, output, offset)
226}
227
228pub(super) fn write_at<S: errno::Source + ?Sized, E: From<Errno>>(
229    file: BorrowedFd<'_>,
230    input: bytes::Prefix<'_, MAX>,
231    offset: file::Offset,
232) -> Result<bounded::raw::U32<0, { MAX as u32 }>, E> {
233    let input = input.as_slice();
234    // SAFETY: the admitted input bounds a completed write to i32::MAX and the offset fits off_t.
235    unsafe {
236        let count = libc::pwrite(
237            file.as_raw_fd(),
238            input.as_ptr().cast(),
239            input.len(),
240            offset.get() as libc::off_t,
241        );
242        Ok(kernel::raw::Status::from_count(count)
243            .try_count::<S, E>()?
244            .bounded())
245    }
246}