Skip to main content

abi_application/
file.rs

1use crate::{
2    Directory, Process, Status, XILA_RIGHT_READ, XILA_RIGHT_WRITE, canonical, path_input,
3    registry::{self, Handle},
4};
5use core::{
6    ffi::{c_char, c_void},
7    slice,
8};
9use file_system::{AccessFlags, CreateFlags, Flags, Position, StateFlags};
10use virtual_file_system::{File as VfsFile, FileReadiness, SynchronousFile};
11
12pub const XILA_OPEN_READ: u32 = 1;
13pub const XILA_OPEN_WRITE: u32 = 2;
14pub const XILA_OPEN_CREATE: u32 = 4;
15pub const XILA_OPEN_EXCLUSIVE: u32 = 8;
16pub const XILA_OPEN_TRUNCATE: u32 = 16;
17pub const XILA_OPEN_APPEND: u32 = 32;
18pub const XILA_OPEN_NON_BLOCKING: u32 = 64;
19pub const XILA_SEEK_START: u32 = 0;
20pub const XILA_SEEK_CURRENT: u32 = 1;
21pub const XILA_SEEK_END: u32 = 2;
22
23/// Opaque owned file. No handle lookup or buffer allocation is required for I/O.
24pub struct File {
25    // Async I/O can suspend a coroutine. Other callers still probe once.
26    pub(crate) inner: VfsFile<'static>,
27    pub(crate) readiness: FileReadiness,
28}
29impl File {
30    pub fn new(inner: SynchronousFile<'static>) -> Self {
31        let readiness = inner.readiness();
32        Self {
33            inner: VfsFile::from_synchronous_file(inner),
34            readiness,
35        }
36    }
37    /// Hand the file to a program as an owned pointer. Inside a native process the file
38    /// is also registered, so the host closes it if the process ends without doing so.
39    pub fn into_raw(self) -> *mut Self {
40        registry::register(self)
41    }
42    /// Reclaim an owned file.
43    /// # Safety
44    /// `raw` must be a live pointer returned by `into_raw`, reclaimed exactly once.
45    pub unsafe fn from_raw(raw: *mut Self) -> Self {
46        unsafe { registry::reclaim(raw) }
47    }
48}
49
50impl Handle for File {
51    unsafe fn close(raw: *mut Self) {
52        // SAFETY: the registry holds only live files that came from `into_raw`.
53        let _ = unsafe { xila_file_close(raw) };
54    }
55}
56const XILA_OPEN_ALL: u32 = XILA_OPEN_READ
57    | XILA_OPEN_WRITE
58    | XILA_OPEN_CREATE
59    | XILA_OPEN_EXCLUSIVE
60    | XILA_OPEN_TRUNCATE
61    | XILA_OPEN_APPEND
62    | XILA_OPEN_NON_BLOCKING;
63/// Flags that modify file contents and therefore need the WRITE right.
64const XILA_OPEN_MODIFYING: u32 =
65    XILA_OPEN_WRITE | XILA_OPEN_CREATE | XILA_OPEN_TRUNCATE | XILA_OPEN_APPEND;
66
67pub(crate) fn open_flags(flags: u32, rights: u8) -> Result<Flags, Status> {
68    let has = |flag: u32| flags & flag != 0;
69    if flags & !XILA_OPEN_ALL != 0
70        || !has(XILA_OPEN_READ | XILA_OPEN_WRITE)
71        || (has(XILA_OPEN_EXCLUSIVE) && !has(XILA_OPEN_CREATE))
72        // Truncating or appending through a read-only file has no defined meaning.
73        || (has(XILA_OPEN_TRUNCATE | XILA_OPEN_APPEND) && !has(XILA_OPEN_WRITE))
74    {
75        return Err(Status::InvalidArgument);
76    }
77    let rights = u32::from(rights);
78    if (has(XILA_OPEN_READ) && rights & XILA_RIGHT_READ == 0)
79        || (has(XILA_OPEN_MODIFYING) && rights & XILA_RIGHT_WRITE == 0)
80    {
81        return Err(Status::PermissionDenied);
82    }
83    let mut access = AccessFlags::empty();
84    access.set(AccessFlags::Read, has(XILA_OPEN_READ));
85    access.set(AccessFlags::Write, has(XILA_OPEN_WRITE));
86    let mut create = CreateFlags::empty();
87    create.set(CreateFlags::Create, has(XILA_OPEN_CREATE));
88    create.set(CreateFlags::Exclusive, has(XILA_OPEN_EXCLUSIVE));
89    create.set(CreateFlags::Truncate, has(XILA_OPEN_TRUNCATE));
90    let mut state = StateFlags::empty();
91    state.set(StateFlags::Append, has(XILA_OPEN_APPEND));
92    state.set(StateFlags::NonBlocking, has(XILA_OPEN_NON_BLOCKING));
93    Ok(Flags::new(access, Some(create), Some(state)))
94}
95
96/// Open a file relative to a directory with validated XILA_OPEN flags.
97/// # Safety
98/// Objects must be live. Path must be readable for its length; output writable,
99/// aligned and disjoint from inputs. Calls on an object must be serialized.
100pub unsafe extern "C" fn xila_file_open(
101    directory: *const Directory,
102    path: *const c_char,
103    path_length: usize,
104    flags: u32,
105    file: *mut *mut File,
106) -> Status {
107    if directory.is_null() || file.is_null() {
108        return Status::InvalidArgument;
109    }
110    // SAFETY: checked non-null above; the caller guarantees the object is live.
111    let directory = unsafe { &*directory };
112    let result = (|| {
113        let flags = open_flags(flags, directory.rights)?;
114        let path = canonical(
115            directory.path.as_str(),
116            unsafe { path_input(path, path_length)? },
117            true,
118        )?;
119        // Passed by value: the open owns the path, so a cancellation drops it.
120        SynchronousFile::open(directory.vfs, directory.task, path, flags)
121            .map(File::new)
122            .map_err(Status::from)
123    })();
124    match result {
125        Ok(value) => {
126            unsafe { file.write(value.into_raw()) };
127            Status::Ok
128        }
129        Err(error) => error,
130    }
131}
132
133/// Read directly into the caller's buffer; zero size permits a null buffer.
134/// # Safety
135/// File must be live and exclusively accessed. Buffer must be writable for size
136/// bytes and disjoint from file and count. Count must be aligned and writable.
137pub unsafe extern "C" fn xila_file_read(
138    file: *mut File,
139    buffer: *mut core::ffi::c_void,
140    size: usize,
141    count: *mut usize,
142) -> Status {
143    unsafe { file_read(file, buffer, size, None, count) }
144}
145
146/// Transfer at an explicit offset without changing the shared cursor.
147/// Streams return InvalidSeek.
148/// # Safety
149/// Same requirements as `xila_file_read`.
150pub unsafe extern "C" fn xila_file_read_at(
151    file: *mut File,
152    buffer: *mut c_void,
153    size: usize,
154    offset: u64,
155    count: *mut usize,
156) -> Status {
157    unsafe { file_read(file, buffer, size, Some(offset), count) }
158}
159
160unsafe fn file_read(
161    file: *mut File,
162    buffer: *mut c_void,
163    size: usize,
164    offset: Option<u64>,
165    count: *mut usize,
166) -> Status {
167    if file.is_null()
168        || count.is_null()
169        || (size != 0 && buffer.is_null())
170        || size > isize::MAX as usize
171        || offset.is_some_and(|offset| offset.checked_add(size as u64).is_none())
172    {
173        return Status::InvalidArgument;
174    }
175    let buffer = if size == 0 {
176        &mut []
177    } else {
178        unsafe { slice::from_raw_parts_mut(buffer.cast(), size) }
179    };
180    let file = unsafe { &mut (*file).inner };
181    let result = if crate::is_in_coroutine() {
182        crate::suspend_on(file.read_with_offset(buffer, offset))
183    } else {
184        let file = file.as_synchronous_file_mut();
185        match offset {
186            Some(offset) => file.read_at(buffer, offset),
187            None => file.read(buffer),
188        }
189    };
190    match result {
191        Ok(value) => {
192            unsafe { count.write(value) };
193            Status::Ok
194        }
195        Err(error) => error.into(),
196    }
197}
198/// Write directly from the caller's buffer; zero size permits a null buffer.
199/// # Safety
200/// File must be live and exclusively accessed. Buffer must be readable for size
201/// bytes and disjoint from file and count. Count must be aligned and writable.
202pub unsafe extern "C" fn xila_file_write(
203    file: *mut File,
204    buffer: *const core::ffi::c_void,
205    size: usize,
206    count: *mut usize,
207) -> Status {
208    unsafe { file_write(file, buffer, size, None, count) }
209}
210
211/// Transfer at an explicit offset without changing the shared cursor.
212/// Streams return InvalidSeek.
213/// # Safety
214/// Same requirements as `xila_file_write`.
215pub unsafe extern "C" fn xila_file_write_at(
216    file: *mut File,
217    buffer: *const c_void,
218    size: usize,
219    offset: u64,
220    count: *mut usize,
221) -> Status {
222    unsafe { file_write(file, buffer, size, Some(offset), count) }
223}
224
225unsafe fn file_write(
226    file: *mut File,
227    buffer: *const c_void,
228    size: usize,
229    offset: Option<u64>,
230    count: *mut usize,
231) -> Status {
232    if file.is_null()
233        || count.is_null()
234        || (size != 0 && buffer.is_null())
235        || size > isize::MAX as usize
236        || offset.is_some_and(|offset| offset.checked_add(size as u64).is_none())
237    {
238        return Status::InvalidArgument;
239    }
240    let buffer = if size == 0 {
241        &[]
242    } else {
243        unsafe { slice::from_raw_parts(buffer.cast(), size) }
244    };
245    let file = unsafe { &mut (*file).inner };
246    let result = if crate::is_in_coroutine() {
247        crate::suspend_on(file.write_with_offset(buffer, offset))
248    } else {
249        let file = file.as_synchronous_file_mut();
250        match offset {
251            Some(offset) => file.write_at(buffer, offset),
252            None => file.write(buffer),
253        }
254    };
255    match result {
256        Ok(value) => {
257            unsafe { count.write(value) };
258            Status::Ok
259        }
260        Err(error) => error.into(),
261    }
262}
263/// Seek using XILA_SEEK_START, CURRENT or END. Position output is optional.
264/// # Safety
265/// File must be live and exclusively accessed; non-null position must be aligned,
266/// writable and disjoint from the object.
267pub unsafe extern "C" fn xila_file_seek(
268    file: *mut File,
269    offset: i64,
270    whence: u32,
271    position: *mut u64,
272) -> Status {
273    if file.is_null() {
274        return Status::InvalidArgument;
275    }
276    if unsafe { &(*file).readiness }.is_pipe() {
277        return Status::InvalidSeek;
278    }
279    let seek = match whence {
280        0 if offset >= 0 => Position::Start(offset as u64),
281        1 => Position::Current(offset),
282        2 => Position::End(offset),
283        _ => return Status::InvalidArgument,
284    };
285    match unsafe { &mut *file }
286        .inner
287        .as_synchronous_file_mut()
288        .set_position(&seek)
289    {
290        Ok(value) => {
291            if !position.is_null() {
292                unsafe { position.write(value) };
293            }
294            Status::Ok
295        }
296        Err(error) => error.into(),
297    }
298}
299/// Flush pending writes.
300/// # Safety
301/// File must be live and exclusively accessed.
302pub unsafe extern "C" fn xila_file_flush(file: *mut File) -> Status {
303    if file.is_null() {
304        return Status::InvalidArgument;
305    }
306    let file = unsafe { &mut (*file).inner };
307    let result = if crate::is_in_coroutine() {
308        crate::suspend_on(file.flush())
309    } else {
310        file.as_synchronous_file_mut().flush()
311    };
312    result.map_or_else(Status::from, |()| Status::Ok)
313}
314/// Close and free the object even if closing fails. Null succeeds.
315/// # Safety
316/// Non-null file must be owned and released exactly once, with no concurrent calls.
317pub unsafe extern "C" fn xila_file_close(file: *mut File) -> Status {
318    if file.is_null() {
319        return Status::Ok;
320    }
321    // Closed in place: the file stays registered while the close waits for the file system,
322    // so a process cancelled in the middle leaves it to the host, which closes it again.
323    let result = unsafe { &mut (*file).inner }
324        .as_synchronous_file_mut()
325        .close_in_place();
326    drop(unsafe { File::from_raw(file) });
327    result.map_or_else(Status::from, |()| Status::Ok)
328}
329
330/// Resize a writable file without changing its cursor.
331/// # Safety
332/// File must be live and exclusively accessed.
333pub unsafe extern "C" fn xila_file_set_size(file: *mut File, size: u64) -> Status {
334    if file.is_null() {
335        return Status::InvalidArgument;
336    }
337    unsafe { &mut *file }
338        .inner
339        .as_synchronous_file_mut()
340        .set_size(size)
341        .map_or_else(Status::from, |()| Status::Ok)
342}
343
344/// Return an independently closable handle with the same cursor and status flags.
345/// # Safety
346/// File must be live. Serialize with close and operations that mutably borrow
347/// the file. Output must be aligned, writable and disjoint from the file.
348pub unsafe extern "C" fn xila_file_duplicate(file: *const File, output: *mut *mut File) -> Status {
349    if file.is_null() || output.is_null() {
350        return Status::InvalidArgument;
351    }
352    match crate::suspend_on(unsafe { &(*file).inner }.duplicate()) {
353        Ok(duplicate) => {
354            unsafe { output.write(File::new(duplicate.into_synchronous_file()).into_raw()) };
355            Status::Ok
356        }
357        Err(error) => error.into(),
358    }
359}
360
361pub const XILA_CONTROL_BYTES_AVAILABLE: u32 = 1;
362pub const XILA_CONTROL_GET_FILE_FLAGS: u32 = 2;
363pub const XILA_CONTROL_SET_FILE_FLAGS: u32 = 3;
364
365/// A bounded command with one native-endian uint32_t input or output.
366/// BYTES_AVAILABLE returns the queued byte count on either pipe end.
367/// GET_FILE_FLAGS returns the access mode and status as XILA_OPEN_* bits.
368/// SET_FILE_FLAGS replaces the append and nonblocking bits shared by duplicates.
369/// # Safety
370/// File must be live. Serialize access to this handle with close and any other
371/// operations on this handle. A used buffer must be aligned for a uint32_t and
372/// disjoint from the file. Input must be readable for input_size bytes and
373/// output writable for output_size bytes.
374pub unsafe extern "C" fn xila_file_control(
375    file: *mut File,
376    command: u32,
377    input: *const c_void,
378    input_size: usize,
379    output: *mut c_void,
380    output_size: usize,
381) -> Status {
382    if file.is_null() {
383        return Status::InvalidArgument;
384    }
385    let file = unsafe { &mut (*file).inner }.as_synchronous_file_mut();
386    let result = match command {
387        XILA_CONTROL_BYTES_AVAILABLE | XILA_CONTROL_GET_FILE_FLAGS => {
388            let output = output.cast::<u32>();
389            if input_size != 0
390                || output_size != size_of::<u32>()
391                || output.is_null()
392                || !output.is_aligned()
393            {
394                return Status::InvalidArgument;
395            }
396            let value = if command == XILA_CONTROL_BYTES_AVAILABLE {
397                // All pipes exposed through this ABI have bounded capacities.
398                file.pipe_bytes_available()
399                    .map(|bytes| u32::try_from(bytes).unwrap_or(u32::MAX))
400            } else {
401                file_flags(file)
402            };
403            value.map(|value| unsafe { output.write(value) })
404        }
405        XILA_CONTROL_SET_FILE_FLAGS => {
406            let input = input.cast::<u32>();
407            if input_size != size_of::<u32>()
408                || output_size != 0
409                || input.is_null()
410                || !input.is_aligned()
411            {
412                return Status::InvalidArgument;
413            }
414            let flags = unsafe { input.read() };
415            if flags & !(XILA_OPEN_APPEND | XILA_OPEN_NON_BLOCKING) != 0 {
416                return Status::InvalidArgument;
417            }
418            file.get_state().and_then(|mut state| {
419                state.set(StateFlags::Append, flags & XILA_OPEN_APPEND != 0);
420                state.set(StateFlags::NonBlocking, flags & XILA_OPEN_NON_BLOCKING != 0);
421                file.set_state(state)
422            })
423        }
424        _ => return Status::Unsupported,
425    };
426    result.map_or_else(Status::from, |()| Status::Ok)
427}
428
429fn file_flags(file: &SynchronousFile<'_>) -> file_system::Result<u32> {
430    let access = file.get_access()?;
431    let state = file.get_state()?;
432    Ok(
433        (u32::from(access.contains(AccessFlags::Read)) * XILA_OPEN_READ)
434            | (u32::from(access.contains(AccessFlags::Write)) * XILA_OPEN_WRITE)
435            | (u32::from(state.contains(StateFlags::Append)) * XILA_OPEN_APPEND)
436            | (u32::from(state.contains(StateFlags::NonBlocking)) * XILA_OPEN_NON_BLOCKING),
437    )
438}
439
440/// Report whether this file is an interactive terminal.
441/// # Safety
442/// File must be live and exclusively accessed. Output must be writable and
443/// disjoint from the file.
444pub unsafe extern "C" fn xila_file_is_terminal(file: *mut File, terminal: *mut bool) -> Status {
445    if file.is_null() || terminal.is_null() {
446        return Status::InvalidArgument;
447    }
448    let file = unsafe { &mut (*file).inner };
449    let command = file_system::character_device::IS_A_TERMINAL;
450    let result = if crate::is_in_coroutine() {
451        crate::suspend_on(file.control(command, &()))
452    } else {
453        file.as_synchronous_file_mut().control(command, &())
454    };
455    let value = match result {
456        Ok(value) => value,
457        Err(file_system::IoErrorKind::Unsupported) => 0,
458        Err(error) => return error.into(),
459    };
460    // The payload is a byte (`0` or `1`); an unknown byte is invalid.
461    let value = match bool::try_from(value) {
462        Ok(value) => value,
463        Err(_) => return Status::InvalidArgument,
464    };
465    unsafe { terminal.write(value) };
466    Status::Ok
467}
468
469pub const XILA_PIPE_CAPACITY: usize = 512;
470const _: () = assert!(XILA_PIPE_CAPACITY == virtual_file_system::PIPE_BUF);
471
472/// Create an unnamed pipe. Only XILA_OPEN_NON_BLOCKING is accepted in flags.
473/// # Safety
474/// Process must be a live capability. Both outputs must be aligned, writable,
475/// distinct and disjoint from the process.
476pub unsafe extern "C" fn xila_pipe_create(
477    process: *const Process,
478    flags: u32,
479    reader: *mut *mut File,
480    writer: *mut *mut File,
481) -> Status {
482    if process.is_null()
483        || reader.is_null()
484        || writer.is_null()
485        || reader == writer
486        || flags & !XILA_OPEN_NON_BLOCKING != 0
487    {
488        return Status::InvalidArgument;
489    }
490    let mut state = StateFlags::empty();
491    state.set(StateFlags::NonBlocking, flags & XILA_OPEN_NON_BLOCKING != 0);
492    let vfs = unsafe { (*process).host }.virtual_file_system();
493    match crate::suspend_on(vfs.create_unnamed_pipe(XILA_PIPE_CAPACITY, state)) {
494        Ok((input, output)) => {
495            unsafe {
496                reader.write(File::new(input.into_synchronous_file()).into_raw());
497                writer.write(File::new(output.into_synchronous_file()).into_raw());
498            }
499            Status::Ok
500        }
501        Err(error) => error.into(),
502    }
503}