Skip to main content

virtual_file_system/
synchronous_file.rs

1use core::fmt::Debug;
2
3use crate::{
4    IoErrorKind, ItemStatic, Result, VirtualFileSystem, suspend_on, suspend_on_cancellable,
5};
6use alloc::{vec, vec::Vec};
7use exported_file_system::StateFlags;
8use exported_file_system::{ControlCommand, ControlCommandIdentifier, Permissions};
9use file_system::{
10    AccessFlags, AttributeFlags, Attributes, Context, Flags, Inode, Path, Position, Size,
11    Statistics,
12};
13use shared::AnyByLayout;
14use task::TaskIdentifier;
15use users::{GroupIdentifier, UserIdentifier};
16
17pub struct SynchronousFile<'a> {
18    closed: bool,
19    // Native callers are trusted; this is the retained task context of the
20    // opening, not a sandbox between native components.
21    pub(crate) authority: Option<task::TaskAuthority<'static>>,
22    virtual_file_system: &'a VirtualFileSystem,
23    pub(crate) item: ItemStatic,
24    /// Inode of the device entry the opening took its reference on. Two
25    /// mounted devices can share a pointer (every value of a zero-sized type
26    /// does), so references are released by inode, not by pointer.
27    pub(crate) device_inode: Option<Inode>,
28    cursor: crate::cursor::Cursor,
29    pub(crate) flags: Flags,
30    pub(crate) context: Context,
31    /// The modification and status times were recorded on this handle since
32    /// the last flush: only the first write of more than zero bytes after an
33    /// open or a flush touches them, so repeated writes cost no extra metadata.
34    times_touched: bool,
35    /// A metadata-update failure was already logged for this handle.
36    time_error_logged: bool,
37}
38
39impl Debug for SynchronousFile<'_> {
40    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
41        f.debug_struct("SynchronousFile")
42            .field("item", &self.item)
43            .field("position", &self.cursor.position())
44            .field("flags", &self.flags.set_status(self.state()))
45            .finish()
46    }
47}
48
49impl<'a> SynchronousFile<'a> {
50    pub(crate) const fn new(
51        virtual_file_system: &'a VirtualFileSystem,
52        item: ItemStatic,
53        position: Size,
54        flags: Flags,
55        context: Context,
56    ) -> Self {
57        Self {
58            closed: false,
59            authority: None,
60            virtual_file_system,
61            item,
62            device_inode: None,
63            cursor: crate::cursor::Cursor::new(position, flags.get_state()),
64            flags: flags.set_status(StateFlags::empty()),
65            context,
66            times_touched: false,
67            time_error_logged: false,
68        }
69    }
70
71    /// Open a file. In a stackful coroutine the call suspends, and a cancellation drops it
72    /// in place: the wait owns the path and the namespace lock it may hold, so neither is
73    /// left behind in the abandoned frames. An open the cancellation interrupts may have
74    /// created the file already.
75    pub fn open(
76        virtual_file_system: &'a VirtualFileSystem,
77        task: TaskIdentifier,
78        path: impl AsRef<Path>,
79        flags: Flags,
80    ) -> Result<Self> {
81        let file_identifier = suspend_on_cancellable(async move {
82            virtual_file_system.open(&path.as_ref(), flags, task).await
83        })?;
84
85        Ok(file_identifier.into_synchronous_file())
86    }
87
88    pub fn set_position(&mut self, position: &Position) -> Result<Size> {
89        let operations = self
90            .item
91            .as_base_operations()
92            .ok_or(IoErrorKind::Unsupported)?;
93        let context = &mut self.context;
94        self.cursor.update(|current| {
95            let absolute;
96            let position = if let Position::Current(delta) = position {
97                absolute = Position::Start(
98                    current
99                        .checked_add_signed(*delta)
100                        .ok_or(IoErrorKind::InvalidArgument)?,
101                );
102                &absolute
103            } else {
104                position
105            };
106            let next = operations.set_position(context, current, position)?;
107            Ok((next, next))
108        })
109    }
110
111    // - Operations
112
113    pub(crate) fn cancel_operation(&mut self, operation: file_system::Operation) {
114        if let Some(operations) = self.item.as_base_operations() {
115            operations.cancel_operation(&mut self.context, operation);
116        }
117    }
118
119    pub(crate) fn poll_read(
120        &mut self,
121        cx: &mut core::task::Context<'_>,
122        buffer: &mut [u8],
123        offset: Option<Size>,
124    ) -> core::task::Poll<Result<usize>> {
125        if !self.flags.get_access().contains(AccessFlags::Read) {
126            return core::task::Poll::Ready(Err(IoErrorKind::BadDescriptor));
127        }
128        if let Some(offset) = offset {
129            let operations = Self::positional_operations(&self.item)?;
130            return operations.read(&mut self.context, cx, buffer, offset);
131        }
132        let operations = self
133            .item
134            .as_base_operations()
135            .ok_or(IoErrorKind::Unsupported)?;
136        let context = &mut self.context;
137        self.cursor.poll_update(|position| {
138            operations
139                .read(context, cx, buffer, position)
140                .map(|result| result.map(|count| (count, position + count as Size)))
141        })
142    }
143
144    pub(crate) fn poll_read_until(
145        &mut self,
146        cx: &mut core::task::Context<'_>,
147        buffer: &mut [u8],
148        delimiter: &[u8],
149    ) -> core::task::Poll<Result<usize>> {
150        if !self.flags.get_access().contains(AccessFlags::Read) {
151            return core::task::Poll::Ready(Err(IoErrorKind::BadDescriptor));
152        }
153        let operations = self
154            .item
155            .as_base_operations()
156            .ok_or(IoErrorKind::Unsupported)?;
157        let context = &mut self.context;
158        self.cursor.poll_update(|position| {
159            operations
160                .read_until(context, cx, buffer, position, delimiter)
161                .map(|result| result.map(|count| (count, position + count as Size)))
162        })
163    }
164
165    fn file_system_operations(&self) -> Option<&'static dyn file_system::FileSystemOperations> {
166        match &self.item {
167            ItemStatic::File(file_system) => Some(*file_system),
168            _ => None,
169        }
170    }
171
172    /// Update the modification and status times after a mutation of an open
173    /// regular file, once per open or flush interval. The backend commits them
174    /// with the file data on the next sync or close, so this costs no extra
175    /// flash write. Best effort: the triggering operation already succeeded.
176    ///
177    /// With several writers on the same file, the committed modification time
178    /// is the one recorded by the handle whose sync or close commits last,
179    /// which depends on the close order. This is never worse than recording a
180    /// time on every open.
181    fn touch_modification_time(&mut self) {
182        if self.times_touched {
183            return;
184        }
185        if let Err(error) = self
186            .virtual_file_system
187            .touch_handle_modification_time(&self.item, &mut self.context)
188        {
189            match error {
190                IoErrorKind::Unsupported | IoErrorKind::ResourceBusy | IoErrorKind::WouldBlock => {}
191                _ => {
192                    // Log once per handle, not on every write of an errored one.
193                    if !self.time_error_logged {
194                        self.time_error_logged = true;
195                        log::warning!("Failed to update modification time after a write: {error}");
196                    }
197                }
198            }
199        } else {
200            self.times_touched = true;
201        }
202    }
203
204    /// Attach the result of a backend write to the modification-time update.
205    fn after_write(
206        &mut self,
207        result: core::task::Poll<Result<usize>>,
208    ) -> core::task::Poll<Result<usize>> {
209        if let core::task::Poll::Ready(Ok(count)) = result
210            && count > 0
211        {
212            self.touch_modification_time();
213        }
214        result
215    }
216
217    fn append_position(&mut self) -> Option<Size> {
218        // Some devices cannot report a size. Keep the cursor for those devices.
219        if self.state().contains(StateFlags::Append) {
220            self.get_statistics().ok().map(|statistics| statistics.size)
221        } else {
222            None
223        }
224    }
225
226    pub(crate) fn poll_write(
227        &mut self,
228        cx: &mut core::task::Context<'_>,
229        buffer: &[u8],
230        offset: Option<Size>,
231    ) -> core::task::Poll<Result<usize>> {
232        if !self.flags.get_access().contains(AccessFlags::Write) {
233            return core::task::Poll::Ready(Err(IoErrorKind::BadDescriptor));
234        }
235        if let Some(offset) = offset {
236            let result = Self::positional_operations(&self.item)?.write(
237                &mut self.context,
238                cx,
239                buffer,
240                offset,
241            );
242            return self.after_write(result);
243        }
244        let append_position = self.append_position();
245        let operations = self
246            .item
247            .as_base_operations()
248            .ok_or(IoErrorKind::Unsupported)?;
249        let context = &mut self.context;
250        let result = self.cursor.poll_update(|position| {
251            let position = append_position.unwrap_or(position);
252            operations
253                .write(context, cx, buffer, position)
254                .map(|result| result.map(|count| (count, position + count as Size)))
255        });
256        self.after_write(result)
257    }
258
259    pub(crate) fn poll_flush(
260        &mut self,
261        cx: &mut core::task::Context<'_>,
262    ) -> core::task::Poll<Result<()>> {
263        let result = self
264            .item
265            .as_base_operations()
266            .ok_or(IoErrorKind::Unsupported)?
267            .flush(&mut self.context, cx);
268        // A successful flush committed the pending data and times: the next
269        // write is a new mutation and records the times again.
270        if let core::task::Poll::Ready(Ok(())) = result {
271            self.times_touched = false;
272        }
273        result
274    }
275
276    pub(crate) fn poll_control(
277        &mut self,
278        cx: &mut core::task::Context<'_>,
279        command: ControlCommandIdentifier,
280        input: &AnyByLayout,
281        output: &mut AnyByLayout,
282    ) -> core::task::Poll<Result<()>> {
283        if command
284            .get_direction()
285            .contains(file_system::ControlDirectionFlags::Write)
286            && !self.flags.get_access().contains(AccessFlags::Write)
287        {
288            return core::task::Poll::Ready(Err(IoErrorKind::BadDescriptor));
289        }
290        self.item
291            .as_base_operations()
292            .ok_or(IoErrorKind::Unsupported)?
293            .control(&mut self.context, cx, command, input, output)
294    }
295
296    pub fn write(&mut self, buffer: &[u8]) -> Result<usize> {
297        if !self.flags.get_access().contains(AccessFlags::Write) {
298            return Err(IoErrorKind::BadDescriptor);
299        }
300        let append_position = self.append_position();
301        let operations = self
302            .item
303            .as_base_operations()
304            .ok_or(IoErrorKind::Unsupported)?;
305        let context = &mut self.context;
306        let result = self.cursor.update(|position| {
307            let position = append_position.unwrap_or(position);
308            let count = operations.write_sync(context, buffer, position)?;
309            Ok((count, position + count as Size))
310        });
311        if let Ok(count) = result
312            && count > 0
313        {
314            self.touch_modification_time();
315        }
316        result
317    }
318
319    pub fn write_vectored(&mut self, buffers: &[&[u8]]) -> Result<usize> {
320        if !self.flags.get_access().contains(AccessFlags::Write) {
321            return Err(IoErrorKind::BadDescriptor);
322        }
323        let operations = self
324            .item
325            .as_base_operations()
326            .ok_or(IoErrorKind::Unsupported)?;
327        let context = &mut self.context;
328        let result = self.cursor.update(|position| {
329            let count = operations.write_vectored_sync(context, buffers, position)?;
330            Ok((count, position + count as Size))
331        });
332        if let Ok(count) = result
333            && count > 0
334        {
335            self.touch_modification_time();
336        }
337        result
338    }
339
340    pub fn write_line(&mut self, buffer: &[u8]) -> Result<usize> {
341        let size = self.write(buffer)? + self.write(b"\n")?;
342
343        Ok(size)
344    }
345
346    pub fn read(&mut self, buffer: &mut [u8]) -> Result<usize> {
347        if !self.flags.get_access().contains(AccessFlags::Read) {
348            return Err(IoErrorKind::BadDescriptor);
349        }
350        let operations = self
351            .item
352            .as_base_operations()
353            .ok_or(IoErrorKind::Unsupported)?;
354        let context = &mut self.context;
355        self.cursor.update(|position| {
356            let count = operations.read_sync(context, buffer, position)?;
357            Ok((count, position + count as Size))
358        })
359    }
360
361    pub fn read_until(&mut self, buffer: &mut [u8], delimiter: &[u8]) -> Result<usize> {
362        if !self.flags.get_access().contains(AccessFlags::Read) {
363            return Err(IoErrorKind::BadDescriptor);
364        }
365        let operations = self
366            .item
367            .as_base_operations()
368            .ok_or(IoErrorKind::Unsupported)?;
369        let context = &mut self.context;
370        self.cursor.update(|position| {
371            let count = operations.read_until_sync(context, buffer, position, delimiter)?;
372            Ok((count, position + count as Size))
373        })
374    }
375
376    pub fn read_to_end(&mut self, buffer: &mut Vec<u8>, chunk_size: usize) -> Result<usize> {
377        let mut total_read_size = 0;
378
379        let mut chunk = vec![0u8; chunk_size];
380        loop {
381            let read_size = self.read(&mut chunk)?;
382
383            if read_size == 0 {
384                break;
385            }
386
387            total_read_size += read_size;
388
389            buffer.extend_from_slice(&chunk[..read_size]);
390
391            // Yield to allow other tasks to run.
392            //yield_now().await;
393        }
394
395        Ok(total_read_size)
396    }
397
398    pub fn flush(&mut self) -> Result<()> {
399        self.item
400            .as_base_operations()
401            .ok_or(IoErrorKind::Unsupported)?
402            .flush_sync(&mut self.context)?;
403        // The flush committed the pending data and times: the next write is a
404        // new mutation and records the times again.
405        self.times_touched = false;
406
407        Ok(())
408    }
409
410    pub fn duplicate(&self) -> Result<Self> {
411        let context = self
412            .item
413            .as_base_operations()
414            .ok_or(IoErrorKind::Unsupported)?
415            .clone_context(&self.context)?;
416        suspend_on(
417            self.virtual_file_system
418                .retain(&self.item, self.device_inode),
419        )?;
420
421        Ok(Self {
422            closed: false,
423            authority: self.authority,
424            virtual_file_system: self.virtual_file_system,
425            item: self.item.clone(),
426            device_inode: self.device_inode,
427            cursor: self.cursor.duplicate(),
428            flags: self.flags,
429            context,
430            // The duplicate shares the native context, whose pending times
431            // are already recorded.
432            times_touched: self.times_touched,
433            time_error_logged: self.time_error_logged,
434        })
435    }
436
437    pub fn get_statistics(&mut self) -> Result<Statistics> {
438        let mut attributes = Attributes::new().set_mask(AttributeFlags::all());
439
440        self.item
441            .as_attributes_operations()
442            .ok_or(IoErrorKind::Unsupported)?
443            .get_attributes(&mut self.context, &mut attributes)?;
444
445        Statistics::from_attributes(&attributes).ok_or(IoErrorKind::InputOutput)
446    }
447
448    /// Resize through an already opened writable file without changing its cursor.
449    /// Resizing mutates the file, so the modification and status times are
450    /// updated with the size change and committed together with it.
451    pub fn set_size(&mut self, size: Size) -> Result<()> {
452        if !self.flags.get_access().contains(AccessFlags::Write) {
453            return Err(IoErrorKind::BadDescriptor);
454        }
455        let mut attributes = Attributes::new().set_size(size);
456        if let Some(file_system) = self.file_system_operations()
457            && let Ok(time) = self.virtual_file_system.current_time()
458        {
459            let times = Attributes::new().set_modification(time).set_status(time);
460            let mask = AttributeFlags::Size
461                | times
462                    .get_mask()
463                    .intersection(file_system.writable_attributes());
464            attributes = attributes
465                .set_modification(time)
466                .set_status(time)
467                .set_mask(mask);
468        }
469        self.item
470            .as_attributes_operations()
471            .ok_or(IoErrorKind::Unsupported)?
472            .set_attributes(&mut self.context, &attributes)?;
473        Ok(())
474    }
475
476    /// Update timestamps through retained handle authority.
477    pub fn set_times(
478        &mut self,
479        access: Option<file_system::Time>,
480        modification: Option<file_system::Time>,
481    ) -> Result<()> {
482        let mut attributes = Attributes::new();
483        if let Some(time) = access {
484            attributes = attributes.set_access(time);
485        }
486        if let Some(time) = modification {
487            attributes = attributes.set_modification(time);
488        }
489        self.set_metadata(&attributes)
490    }
491
492    fn positional_operations(item: &ItemStatic) -> Result<&dyn file_system::BaseOperations> {
493        if matches!(item, ItemStatic::Pipe(_) | ItemStatic::CharacterDevice(_)) {
494            return Err(IoErrorKind::InvalidSeek);
495        }
496        item.as_base_operations().ok_or(IoErrorKind::Unsupported)
497    }
498
499    /// Read at an explicit offset, leaving the shared cursor unchanged.
500    pub fn read_at(&mut self, buffer: &mut [u8], offset: Size) -> Result<usize> {
501        if !self.flags.get_access().contains(AccessFlags::Read) {
502            return Err(IoErrorKind::BadDescriptor);
503        }
504        Self::positional_operations(&self.item)?.read_sync(&mut self.context, buffer, offset)
505    }
506
507    /// Write at an explicit offset, leaving the shared cursor unchanged.
508    pub fn write_at(&mut self, buffer: &[u8], offset: Size) -> Result<usize> {
509        if !self.flags.get_access().contains(AccessFlags::Write) {
510            return Err(IoErrorKind::BadDescriptor);
511        }
512        let result =
513            Self::positional_operations(&self.item)?.write_sync(&mut self.context, buffer, offset);
514        if let Ok(count) = result
515            && count > 0
516        {
517            self.touch_modification_time();
518        }
519        result
520    }
521
522    pub fn set_owner(
523        &mut self,
524        user: Option<UserIdentifier>,
525        group: Option<GroupIdentifier>,
526    ) -> Result<()> {
527        let mut attributes = Attributes::new();
528
529        if let Some(user) = user {
530            attributes = attributes.set_user(user);
531        }
532
533        if let Some(group) = group {
534            attributes = attributes.set_group(group);
535        }
536
537        self.set_metadata(&attributes)?;
538
539        Ok(())
540    }
541
542    pub fn set_permissions(&mut self, permissions: Permissions) -> Result<()> {
543        let attributes = Attributes::new().set_permissions(permissions);
544
545        self.set_metadata(&attributes)?;
546
547        Ok(())
548    }
549
550    fn set_metadata(&mut self, attributes: &Attributes) -> Result<()> {
551        if self.closed {
552            return Err(IoErrorKind::BadDescriptor);
553        }
554        self.virtual_file_system.set_handle_attributes(
555            self.authority
556                .as_ref()
557                .ok_or(IoErrorKind::PermissionDenied)?,
558            &self.item,
559            &mut self.context,
560            attributes,
561        )
562    }
563
564    pub fn control<C>(&mut self, _command: C, argument: &C::Input) -> Result<C::Output>
565    where
566        C: ControlCommand,
567        C::Output: Default,
568    {
569        let mut output = C::Output::default();
570
571        if C::IDENTIFIER
572            .get_direction()
573            .contains(file_system::ControlDirectionFlags::Write)
574            && !self.flags.get_access().contains(AccessFlags::Write)
575        {
576            return Err(IoErrorKind::BadDescriptor);
577        }
578        self.item
579            .as_base_operations()
580            .ok_or(IoErrorKind::Unsupported)?
581            .control_sync(
582                &mut self.context,
583                C::IDENTIFIER,
584                AnyByLayout::from(argument),
585                AnyByLayout::from_mutable(&mut output),
586            )?;
587
588        Ok(output)
589    }
590
591    /// Forwards an opaque control command and caller-owned payload layouts.
592    pub fn control_raw(
593        &mut self,
594        command: ControlCommandIdentifier,
595        input: &AnyByLayout,
596        output: &mut AnyByLayout,
597    ) -> Result<()> {
598        if command
599            .get_direction()
600            .contains(file_system::ControlDirectionFlags::Write)
601            && !self.flags.get_access().contains(AccessFlags::Write)
602        {
603            return Err(IoErrorKind::BadDescriptor);
604        }
605        self.item
606            .as_base_operations()
607            .ok_or(IoErrorKind::Unsupported)?
608            .control_sync(&mut self.context, command, input, output)?;
609
610        Ok(())
611    }
612
613    pub fn get_access(&self) -> Result<AccessFlags> {
614        Ok(self.flags.get_access())
615    }
616
617    /// Set status flags on this open file description, including its duplicates.
618    pub fn set_state(&mut self, state: StateFlags) -> Result<()> {
619        if state.intersects(StateFlags::Synchronous | StateFlags::SynchronousDataOnly) {
620            return Err(IoErrorKind::Unsupported);
621        }
622        self.cursor.set_state(state);
623        Ok(())
624    }
625
626    pub(crate) fn state(&self) -> StateFlags {
627        self.cursor.state()
628    }
629
630    pub fn get_state(&self) -> Result<StateFlags> {
631        Ok(self.state())
632    }
633
634    pub fn close_internal(&mut self, virtual_file_system: &VirtualFileSystem) -> crate::Result<()> {
635        if self.closed {
636            return Ok(());
637        }
638        let result =
639            suspend_on(virtual_file_system.close(&self.item, self.device_inode, &mut self.context));
640        // Marked only once the close has run. A coroutine cancelled while the close waits
641        // for the file system never gets here, and whoever owns the file next, which is the
642        // native host closing what a cancelled process held, closes it instead of skipping it.
643        self.closed = true;
644        result
645    }
646
647    /// Close using the VFS retained by this file, without consuming it, so that its owner
648    /// can keep it where a cancellation can still reach it until the close is done. Closing
649    /// again, or dropping, does nothing more once this has returned.
650    pub fn close_in_place(&mut self) -> crate::Result<()> {
651        self.close_internal(self.virtual_file_system)
652    }
653
654    /// Close using the VFS retained by this file, reporting any close error.
655    pub fn close_owned(mut self) -> crate::Result<()> {
656        self.close_internal(self.virtual_file_system)
657    }
658
659    pub fn close(mut self, virtual_file_system: &VirtualFileSystem) -> crate::Result<()> {
660        self.close_internal(virtual_file_system)
661    }
662}
663
664impl Drop for SynchronousFile<'_> {
665    /// Closes a file that was not closed, without waiting: a drop must never suspend, or a
666    /// cancellation could abandon it halfway (see
667    /// [`VirtualFileSystem::close_without_waiting`]). Errors are only logged.
668    fn drop(&mut self) {
669        if self.closed {
670            return;
671        }
672        self.closed = true;
673        let _ = self
674            .virtual_file_system
675            .close_without_waiting(&self.item, self.device_inode, &mut self.context)
676            .map_err(|e| {
677                log::warning!("Failed to close SynchronousFile in Drop: {e}");
678            });
679    }
680}