Skip to main content

abi_application/
metadata.rs

1use crate::{Directory, File, Status, XILA_RIGHT_READ};
2use core::{ffi::c_char, mem::size_of};
3
4pub const XILA_STATISTICS_NO_FOLLOW: u32 = 1;
5pub const XILA_KIND_FILE: u32 = 1;
6pub const XILA_KIND_DIRECTORY: u32 = 2;
7pub const XILA_KIND_BLOCK_DEVICE: u32 = 3;
8pub const XILA_KIND_CHARACTER_DEVICE: u32 = 4;
9pub const XILA_KIND_PIPE: u32 = 5;
10pub const XILA_KIND_SOCKET: u32 = 6;
11pub const XILA_KIND_SYMLINK: u32 = 7;
12
13/// Versioned output: initialize size to sizeof(XilaStatistics) before each call.
14#[repr(C)]
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16pub struct Statistics {
17    pub size: u32,
18    pub kind: u32,
19    pub permissions: u32,
20    pub owner_user: u32,
21    pub owner_group: u32,
22    pub reserved: u32,
23    pub file_size: u64,
24    pub link_count: u64,
25    pub inode: u64,
26    pub access_nanoseconds: i64,
27    pub modification_nanoseconds: i64,
28    pub status_change_nanoseconds: i64,
29}
30
31/// Map the internal kind to its published value; never rely on enum order.
32pub(crate) const fn kind_value(kind: file_system::Kind) -> u32 {
33    use file_system::Kind;
34    match kind {
35        Kind::File => XILA_KIND_FILE,
36        Kind::Directory => XILA_KIND_DIRECTORY,
37        Kind::BlockDevice => XILA_KIND_BLOCK_DEVICE,
38        Kind::CharacterDevice => XILA_KIND_CHARACTER_DEVICE,
39        Kind::Pipe => XILA_KIND_PIPE,
40        Kind::Socket => XILA_KIND_SOCKET,
41        Kind::SymbolicLink => XILA_KIND_SYMLINK,
42    }
43}
44
45impl TryFrom<file_system::Statistics> for Statistics {
46    type Error = Status;
47    fn try_from(value: file_system::Statistics) -> Result<Self, Status> {
48        let nanos = |time: file_system::Time| {
49            time.as_u64()
50                .checked_mul(1_000_000_000)
51                .and_then(|n| i64::try_from(n).ok())
52                .ok_or(Status::Overflow)
53        };
54        Ok(Self {
55            size: size_of::<Self>() as u32,
56            kind: kind_value(value.kind),
57            permissions: u32::from(value.permissions.as_u16()),
58            owner_user: u32::from(value.user.as_u16()),
59            owner_group: u32::from(value.group.as_u16()),
60            reserved: 0,
61            file_size: value.size,
62            link_count: value.links,
63            inode: value.inode,
64            access_nanoseconds: nanos(value.access)?,
65            modification_nanoseconds: nanos(value.modification)?,
66            status_change_nanoseconds: nanos(value.status)?,
67        })
68    }
69}
70
71const STATISTICS_V1_SIZE: u32 = 72;
72
73pub(crate) unsafe fn validate_output(output: *mut Statistics) -> Result<(), Status> {
74    if output.is_null()
75        || unsafe { core::ptr::addr_of!((*output).size).read() } < STATISTICS_V1_SIZE
76    {
77        return Err(Status::InvalidArgument);
78    }
79    Ok(())
80}
81
82unsafe fn write_output(output: *mut Statistics, value: &Statistics) {
83    let length = (unsafe { core::ptr::addr_of!((*output).size).read() } as usize)
84        .min(size_of::<Statistics>());
85    // The public layout contains no implicit padding; every copied byte is initialized.
86    unsafe {
87        core::ptr::copy_nonoverlapping(
88            core::ptr::from_ref(value).cast::<u8>(),
89            output.cast::<u8>(),
90            length,
91        );
92    }
93}
94
95/// Read metadata of an opened readable file.
96/// # Safety
97/// File must be live and exclusively accessed. Output must be aligned, writable
98/// for its declared size, initialized with size, and disjoint from the file.
99pub unsafe extern "C" fn xila_file_get_statistics(
100    file: *mut File,
101    output: *mut Statistics,
102) -> Status {
103    if file.is_null() {
104        return Status::InvalidArgument;
105    }
106    // SAFETY: checked non-null above; the caller guarantees the object is live.
107    let file = unsafe { &mut *file };
108    let result = (|| {
109        unsafe {
110            validate_output(output)?;
111        }
112        // Metadata is not file content: like POSIX fstat, any open file may be queried.
113        Statistics::try_from(file.inner.as_synchronous_file_mut().get_statistics()?)
114    })();
115    match result {
116        Ok(value) => {
117            unsafe {
118                write_output(output, &value);
119            }
120            Status::Ok
121        }
122        Err(error) => error,
123    }
124}
125
126/// Read relative path metadata; an empty path means the capability itself.
127/// # Safety
128/// Directory must be live; path readable for length. Output must be aligned,
129/// writable for its declared size, initialized with size and disjoint from inputs.
130/// Calls must be serialized.
131pub unsafe extern "C" fn xila_directory_get_statistics(
132    directory: *const Directory,
133    path: *const c_char,
134    length: usize,
135    flags: u32,
136    output: *mut Statistics,
137) -> Status {
138    if directory.is_null() || flags & !XILA_STATISTICS_NO_FOLLOW != 0 {
139        return Status::InvalidArgument;
140    }
141    // SAFETY: checked non-null above; the caller guarantees the object is live.
142    let directory = unsafe { &*directory };
143    let result = (|| {
144        unsafe {
145            validate_output(output)?;
146        }
147        let path = unsafe { directory.resolve(path, length, XILA_RIGHT_READ, false)? };
148        let (vfs, task) = (directory.vfs, directory.task);
149        // The future owns the path, so a cancellation drops it with the wait.
150        let value = crate::suspend_on_cancellable(async move {
151            if flags & XILA_STATISTICS_NO_FOLLOW != 0 {
152                vfs.get_link_statistics_for_task(task, &path).await
153            } else {
154                vfs.get_statistics_for_task(task, &path).await
155            }
156        })?;
157        Statistics::try_from(value)
158    })();
159    match result {
160        Ok(value) => {
161            unsafe {
162                write_output(output, &value);
163            }
164            Status::Ok
165        }
166        Err(error) => error,
167    }
168}