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
use crate::handle::{Handle, HandleRights};
use crate::wasi::{self, types, Errno, Result, RightsExt};
use log::trace;
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::convert::TryInto;
use std::io;
use std::io::SeekFrom;
use std::path::{Path, PathBuf};
use std::rc::Rc;

pub enum VirtualDirEntry {
    Directory(HashMap<String, VirtualDirEntry>),
    File(Box<dyn FileContents>),
}

impl VirtualDirEntry {
    pub fn empty_directory() -> Self {
        Self::Directory(HashMap::new())
    }
}

/// Files and directories may be moved, and for implementation reasons retain a reference to their
/// parent Handle, so files that can be moved must provide an interface to update their parent
/// reference.
pub(crate) trait MovableFile {
    fn set_parent(&self, new_parent: Option<Box<dyn Handle>>);
}

pub trait FileContents {
    /// The implementation-defined maximum size of the store corresponding to a `FileContents`
    /// implementation.
    fn max_size(&self) -> types::Filesize;
    /// The current number of bytes this `FileContents` describes.
    fn size(&self) -> types::Filesize;
    /// Resize to hold `new_size` number of bytes, or error if this is not possible.
    fn resize(&mut self, new_size: types::Filesize) -> Result<()>;
    /// Write a list of `IoSlice` starting at `offset`. `offset` plus the total size of all `iovs`
    /// is guaranteed to not exceed `max_size`. Implementations must not indicate more bytes have
    /// been written than can be held by `iovs`.
    fn pwritev(&mut self, iovs: &[io::IoSlice], offset: types::Filesize) -> Result<usize>;
    /// Read from the file from `offset`, filling a list of `IoSlice`. The returend size must not
    /// be more than the capactiy of `iovs`, and must not exceed the limit reported by
    /// `self.max_size()`.
    fn preadv(&self, iovs: &mut [io::IoSliceMut], offset: types::Filesize) -> Result<usize>;
    /// Write contents from `buf` to this file starting at `offset`. `offset` plus the length of
    /// `buf` is guaranteed to not exceed `max_size`. Implementations must not indicate more bytes
    /// have been written than the size of `buf`.
    fn pwrite(&mut self, buf: &[u8], offset: types::Filesize) -> Result<usize>;
    /// Read from the file at `offset`, filling `buf`. The returned size must not be more than the
    /// capacity of `buf`, and `offset` plus the returned size must not exceed `self.max_size()`.
    fn pread(&self, buf: &mut [u8], offset: types::Filesize) -> Result<usize>;
}

impl FileContents for VecFileContents {
    fn max_size(&self) -> types::Filesize {
        std::usize::MAX as types::Filesize
    }

    fn size(&self) -> types::Filesize {
        self.content.len() as types::Filesize
    }

    fn resize(&mut self, new_size: types::Filesize) -> Result<()> {
        let new_size: usize = new_size.try_into().map_err(|_| Errno::Inval)?;
        self.content.resize(new_size, 0);
        Ok(())
    }

    fn preadv(&self, iovs: &mut [io::IoSliceMut], offset: types::Filesize) -> Result<usize> {
        let mut read_total = 0usize;
        for iov in iovs.iter_mut() {
            let read = self.pread(iov, offset)?;
            read_total = read_total.checked_add(read).expect("FileContents::preadv must not be called when reads could total to more bytes than the return value can hold");
        }
        Ok(read_total)
    }

    fn pwritev(&mut self, iovs: &[io::IoSlice], offset: types::Filesize) -> Result<usize> {
        let mut write_total = 0usize;
        for iov in iovs.iter() {
            let written = self.pwrite(iov, offset)?;
            write_total = write_total.checked_add(written).expect("FileContents::pwritev must not be called when writes could total to more bytes than the return value can hold");
        }
        Ok(write_total)
    }

    fn pread(&self, buf: &mut [u8], offset: types::Filesize) -> Result<usize> {
        trace!("     | pread(buf.len={}, offset={})", buf.len(), offset);
        let offset: usize = offset.try_into().map_err(|_| Errno::Inval)?;

        let data_remaining = self.content.len().saturating_sub(offset);

        let read_count = std::cmp::min(buf.len(), data_remaining);

        (&mut buf[..read_count]).copy_from_slice(&self.content[offset..][..read_count]);

        let res = Ok(read_count);
        trace!("     | pread={:?}", res);
        res
    }

    fn pwrite(&mut self, buf: &[u8], offset: types::Filesize) -> Result<usize> {
        let offset: usize = offset.try_into().map_err(|_| Errno::Inval)?;

        let write_end = offset.checked_add(buf.len()).ok_or(Errno::Fbig)?;

        if write_end > self.content.len() {
            self.content.resize(write_end, 0);
        }

        (&mut self.content[offset..][..buf.len()]).copy_from_slice(buf);

        Ok(buf.len())
    }
}

struct VecFileContents {
    content: Vec<u8>,
}

impl VecFileContents {
    fn new() -> Self {
        Self {
            content: Vec::new(),
        }
    }
}

/// An `InMemoryFile` is a shared handle to some underlying data. The relationship is analagous to
/// a filesystem wherein a file descriptor is one view into a possibly-shared underlying collection
/// of data and permissions on a filesystem.
pub struct InMemoryFile {
    rights: Cell<HandleRights>,
    cursor: Cell<types::Filesize>,
    parent: Rc<RefCell<Option<Box<dyn Handle>>>>,
    fd_flags: Cell<types::Fdflags>,
    data: Rc<RefCell<Box<dyn FileContents>>>,
}

impl InMemoryFile {
    pub fn memory_backed() -> Self {
        Self::new(Box::new(VecFileContents::new()))
    }

    pub fn new(contents: Box<dyn FileContents>) -> Self {
        let rights = HandleRights::new(
            types::Rights::regular_file_base(),
            types::Rights::regular_file_inheriting(),
        );
        let rights = Cell::new(rights);
        Self {
            rights,
            cursor: Cell::new(0),
            fd_flags: Cell::new(types::Fdflags::empty()),
            parent: Rc::new(RefCell::new(None)),
            data: Rc::new(RefCell::new(contents)),
        }
    }
}

impl MovableFile for InMemoryFile {
    fn set_parent(&self, new_parent: Option<Box<dyn Handle>>) {
        *self.parent.borrow_mut() = new_parent;
    }
}

impl Handle for InMemoryFile {
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn try_clone(&self) -> io::Result<Box<dyn Handle>> {
        Ok(Box::new(Self {
            rights: self.rights.clone(),
            cursor: Cell::new(0),
            fd_flags: self.fd_flags.clone(),
            parent: Rc::clone(&self.parent),
            data: Rc::clone(&self.data),
        }))
    }
    fn get_file_type(&self) -> types::Filetype {
        types::Filetype::RegularFile
    }
    fn get_rights(&self) -> HandleRights {
        self.rights.get()
    }
    fn set_rights(&self, rights: HandleRights) {
        self.rights.set(rights)
    }
    // FdOps
    fn advise(
        &self,
        _advice: types::Advice,
        _offset: types::Filesize,
        _len: types::Filesize,
    ) -> Result<()> {
        // we'll just ignore advice for now, unless it's totally invalid
        Ok(())
    }
    fn allocate(&self, offset: types::Filesize, len: types::Filesize) -> Result<()> {
        let new_limit = offset.checked_add(len).ok_or(Errno::Fbig)?;
        let mut data = self.data.borrow_mut();

        if new_limit > data.max_size() {
            return Err(Errno::Fbig);
        }

        if new_limit > data.size() {
            data.resize(new_limit)?;
        }

        Ok(())
    }
    fn fdstat_get(&self) -> Result<types::Fdflags> {
        Ok(self.fd_flags.get())
    }
    fn fdstat_set_flags(&self, fdflags: types::Fdflags) -> Result<()> {
        self.fd_flags.set(fdflags);
        Ok(())
    }
    fn filestat_get(&self) -> Result<types::Filestat> {
        let stat = types::Filestat {
            dev: 0,
            ino: 0,
            nlink: 0,
            size: self.data.borrow().size(),
            atim: 0,
            ctim: 0,
            mtim: 0,
            filetype: self.get_file_type(),
        };
        Ok(stat)
    }
    fn filestat_set_size(&self, st_size: types::Filesize) -> Result<()> {
        let mut data = self.data.borrow_mut();
        if st_size > data.max_size() {
            return Err(Errno::Fbig);
        }
        data.resize(st_size)
    }
    fn preadv(&self, buf: &mut [io::IoSliceMut], offset: types::Filesize) -> Result<usize> {
        self.data.borrow_mut().preadv(buf, offset)
    }
    fn pwritev(&self, buf: &[io::IoSlice], offset: types::Filesize) -> Result<usize> {
        self.data.borrow_mut().pwritev(buf, offset)
    }
    fn read_vectored(&self, iovs: &mut [io::IoSliceMut]) -> Result<usize> {
        trace!("read_vectored(iovs={:?})", iovs);
        trace!("     | *read_start={:?}", self.cursor.get());
        self.data.borrow_mut().preadv(iovs, self.cursor.get())
    }
    fn seek(&self, offset: SeekFrom) -> Result<types::Filesize> {
        let content_len = self.data.borrow().size();
        match offset {
            SeekFrom::Current(offset) => {
                let new_cursor = if offset < 0 {
                    self.cursor
                        .get()
                        .checked_sub(offset.wrapping_neg() as u64)
                        .ok_or(Errno::Inval)?
                } else {
                    self.cursor
                        .get()
                        .checked_add(offset as u64)
                        .ok_or(Errno::Inval)?
                };
                self.cursor.set(std::cmp::min(content_len, new_cursor));
            }
            SeekFrom::End(offset) => {
                // A negative offset from the end would be past the end of the file,
                let offset: u64 = offset.try_into().map_err(|_| Errno::Inval)?;
                self.cursor.set(content_len.saturating_sub(offset));
            }
            SeekFrom::Start(offset) => {
                // A negative offset from the end would be before the start of the file.
                let offset: u64 = offset.try_into().map_err(|_| Errno::Inval)?;
                self.cursor.set(std::cmp::min(content_len, offset));
            }
        }

        Ok(self.cursor.get())
    }
    fn write_vectored(&self, iovs: &[io::IoSlice]) -> Result<usize> {
        trace!("write_vectored(iovs={:?})", iovs);
        let mut data = self.data.borrow_mut();

        let append_mode = self.fd_flags.get().contains(&types::Fdflags::APPEND);
        trace!("     | fd_flags={}", self.fd_flags.get());

        // If this file is in append mode, we write to the end.
        let write_start = if append_mode {
            data.size()
        } else {
            self.cursor.get()
        };

        let max_size = iovs
            .iter()
            .map(|iov| {
                let cast_iovlen: types::Size = iov
                    .len()
                    .try_into()
                    .expect("iovec are bounded by wasi max sizes");
                cast_iovlen
            })
            .fold(Some(0u32), |len, iov| len.and_then(|x| x.checked_add(iov)))
            .expect("write_vectored will not be called with invalid iovs");

        if let Some(end) = write_start.checked_add(max_size as types::Filesize) {
            if end > data.max_size() {
                return Err(Errno::Fbig);
            }
        } else {
            return Err(Errno::Fbig);
        }

        trace!("     | *write_start={:?}", write_start);
        let written = data.pwritev(iovs, write_start)?;

        // If we are not appending, adjust the cursor appropriately for the write, too. This can't
        // overflow, as we checked against that before writing any data.
        if !append_mode {
            let update = self.cursor.get() + written as u64;
            self.cursor.set(update);
        }

        Ok(written)
    }
    // PathOps
    fn create_directory(&self, _path: &str) -> Result<()> {
        Err(Errno::Notdir)
    }
    fn openat(
        &self,
        path: &str,
        read: bool,
        write: bool,
        oflags: types::Oflags,
        fd_flags: types::Fdflags,
    ) -> Result<Box<dyn Handle>> {
        log::trace!(
            "InMemoryFile::openat(path={:?}, read={:?}, write={:?}, oflags={:?}, fd_flags={:?}",
            path,
            read,
            write,
            oflags,
            fd_flags
        );

        if oflags.contains(&types::Oflags::DIRECTORY) {
            log::trace!(
                "InMemoryFile::openat was passed oflags DIRECTORY, but {:?} is a file.",
                path
            );
            log::trace!("  return Notdir");
            return Err(Errno::Notdir);
        }

        if path == "." {
            return self.try_clone().map_err(Into::into);
        } else if path == ".." {
            match &*self.parent.borrow() {
                Some(file) => file.try_clone().map_err(Into::into),
                None => self.try_clone().map_err(Into::into),
            }
        } else {
            Err(Errno::Acces)
        }
    }
    fn link(
        &self,
        _old_path: &str,
        _new_handle: Box<dyn Handle>,
        _new_path: &str,
        _follow: bool,
    ) -> Result<()> {
        Err(Errno::Notdir)
    }
    fn readlink(&self, _path: &str, _buf: &mut [u8]) -> Result<usize> {
        Err(Errno::Notdir)
    }
    fn readlinkat(&self, _path: &str) -> Result<String> {
        Err(Errno::Notdir)
    }
    fn rename(&self, _old_path: &str, _new_handle: Box<dyn Handle>, _new_path: &str) -> Result<()> {
        Err(Errno::Notdir)
    }
    fn remove_directory(&self, _path: &str) -> Result<()> {
        Err(Errno::Notdir)
    }
    fn symlink(&self, _old_path: &str, _new_path: &str) -> Result<()> {
        Err(Errno::Notdir)
    }
    fn unlink_file(&self, _path: &str) -> Result<()> {
        Err(Errno::Notdir)
    }
}

/// A clonable read/write directory.
pub struct VirtualDir {
    rights: Cell<HandleRights>,
    writable: bool,
    // All copies of this `VirtualDir` must share `parent`, and changes in one copy's `parent`
    // must be reflected in all handles, so they share `Rc` of an underlying `parent`.
    parent: Rc<RefCell<Option<Box<dyn Handle>>>>,
    entries: Rc<RefCell<HashMap<PathBuf, Box<dyn Handle>>>>,
}

impl VirtualDir {
    pub fn new(writable: bool) -> Self {
        let rights = HandleRights::new(
            types::Rights::directory_base(),
            types::Rights::directory_inheriting(),
        );
        let rights = Cell::new(rights);
        Self {
            rights,
            writable,
            parent: Rc::new(RefCell::new(None)),
            entries: Rc::new(RefCell::new(HashMap::new())),
        }
    }

    #[allow(dead_code)]
    pub fn with_dir<P: AsRef<Path>>(mut self, dir: Self, path: P) -> Self {
        self.add_dir(dir, path);
        self
    }

    #[allow(dead_code)]
    pub fn add_dir<P: AsRef<Path>>(&mut self, dir: Self, path: P) {
        let entry = Box::new(dir);
        entry.set_parent(Some(self.try_clone().expect("can clone self")));
        self.entries
            .borrow_mut()
            .insert(path.as_ref().to_owned(), entry);
    }

    #[allow(dead_code)]
    pub fn with_file<P: AsRef<Path>>(mut self, content: Box<dyn FileContents>, path: P) -> Self {
        self.add_file(content, path);
        self
    }

    #[allow(dead_code)]
    pub fn add_file<P: AsRef<Path>>(&mut self, content: Box<dyn FileContents>, path: P) {
        let entry = Box::new(InMemoryFile::new(content));
        entry.set_parent(Some(self.try_clone().expect("can clone self")));
        self.entries
            .borrow_mut()
            .insert(path.as_ref().to_owned(), entry);
    }
}

impl MovableFile for VirtualDir {
    fn set_parent(&self, new_parent: Option<Box<dyn Handle>>) {
        *self.parent.borrow_mut() = new_parent;
    }
}

const SELF_DIR_COOKIE: u32 = 0;
const PARENT_DIR_COOKIE: u32 = 1;

// This MUST be the number of constants above. This limit is used to prevent allocation of files
// that would wrap and be mapped to the same dir cookies as `self` or `parent`.
const RESERVED_ENTRY_COUNT: u32 = 2;

impl Handle for VirtualDir {
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn try_clone(&self) -> io::Result<Box<dyn Handle>> {
        Ok(Box::new(Self {
            rights: self.rights.clone(),
            writable: self.writable,
            parent: Rc::clone(&self.parent),
            entries: Rc::clone(&self.entries),
        }))
    }
    fn get_file_type(&self) -> types::Filetype {
        types::Filetype::Directory
    }
    fn get_rights(&self) -> HandleRights {
        self.rights.get()
    }
    fn set_rights(&self, rights: HandleRights) {
        self.rights.set(rights)
    }
    // FdOps
    fn filestat_get(&self) -> Result<types::Filestat> {
        let stat = types::Filestat {
            dev: 0,
            ino: 0,
            nlink: 0,
            size: 0,
            atim: 0,
            ctim: 0,
            mtim: 0,
            filetype: self.get_file_type(),
        };
        Ok(stat)
    }
    fn readdir(
        &self,
        cookie: types::Dircookie,
    ) -> Result<Box<dyn Iterator<Item = Result<(types::Dirent, String)>>>> {
        struct VirtualDirIter {
            start: u32,
            entries: Rc<RefCell<HashMap<PathBuf, Box<dyn Handle>>>>,
        }
        impl Iterator for VirtualDirIter {
            type Item = Result<(types::Dirent, String)>;

            fn next(&mut self) -> Option<Self::Item> {
                log::trace!("VirtualDirIter::next continuing from {}", self.start);
                if self.start == SELF_DIR_COOKIE {
                    self.start += 1;
                    let name = ".".to_owned();
                    let dirent = types::Dirent {
                        d_next: self.start as u64,
                        d_ino: 0,
                        d_namlen: name.len() as _,
                        d_type: types::Filetype::Directory,
                    };
                    return Some(Ok((dirent, name)));
                }
                if self.start == PARENT_DIR_COOKIE {
                    self.start += 1;
                    let name = "..".to_owned();
                    let dirent = types::Dirent {
                        d_next: self.start as u64,
                        d_ino: 0,
                        d_namlen: name.len() as _,
                        d_type: types::Filetype::Directory,
                    };
                    return Some(Ok((dirent, name)));
                }

                let entries = self.entries.borrow();

                // Adjust `start` to be an appropriate number of HashMap entries.
                let start = self.start - RESERVED_ENTRY_COUNT;
                if start as usize >= entries.len() {
                    return None;
                }

                self.start += 1;

                let (path, file) = entries
                    .iter()
                    .skip(start as usize)
                    .next()
                    .expect("seeked less than the length of entries");

                let name = path
                    .to_str()
                    .expect("wasi paths are valid utf8 strings")
                    .to_owned();
                let dirent = || -> Result<types::Dirent> {
                    let dirent = types::Dirent {
                        d_namlen: name.len().try_into()?,
                        d_type: file.get_file_type(),
                        d_ino: 0,
                        d_next: self.start as u64,
                    };
                    Ok(dirent)
                };
                Some(dirent().map(|dirent| (dirent, name)))
            }
        }
        let cookie = match cookie.try_into() {
            Ok(cookie) => cookie,
            Err(_) => {
                // Cookie is larger than u32. it doesn't seem like there's an explicit error
                // condition in POSIX or WASI, so just start from the start?
                0
            }
        };
        Ok(Box::new(VirtualDirIter {
            start: cookie,
            entries: Rc::clone(&self.entries),
        }))
    }
    // PathOps
    fn create_directory(&self, path: &str) -> Result<()> {
        let mut entries = self.entries.borrow_mut();
        match entries.entry(PathBuf::from(path)) {
            Entry::Occupied(_) => Err(Errno::Exist),
            Entry::Vacant(v) => {
                if self.writable {
                    let new_dir = Box::new(Self::new(true));
                    new_dir.set_parent(Some(self.try_clone()?));
                    v.insert(new_dir);
                    Ok(())
                } else {
                    Err(Errno::Acces)
                }
            }
        }
    }
    fn filestat_get_at(&self, path: &str, _follow: bool) -> Result<types::Filestat> {
        let stat = self
            .openat(
                path,
                false,
                false,
                types::Oflags::empty(),
                types::Fdflags::empty(),
            )?
            .filestat_get()?;
        Ok(stat)
    }
    fn filestat_set_times_at(
        &self,
        path: &str,
        atim: types::Timestamp,
        mtim: types::Timestamp,
        fst_flags: types::Fstflags,
        _follow: bool,
    ) -> Result<()> {
        self.openat(
            path,
            false,
            false,
            types::Oflags::empty(),
            types::Fdflags::empty(),
        )?
        .filestat_set_times(atim, mtim, fst_flags)?;
        Ok(())
    }
    fn openat(
        &self,
        path: &str,
        read: bool,
        write: bool,
        oflags: types::Oflags,
        fd_flags: types::Fdflags,
    ) -> Result<Box<dyn Handle>> {
        log::trace!(
            "VirtualDir::openat(path={:?}, read={:?}, write={:?}, oflags={:?}, fd_flags={:?}",
            path,
            read,
            write,
            oflags,
            fd_flags
        );

        if path == "." {
            return self.try_clone().map_err(Into::into);
        } else if path == ".." {
            match &*self.parent.borrow() {
                Some(file) => {
                    return file.try_clone().map_err(Into::into);
                }
                None => {
                    return self.try_clone().map_err(Into::into);
                }
            }
        }

        // openat may have been passed a path with a trailing slash, but files are mapped to paths
        // with trailing slashes normalized out.
        let file_name = Path::new(path).file_name().ok_or(Errno::Inval)?;
        let mut entries = self.entries.borrow_mut();
        let entry_count = entries.len();
        match entries.entry(Path::new(file_name).to_path_buf()) {
            Entry::Occupied(e) => {
                let creat_excl_mask = types::Oflags::CREAT | types::Oflags::EXCL;
                if (oflags & creat_excl_mask) == creat_excl_mask {
                    log::trace!("VirtualDir::openat was passed oflags CREAT|EXCL, but the file {:?} exists.", file_name);
                    log::trace!("  return Exist");
                    return Err(Errno::Exist);
                }

                if oflags.contains(&types::Oflags::DIRECTORY)
                    && e.get().get_file_type() != types::Filetype::Directory
                {
                    log::trace!(
                        "VirtualDir::openat was passed oflags DIRECTORY, but {:?} is a file.",
                        file_name
                    );
                    log::trace!("  return Notdir");
                    return Err(Errno::Notdir);
                }

                e.get().try_clone().map_err(Into::into)
            }
            Entry::Vacant(v) => {
                if self.writable {
                    // Enforce a hard limit at `u32::MAX - 2` files.
                    // This is to have a constant limit (rather than target-dependent limit we
                    // would have with `usize`. The limit is the full `u32` range minus two so we
                    // can reserve "self" and "parent" cookie values.
                    if entry_count >= (std::u32::MAX - RESERVED_ENTRY_COUNT) as usize {
                        return Err(Errno::Nospc);
                    }

                    log::trace!("VirtualDir::openat creating an InMemoryFile named {}", path);

                    let file = Box::new(InMemoryFile::memory_backed());
                    file.fd_flags.set(fd_flags);
                    file.set_parent(Some(self.try_clone().expect("can clone self")));
                    v.insert(file).try_clone().map_err(Into::into)
                } else {
                    Err(Errno::Acces)
                }
            }
        }
    }
    fn readlinkat(&self, _path: &str) -> Result<String> {
        // Files are not symbolic links or directories, faithfully report Notdir.
        Err(Errno::Notdir)
    }
    fn remove_directory(&self, path: &str) -> Result<()> {
        let trimmed_path = path.trim_end_matches('/');
        let mut entries = self.entries.borrow_mut();
        match entries.entry(Path::new(trimmed_path).to_path_buf()) {
            Entry::Occupied(e) => {
                // first, does this name a directory?
                if e.get().get_file_type() != types::Filetype::Directory {
                    return Err(Errno::Notdir);
                }

                // Okay, but is the directory empty?
                let iter = e.get().readdir(wasi::DIRCOOKIE_START)?;
                if iter.skip(RESERVED_ENTRY_COUNT as usize).next().is_some() {
                    return Err(Errno::Notempty);
                }

                // Alright, it's an empty directory. We can remove it.
                let removed = e.remove_entry();

                // TODO refactor
                // And sever the file's parent ref to avoid Rc cycles.
                if let Some(dir) = removed.1.as_any().downcast_ref::<Self>() {
                    dir.set_parent(None);
                } else if let Some(file) = removed.1.as_any().downcast_ref::<InMemoryFile>() {
                    file.set_parent(None);
                } else {
                    panic!("neither VirtualDir nor InMemoryFile");
                }

                Ok(())
            }
            Entry::Vacant(_) => {
                log::trace!(
                    "VirtualDir::remove_directory failed to remove {}, no such entry",
                    trimmed_path
                );
                Err(Errno::Noent)
            }
        }
    }
    fn unlink_file(&self, path: &str) -> Result<()> {
        let trimmed_path = path.trim_end_matches('/');

        // Special case: we may be unlinking this directory itself if path is `"."`. In that case,
        // fail with Isdir, since this is a directory. Alternatively, we may be unlinking `".."`,
        // which is bound the same way, as this is by definition contained in a directory.
        if trimmed_path == "." || trimmed_path == ".." {
            return Err(Errno::Isdir);
        }

        let mut entries = self.entries.borrow_mut();
        match entries.entry(Path::new(trimmed_path).to_path_buf()) {
            Entry::Occupied(e) => {
                // Directories must be removed through `remove_directory`, not `unlink_file`.
                if e.get().get_file_type() == types::Filetype::Directory {
                    return Err(Errno::Isdir);
                }

                let removed = e.remove_entry();

                // TODO refactor
                // Sever the file's parent ref to avoid Rc cycles.
                if let Some(dir) = removed.1.as_any().downcast_ref::<Self>() {
                    dir.set_parent(None);
                } else if let Some(file) = removed.1.as_any().downcast_ref::<InMemoryFile>() {
                    file.set_parent(None);
                } else {
                    panic!("neither VirtualDir nor InMemoryFile");
                }

                Ok(())
            }
            Entry::Vacant(_) => {
                log::trace!(
                    "VirtualDir::unlink_file failed to remove {}, no such entry",
                    trimmed_path
                );
                Err(Errno::Noent)
            }
        }
    }
}