yash-env 0.13.2

Yash shell execution environment interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2021 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! I/O within a virtual system.

use super::super::Errno;
use super::super::FileType;
use super::FdFlag;
use super::FileBody;
use super::Inode;
use enumset::EnumSet;
use std::cell::Cell;
use std::cell::RefCell;
use std::fmt::Debug;
use std::io::SeekFrom;
use std::rc::Rc;
use std::rc::Weak;
use std::task::Poll;
use std::task::Waker;

/// State of a file opened for reading and/or writing
#[derive(Clone, Debug)]
pub struct OpenFileDescription {
    /// File content and metadata
    file: Rc<RefCell<Inode>>,
    /// Position in bytes to perform next I/O operation at
    offset: usize,
    /// Whether this file is opened for reading
    is_readable: bool,
    /// Whether this file is opened for writing
    is_writable: bool,
    /// Whether this file is opened for appending
    is_appending: bool,
    /// Whether this file is opened in non-blocking mode
    is_nonblocking: bool,
}

impl Drop for OpenFileDescription {
    fn drop(&mut self) {
        let mut file = self.file.borrow_mut();
        file.body.close(self.is_readable, self.is_writable);
    }
}

impl OpenFileDescription {
    /// Creates a new open file description.
    pub(crate) fn new(
        file: Rc<RefCell<Inode>>,
        offset: usize,
        is_readable: bool,
        is_writable: bool,
        is_appending: bool,
        is_nonblocking: bool,
    ) -> Self {
        file.borrow_mut().body.open(is_readable, is_writable);

        Self {
            file,
            offset,
            is_readable,
            is_writable,
            is_appending,
            is_nonblocking,
        }
    }

    /// Returns the i-node this open file description is operating on.
    #[must_use]
    pub(crate) fn file(&self) -> &Rc<RefCell<Inode>> {
        &self.file
    }

    /// Returns true if you can read from this open file description.
    #[must_use]
    pub fn is_readable(&self) -> bool {
        self.is_readable
    }

    /// Returns true if you can write to this open file description.
    #[must_use]
    pub fn is_writable(&self) -> bool {
        self.is_writable
    }

    /// Returns true if this open file description is in non-blocking mode.
    #[inline]
    #[must_use]
    pub fn is_nonblocking(&self) -> bool {
        self.is_nonblocking
    }

    /// Sets whether this open file description is in non-blocking mode.
    #[inline]
    pub fn set_nonblocking(&mut self, is_nonblocking: bool) {
        self.is_nonblocking = is_nonblocking
    }

    /// Returns true if a read operation on this open file description would not
    /// block.
    #[must_use]
    pub fn is_ready_for_reading(&self) -> bool {
        // If this file is not readable, it is considered ready for reading
        // because any read operation on it would immediately fail.
        !self.is_readable || self.file.borrow().body.is_ready_for_reading()
    }

    /// Returns true if a write operation on this open file description would
    /// not block.
    #[must_use]
    pub fn is_ready_for_writing(&self) -> bool {
        // If this file is not writable, it is considered ready for writing
        // because any write operation on it would immediately fail.
        !self.is_writable || self.file.borrow().body.is_ready_for_writing()
    }

    /// Registers a waker to be woken up when this open file description becomes
    /// ready for reading.
    ///
    /// The caller should ensure that the OFD is not
    /// [ready for reading](Self::is_ready_for_reading) when calling this
    /// method, otherwise the waker may never be woken up.
    pub(super) fn register_reader_waker(&mut self, waker: Weak<Cell<Option<Waker>>>) {
        self.file.borrow_mut().body.register_reader_waker(waker);
    }

    /// Registers a waker to be woken up when this open file description becomes
    /// ready for writing.
    ///
    /// The caller should ensure that the OFD is not
    /// [ready for writing](Self::is_ready_for_writing) when calling this
    /// method, otherwise the waker may never be woken up.
    pub(super) fn register_writer_waker(&mut self, waker: Weak<Cell<Option<Waker>>>) {
        self.file.borrow_mut().body.register_writer_waker(waker);
    }

    /// Reads from this open file description.
    ///
    /// Returns the number of bytes successfully read.
    ///
    /// This function does not support blocking read. If the file is not ready
    /// for reading, it returns `Err(Errno::EAGAIN)`. Use
    /// [`poll_read`](Self::poll_read) for polling support.
    pub fn read(&mut self, buffer: &mut [u8]) -> Result<usize, Errno> {
        match self.poll_read(buffer, Weak::new) {
            Poll::Ready(result) => result,
            Poll::Pending => Err(Errno::EAGAIN),
        }
    }

    /// Polls for the result of reading from this open file description.
    ///
    /// The `get_waker` parameter is a function that returns a weak reference to
    /// the waker of the current task. It is used to register the waker for
    /// pending read operations on files like FIFOs. The function is called only
    /// when the read operation would block, so it can be used to avoid
    /// unnecessary allocations of wakers when the operation can complete
    /// immediately. Since the waker is passed as a weak reference, the caller
    /// must ensure that there is a strong reference to the waker that lives at
    /// least until the file body wakes it up, otherwise the weak reference may
    /// become invalid and the task may not be woken up correctly. The waker is
    /// wrapped in `Cell<Option<Waker>>` to allow it to be shared among multiple
    /// wake conditions and to allow it to be taken by the first condition that
    /// wakes the task.
    ///
    /// The returned `Poll` indicates whether the read operation has completed
    /// or is still pending. If it is `Poll::Ready`, the contained `Result`
    /// indicates whether the read was successful and how many bytes were read,
    /// or if it failed with an error. If it is `Poll::Pending`, it means a
    /// waker has been registered and the caller should wait until it is woken
    /// up, when this method should be called again.
    pub fn poll_read<F>(
        &mut self,
        buffer: &mut [u8],
        mut get_waker: F,
    ) -> Poll<Result<usize, Errno>>
    where
        F: FnMut() -> Weak<Cell<Option<Waker>>>,
    {
        if !self.is_readable {
            return Poll::Ready(Err(Errno::EBADF));
        }

        let file = self.file.borrow_mut();
        let is_nonblocking = self.is_nonblocking;
        let maybe_get_waker = move || {
            if is_nonblocking {
                Weak::new()
            } else {
                get_waker()
            }
        };

        let poll = { file }
            .body
            .poll_read(buffer, self.offset, maybe_get_waker);

        if is_nonblocking && poll.is_pending() {
            return Poll::Ready(Err(Errno::EAGAIN));
        }
        if let Poll::Ready(Ok(count)) = poll {
            self.offset += count;
        }

        poll
    }

    /// Writes to this open file description.
    ///
    /// Returns the number of bytes successfully written.
    pub fn write(&mut self, buffer: &[u8]) -> Result<usize, Errno> {
        match self.poll_write(buffer, Weak::new) {
            Poll::Ready(result) => result,
            Poll::Pending => Err(Errno::EAGAIN),
        }
    }

    /// Polls for the result of writing to this open file description.
    ///
    /// The `get_waker` parameter is a function that returns a weak reference to
    /// the waker of the current task. It is used to register the waker for
    /// pending write operations on files like FIFOs. The function is called
    /// only when the write operation would block, so it can be used to avoid
    /// unnecessary allocations of wakers when the operation can complete
    /// immediately. Since the waker is passed as a weak reference, the caller
    /// must ensure that there is a strong reference to the waker that lives at
    /// least until the file body wakes it up, otherwise the weak reference may
    /// become invalid and the task may not be woken up correctly. The waker is
    /// wrapped in `Cell<Option<Waker>>` to allow it to be shared among multiple
    /// wake conditions and to allow it to be taken by the first condition that
    /// wakes the task.
    ///
    /// The returned `Poll` indicates whether the write operation has completed
    /// or is still pending. If it is `Poll::Ready`, the contained `Result`
    /// indicates whether the write was successful and how many bytes were
    /// written, or if it failed with an error. If it is `Poll::Pending`, it
    /// means a waker has been registered and the caller should wait until it is
    /// woken up, when this method should be called again.
    pub fn poll_write<F>(&mut self, buffer: &[u8], mut get_waker: F) -> Poll<Result<usize, Errno>>
    where
        F: FnMut() -> Weak<Cell<Option<Waker>>>,
    {
        if !self.is_writable {
            return Poll::Ready(Err(Errno::EBADF));
        }

        let file = self.file.borrow_mut();
        let offset = if self.is_appending {
            file.body.size()
        } else {
            self.offset
        };
        let is_nonblocking = self.is_nonblocking;
        let maybe_get_waker = move || {
            if is_nonblocking {
                Weak::new()
            } else {
                get_waker()
            }
        };

        let poll = { file }.body.poll_write(buffer, offset, maybe_get_waker);

        if is_nonblocking && poll.is_pending() {
            return Poll::Ready(Err(Errno::EAGAIN));
        }
        if let Poll::Ready(Ok(count)) = poll {
            self.offset = offset + count;
        }

        poll
    }

    /// Drives a `write(2)`-equivalent loop on this open file description.
    ///
    /// This helper encapsulates the POSIX rule that a single blocking `write(2)`
    /// call to a pipe must, in the absence of a signal, transfer the entire
    /// buffer even when the buffer is larger than [`PIPE_BUF`]. For a blocking
    /// FIFO it repeatedly calls [`poll_write`](Self::poll_write), advancing
    /// `bytes_written` until either the buffer is exhausted (returns
    /// `Ready(Ok(*bytes_written))`), no more bytes fit and the next call would
    /// block (returns `Pending` after registering the waker), or an error is
    /// reported (returns `Ready(Err(_))` if no bytes have been transferred yet,
    /// or `Ready(Ok(*bytes_written))` otherwise).
    ///
    /// For non-FIFO files or non-blocking file descriptors it returns after a
    /// single `poll_write` call without looping; this matches POSIX `write(2)`
    /// semantics for those cases.
    ///
    /// `bytes_written` is updated in place so that the caller can resume the
    /// operation across multiple polls without losing the running total when a
    /// signal interrupts the operation. This function will panic if
    /// `bytes_written` exceeds the length of `buffer`. `get_waker` has the same
    /// contract as for [`poll_write`](Self::poll_write).
    ///
    /// [`PIPE_BUF`]: super::PIPE_BUF
    pub fn poll_write_full<F>(
        &mut self,
        buffer: &[u8],
        bytes_written: &mut usize,
        mut get_waker: F,
    ) -> Poll<Result<usize, Errno>>
    where
        F: FnMut() -> Weak<Cell<Option<Waker>>>,
    {
        // Whether to keep looping after a successful partial write. Only a
        // blocking FIFO requires looping; everything else returns after the
        // first successful poll_write call.
        let loop_on_success =
            !self.is_nonblocking && self.file.borrow().body.r#type() == FileType::Fifo;
        loop {
            let remaining = &buffer[*bytes_written..];
            if remaining.is_empty() {
                return Poll::Ready(Ok(*bytes_written));
            }
            match self.poll_write(remaining, &mut get_waker) {
                Poll::Ready(Ok(n)) => {
                    *bytes_written += n;
                    if !loop_on_success || n == 0 {
                        return Poll::Ready(Ok(*bytes_written));
                    }
                    // Blocking FIFO with bytes still remaining: try again.
                }
                Poll::Ready(Err(e)) => {
                    return Poll::Ready(if *bytes_written > 0 {
                        Ok(*bytes_written)
                    } else {
                        Err(e)
                    });
                }
                Poll::Pending => return Poll::Pending,
            }
        }
    }

    /// Moves the file offset and returns the new offset.
    pub fn seek(&mut self, position: SeekFrom) -> Result<usize, Errno> {
        let len = match &self.file.borrow().body {
            FileBody::Regular { content, .. } => content.len(),
            FileBody::Directory { files, .. } => files.len(),
            FileBody::Fifo { .. } => return Err(Errno::ESPIPE),
            FileBody::Symlink { .. } | FileBody::Terminal { .. } => return Err(Errno::ENOTSUP),
        };

        let new_offset = match position {
            SeekFrom::Start(offset) => offset.try_into().ok(),
            SeekFrom::Current(offset) => offset
                .try_into()
                .ok()
                .and_then(|offset| self.offset.checked_add_signed(offset)),
            SeekFrom::End(offset) => offset
                .try_into()
                .ok()
                .and_then(|offset| len.checked_add_signed(offset)),
        };

        let new_offset = new_offset.ok_or(Errno::EINVAL)?;
        self.offset = new_offset;
        Ok(new_offset)
    }

    /// Returns the i-node this open file description is operating on.
    #[must_use]
    pub fn inode(&self) -> &Rc<RefCell<Inode>> {
        &self.file
    }
}

/// State of a file descriptor.
#[derive(Clone, Debug)]
pub struct FdBody {
    /// Underlying open file description.
    pub open_file_description: Rc<RefCell<OpenFileDescription>>,
    /// Flags for this file descriptor
    pub flags: EnumSet<FdFlag>,
}

impl PartialEq for FdBody {
    fn eq(&self, rhs: &Self) -> bool {
        Rc::ptr_eq(&self.open_file_description, &rhs.open_file_description)
            && self.flags == rhs.flags
    }
}

impl Eq for FdBody {}

#[cfg(test)]
mod tests {
    use super::super::{Mode, PIPE_SIZE, WakerSet};
    use super::*;
    use assert_matches::assert_matches;
    use std::collections::VecDeque;

    #[test]
    fn regular_file_read_unreadable() {
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([]))),
            offset: 0,
            is_readable: false,
            is_writable: false,
            is_appending: false,
            is_nonblocking: false,
        };

        let mut buffer = [0];
        let result = open_file.read(&mut buffer);
        assert_eq!(result, Err(Errno::EBADF));
    }

    #[test]
    fn regular_file_read_more_than_content() {
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([1, 2, 3]))),
            offset: 1,
            is_readable: true,
            is_writable: false,
            is_appending: false,
            is_nonblocking: false,
        };

        let mut buffer = [0; 3];
        let result = open_file.read(&mut buffer);
        assert_eq!(result, Ok(2));
        assert_eq!(open_file.offset, 3);
        assert_eq!(buffer[..2], [2, 3]);
    }

    #[test]
    fn fifo_nonblocking_read_not_ready() {
        let fifo = Rc::new(RefCell::new(Inode {
            body: FileBody::Fifo {
                content: VecDeque::new(),
                readers: 1,
                writers: 1,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Mode::default(),
        }));
        let mut open_file = OpenFileDescription::new(
            fifo, /* offset */ 0, /* is_readable */ true, /* is_writable */ false,
            /* is_appending */ false, /* is_nonblocking */ true,
        );

        let mut buffer = [0; 4];
        let result = open_file.poll_read(&mut buffer, || unreachable!());
        assert_eq!(result, Poll::Ready(Err(Errno::EAGAIN)));
    }

    #[test]
    fn fifo_nonblocking_read_ready() {
        let fifo = Rc::new(RefCell::new(Inode {
            body: FileBody::Fifo {
                content: VecDeque::from([0, 1, 2, 3]),
                readers: 1,
                writers: 1,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Mode::default(),
        }));
        let mut open_file = OpenFileDescription::new(
            fifo, /* offset */ 0, /* is_readable */ true, /* is_writable */ false,
            /* is_appending */ false, /* is_nonblocking */ true,
        );

        let mut buffer = [0; 4];
        let result = open_file.poll_read(&mut buffer, || unreachable!());
        assert_eq!(result, Poll::Ready(Ok(4)));
        assert_eq!(buffer, [0, 1, 2, 3]);
    }

    #[test]
    fn regular_file_write_unwritable() {
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([]))),
            offset: 0,
            is_readable: false,
            is_writable: false,
            is_appending: false,
            is_nonblocking: false,
        };

        let result = open_file.write(&[0]);
        assert_eq!(result, Err(Errno::EBADF));
    }

    #[test]
    fn regular_file_write_more_than_content() {
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([1, 2, 3]))),
            offset: 1,
            is_readable: false,
            is_writable: true,
            is_appending: false,
            is_nonblocking: false,
        };

        let result = open_file.write(&[9, 8, 7, 6]);
        assert_eq!(result, Ok(4));
        assert_eq!(open_file.offset, 5);
        assert_matches!(
            &open_file.file.borrow().body,
            FileBody::Regular { content, .. } => {
                assert_eq!(content[..], [1, 9, 8, 7, 6]);
            }
        );
    }

    #[test]
    fn regular_file_write_appending() {
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([1, 2, 3]))),
            offset: 1,
            is_readable: false,
            is_writable: true,
            is_appending: true,
            is_nonblocking: false,
        };

        let result = open_file.write(&[4, 5]);
        assert_eq!(result, Ok(2));
        assert_eq!(open_file.offset, 5);
        assert_matches!(
            &open_file.file.borrow().body,
            FileBody::Regular { content, .. } => {
                assert_eq!(content[..], [1, 2, 3, 4, 5]);
            }
        );
    }

    #[test]
    fn fifo_nonblocking_write_not_ready() {
        let fifo = Rc::new(RefCell::new(Inode {
            body: FileBody::Fifo {
                content: VecDeque::from([0; PIPE_SIZE]),
                readers: 1,
                writers: 1,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Mode::default(),
        }));
        let mut open_file = OpenFileDescription::new(
            fifo, /* offset */ 0, /* is_readable */ false, /* is_writable */ true,
            /* is_appending */ false, /* is_nonblocking */ true,
        );

        let result = open_file.poll_write(&[0; 4], || unreachable!());
        assert_eq!(result, Poll::Ready(Err(Errno::EAGAIN)));
    }

    #[test]
    fn fifo_nonblocking_write_ready() {
        let fifo = Rc::new(RefCell::new(Inode {
            body: FileBody::Fifo {
                content: VecDeque::new(),
                readers: 1,
                writers: 1,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Mode::default(),
        }));
        let mut open_file = OpenFileDescription::new(
            fifo, /* offset */ 0, /* is_readable */ false, /* is_writable */ true,
            /* is_appending */ false, /* is_nonblocking */ true,
        );

        let result = open_file.poll_write(&[9; 4], || unreachable!());
        assert_eq!(result, Poll::Ready(Ok(4)));
    }

    #[test]
    fn poll_write_full_regular_file_returns_after_one_call() {
        // For a regular file, poll_write_full must not loop. Even though
        // FileBody::Regular always writes the whole buffer in one call, the
        // helper must not branch on FIFO-specific logic.
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([]))),
            offset: 0,
            is_readable: false,
            is_writable: true,
            is_appending: false,
            is_nonblocking: false,
        };
        let mut bytes_written = 0usize;
        let buffer = [1, 2, 3, 4, 5];
        let result = open_file.poll_write_full(&buffer, &mut bytes_written, || unreachable!());
        assert_eq!(result, Poll::Ready(Ok(5)));
        assert_eq!(bytes_written, 5);
        assert_matches!(
            &open_file.file.borrow().body,
            FileBody::Regular { content, .. } => {
                assert_eq!(content[..], [1, 2, 3, 4, 5]);
            }
        );
    }

    #[test]
    fn poll_write_full_blocking_fifo_loops_until_full() {
        // For a blocking FIFO, poll_write_full must keep calling poll_write
        // until either the buffer is exhausted or no more bytes fit (returning
        // Pending).
        let fifo = Rc::new(RefCell::new(Inode {
            body: FileBody::Fifo {
                content: VecDeque::new(),
                readers: 1,
                writers: 1,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Mode::default(),
        }));
        let mut open_file = OpenFileDescription::new(
            fifo, /* offset */ 0, /* is_readable */ false, /* is_writable */ true,
            /* is_appending */ false, /* is_nonblocking */ false,
        );

        // Write a buffer larger than the pipe capacity. The helper writes as
        // much as fits (PIPE_SIZE bytes) and then returns Pending.
        let buffer = [7u8; PIPE_SIZE + 1];
        let waker_holder: Rc<Cell<Option<Waker>>> = Rc::new(Cell::new(Some(Waker::noop().clone())));
        let mut bytes_written = 0usize;
        let result =
            open_file.poll_write_full(&buffer, &mut bytes_written, || Rc::downgrade(&waker_holder));
        assert_eq!(result, Poll::Pending);
        assert_eq!(bytes_written, PIPE_SIZE);
    }

    #[test]
    fn poll_write_full_nonblocking_fifo_returns_after_one_chunk() {
        // For a non-blocking FIFO, poll_write_full must not loop even if more
        // bytes could be written across multiple poll_write calls.
        let fifo = Rc::new(RefCell::new(Inode {
            body: FileBody::Fifo {
                content: VecDeque::new(),
                readers: 1,
                writers: 1,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Mode::default(),
        }));
        let mut open_file = OpenFileDescription::new(
            fifo, /* offset */ 0, /* is_readable */ false, /* is_writable */ true,
            /* is_appending */ false, /* is_nonblocking */ true,
        );

        let buffer = [3u8; PIPE_SIZE * 2];
        let mut bytes_written = 0usize;
        let result = open_file.poll_write_full(&buffer, &mut bytes_written, || unreachable!());
        // The first chunk fits entirely; the helper returns immediately rather
        // than calling poll_write again (which would return EAGAIN).
        assert_eq!(result, Poll::Ready(Ok(PIPE_SIZE)));
        assert_eq!(bytes_written, PIPE_SIZE);
    }

    #[test]
    fn regular_file_seek_from_start() {
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([]))),
            offset: 3,
            is_readable: true,
            is_writable: true,
            is_appending: false,
            is_nonblocking: false,
        };

        let result = open_file.seek(SeekFrom::Start(10));
        assert_eq!(result, Ok(10));
        assert_eq!(open_file.offset, 10);

        let result = open_file.seek(SeekFrom::Start(0));
        assert_eq!(result, Ok(0));
        assert_eq!(open_file.offset, 0);

        let result = open_file.seek(SeekFrom::Start(3));
        assert_eq!(result, Ok(3));
        assert_eq!(open_file.offset, 3);
    }

    #[test]
    fn regular_file_seek_from_current() {
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([]))),
            offset: 5,
            is_readable: true,
            is_writable: true,
            is_appending: false,
            is_nonblocking: false,
        };

        let result = open_file.seek(SeekFrom::Current(10));
        assert_eq!(result, Ok(15));
        assert_eq!(open_file.offset, 15);

        let result = open_file.seek(SeekFrom::Current(0));
        assert_eq!(result, Ok(15));
        assert_eq!(open_file.offset, 15);

        let result = open_file.seek(SeekFrom::Current(-5));
        assert_eq!(result, Ok(10));
        assert_eq!(open_file.offset, 10);

        let result = open_file.seek(SeekFrom::Current(-11));
        assert_eq!(result, Err(Errno::EINVAL));
        assert_eq!(open_file.offset, 10);
    }

    #[test]
    fn regular_file_seek_from_end() {
        let mut open_file = OpenFileDescription {
            file: Rc::new(RefCell::new(Inode::new([1, 2, 3]))),
            offset: 2,
            is_readable: true,
            is_writable: true,
            is_appending: false,
            is_nonblocking: false,
        };

        let result = open_file.seek(SeekFrom::End(7));
        assert_eq!(result, Ok(10));
        assert_eq!(open_file.offset, 10);

        let result = open_file.seek(SeekFrom::End(0));
        assert_eq!(result, Ok(3));
        assert_eq!(open_file.offset, 3);

        let result = open_file.seek(SeekFrom::End(-3));
        assert_eq!(result, Ok(0));
        assert_eq!(open_file.offset, 0);

        let result = open_file.seek(SeekFrom::End(-4));
        assert_eq!(result, Err(Errno::EINVAL));
        assert_eq!(open_file.offset, 0);
    }

    #[test]
    fn fifo_reader_drop() {
        let file = Rc::new(RefCell::new(Inode {
            body: FileBody::Fifo {
                content: VecDeque::new(),
                readers: 1,
                writers: 1,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Mode::default(),
        }));
        let open_file = OpenFileDescription {
            file: Rc::clone(&file),
            offset: 0,
            is_readable: true,
            is_writable: false,
            is_appending: false,
            is_nonblocking: false,
        };
        drop(open_file);

        assert_matches!(&file.borrow().body, FileBody::Fifo { readers, writers, .. } => {
            assert_eq!(*readers, 0);
            assert_eq!(*writers, 1);
        });
    }

    #[test]
    fn fifo_writer_drop() {
        let file = Rc::new(RefCell::new(Inode {
            body: FileBody::Fifo {
                content: VecDeque::new(),
                readers: 1,
                writers: 1,
                pending_open_wakers: WakerSet::new(),
                pending_read_wakers: WakerSet::new(),
                pending_write_wakers: WakerSet::new(),
            },
            permissions: Mode::default(),
        }));
        let open_file = OpenFileDescription {
            file: Rc::clone(&file),
            offset: 0,
            is_readable: false,
            is_writable: true,
            is_appending: false,
            is_nonblocking: false,
        };
        drop(open_file);

        assert_matches!(&file.borrow().body, FileBody::Fifo { readers, writers, .. } => {
            assert_eq!(*readers, 1);
            assert_eq!(*writers, 0);
        });
    }
}