1use std::any::Any;
2use std::collections::BTreeMap;
3use std::convert::BoundedCastFromInt;
4use std::io::{ErrorKind, IsTerminal, Read, Seek, SeekFrom, Write};
5use std::marker::CoercePointee;
6use std::ops::Deref;
7use std::rc::{Rc, Weak};
8use std::{fs, io};
9
10use rustc_abi::Size;
11
12use crate::shims::unix::UnixFileDescription;
13use crate::*;
14
15pub type FdNum = i32;
17
18pub const FD_LIMIT: FdNum = 524288; pub const BIG_ACCESS: u64 = 8 * 1024;
24
25#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
30pub struct FdId(usize);
31
32impl FdId {
33 pub fn to_usize(self) -> usize {
34 self.0
35 }
36
37 pub fn new_unchecked(id: usize) -> Self {
39 Self(id)
40 }
41}
42
43#[derive(Debug, Clone)]
44struct FdIdWith<T: ?Sized> {
45 id: FdId,
46 inner: T,
47}
48
49#[repr(transparent)]
52#[derive(CoercePointee, Debug)]
53pub struct FileDescriptionRef<T: ?Sized>(Rc<FdIdWith<T>>);
55
56impl<T: ?Sized> Clone for FileDescriptionRef<T> {
57 fn clone(&self) -> Self {
58 FileDescriptionRef(self.0.clone())
59 }
60}
61
62impl<T: ?Sized> Deref for FileDescriptionRef<T> {
63 type Target = T;
64 fn deref(&self) -> &T {
65 &self.0.inner
66 }
67}
68
69impl<T: ?Sized> FileDescriptionRef<T> {
70 pub fn id(&self) -> FdId {
71 self.0.id
72 }
73}
74
75impl<T: ?Sized> PartialEq for FileDescriptionRef<T> {
76 fn eq(&self, other: &Self) -> bool {
77 self.0.id == other.0.id
78 }
79}
80
81impl<T: ?Sized> Eq for FileDescriptionRef<T> {}
82
83#[derive(Debug)]
85pub struct WeakFileDescriptionRef<T: ?Sized>(Weak<FdIdWith<T>>);
86
87impl<T: ?Sized> Clone for WeakFileDescriptionRef<T> {
88 fn clone(&self) -> Self {
89 WeakFileDescriptionRef(self.0.clone())
90 }
91}
92
93impl<T: ?Sized> FileDescriptionRef<T> {
94 pub fn downgrade(this: &Self) -> WeakFileDescriptionRef<T> {
95 WeakFileDescriptionRef(Rc::downgrade(&this.0))
96 }
97}
98
99impl<T: ?Sized> WeakFileDescriptionRef<T> {
100 pub fn upgrade(&self) -> Option<FileDescriptionRef<T>> {
101 self.0.upgrade().map(FileDescriptionRef)
102 }
103
104 pub fn is_closed(&self) -> bool {
107 self.0.strong_count() == 0
108 }
109}
110
111impl<T> VisitProvenance for FileDescriptionRef<T> {
112 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
113 }
115}
116
117pub trait FileDescriptionExt: 'static {
121 fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any>;
122}
123
124impl<T: FileDescription + 'static> FileDescriptionExt for T {
125 fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any> {
126 self.0
127 }
128}
129
130pub type DynFileDescriptionRef = FileDescriptionRef<dyn FileDescription>;
131pub type WeakDynFileDescriptionRef = WeakFileDescriptionRef<dyn FileDescription>;
132
133impl FileDescriptionRef<dyn FileDescription> {
134 pub fn downcast<T: FileDescription + 'static>(self) -> Option<FileDescriptionRef<T>> {
135 let inner = self.into_rc_any().downcast::<FdIdWith<T>>().ok()?;
136 Some(FileDescriptionRef(inner))
137 }
138}
139
140pub trait FileDescription: std::fmt::Debug + FileDescriptionExt {
142 fn name(&self) -> &'static str;
143
144 fn read<'tcx>(
151 self: FileDescriptionRef<Self>,
152 _communicate_allowed: bool,
153 _ptr: Pointer,
154 _len: u64,
155 _ecx: &mut MiriInterpCx<'tcx>,
156 _finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
157 ) -> InterpResult<'tcx> {
158 throw_unsup_format!("cannot read from {}", self.name());
159 }
160
161 fn write<'tcx>(
168 self: FileDescriptionRef<Self>,
169 _communicate_allowed: bool,
170 _ptr: Pointer,
171 _len: u64,
172 _ecx: &mut MiriInterpCx<'tcx>,
173 _finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
174 ) -> InterpResult<'tcx> {
175 throw_unsup_format!("cannot write to {}", self.name());
176 }
177
178 fn short_fd_operations(&self) -> bool {
180 false
182 }
183
184 fn seek<'tcx>(
187 &self,
188 _communicate_allowed: bool,
189 _offset: SeekFrom,
190 ) -> InterpResult<'tcx, io::Result<u64>> {
191 throw_unsup_format!("cannot seek on {}", self.name());
192 }
193
194 fn metadata<'tcx>(
199 &self,
200 _communicate_allowed: bool,
201 ) -> InterpResult<'tcx, Either<io::Result<fs::Metadata>, &'static str>> {
202 throw_unsup_format!("obtaining metadata is not supported on {}", self.name());
203 }
204
205 fn is_tty(&self, _communicate_allowed: bool) -> bool {
206 false
209 }
210
211 fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
214 panic!("Not a unix file description: {}", self.name());
215 }
216
217 fn readiness_watched(&self) -> Option<&ReadinessWatched> {
219 None
220 }
221
222 fn readiness(&self) -> Readiness {
224 panic!("FD type {} implements `readiness_watched` but not `readiness`", self.name());
225 }
226}
227
228#[derive(Debug)]
229pub struct Stdin {
230 stdin: io::Stdin,
231 watched: ReadinessWatched,
232}
233
234impl Stdin {
235 fn new() -> Self {
236 Self { stdin: io::stdin(), watched: ReadinessWatched::default() }
237 }
238}
239
240impl FileDescription for Stdin {
241 fn name(&self) -> &'static str {
242 "stdin"
243 }
244
245 fn read<'tcx>(
246 self: FileDescriptionRef<Self>,
247 communicate_allowed: bool,
248 ptr: Pointer,
249 len: u64,
250 ecx: &mut MiriInterpCx<'tcx>,
251 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
252 ) -> InterpResult<'tcx> {
253 if !communicate_allowed {
254 helpers::isolation_abort_error("`read` from stdin")?;
256 }
257
258 let result = ecx.read_from_host(ptr, len, |buf| (&mut &self.stdin).read(buf))?;
260 finish.call(ecx, result)
261 }
262
263 fn metadata<'tcx>(
264 &self,
265 communicate_allowed: bool,
266 ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
267 let ftype = if self.is_tty(communicate_allowed) { "S_IFCHR" } else { "S_IFIFO" };
268 interp_ok(Either::Right(ftype))
269 }
270
271 fn is_tty(&self, communicate_allowed: bool) -> bool {
272 !communicate_allowed || self.stdin.is_terminal()
274 }
275
276 fn readiness_watched(&self) -> Option<&ReadinessWatched> {
277 Some(&self.watched)
278 }
279
280 fn readiness(&self) -> Readiness {
281 let mut readiness = Readiness::EMPTY;
284 readiness.readable = true;
285 readiness.writable = true;
286 readiness
287 }
288
289 fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
290 self
291 }
292}
293
294#[derive(Debug)]
295pub struct Stdout {
296 stdout: io::Stdout,
297 watched: ReadinessWatched,
298}
299
300impl Stdout {
301 fn new() -> Self {
302 Self { stdout: io::stdout(), watched: ReadinessWatched::default() }
303 }
304}
305
306impl FileDescription for Stdout {
307 fn name(&self) -> &'static str {
308 "stdout"
309 }
310
311 fn write<'tcx>(
312 self: FileDescriptionRef<Self>,
313 _communicate_allowed: bool,
314 ptr: Pointer,
315 len: u64,
316 ecx: &mut MiriInterpCx<'tcx>,
317 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
318 ) -> InterpResult<'tcx> {
319 let result = ecx.write_to_host(ptr, len, |buf| (&self.stdout).write(buf))?;
321 io::stdout().flush().unwrap();
327
328 finish.call(ecx, result)
329 }
330
331 fn metadata<'tcx>(
332 &self,
333 communicate_allowed: bool,
334 ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
335 let ftype = if self.is_tty(communicate_allowed) { "S_IFCHR" } else { "S_IFIFO" };
336 interp_ok(Either::Right(ftype))
337 }
338
339 fn is_tty(&self, communicate_allowed: bool) -> bool {
340 !communicate_allowed || self.stdout.is_terminal()
342 }
343
344 fn readiness_watched(&self) -> Option<&ReadinessWatched> {
345 Some(&self.watched)
346 }
347
348 fn readiness(&self) -> Readiness {
349 let mut readiness = Readiness::EMPTY;
351 readiness.writable = true;
352 readiness
353 }
354
355 fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
356 self
357 }
358}
359
360#[derive(Debug)]
361pub struct Stderr {
362 stderr: io::Stderr,
363 watched: ReadinessWatched,
364}
365
366impl Stderr {
367 fn new() -> Self {
368 Self { stderr: io::stderr(), watched: ReadinessWatched::default() }
369 }
370}
371
372impl FileDescription for Stderr {
373 fn name(&self) -> &'static str {
374 "stderr"
375 }
376
377 fn write<'tcx>(
378 self: FileDescriptionRef<Self>,
379 _communicate_allowed: bool,
380 ptr: Pointer,
381 len: u64,
382 ecx: &mut MiriInterpCx<'tcx>,
383 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
384 ) -> InterpResult<'tcx> {
385 let result = ecx.write_to_host(ptr, len, |buf| (&self.stderr).write(buf))?;
387 finish.call(ecx, result)
389 }
390
391 fn metadata<'tcx>(
392 &self,
393 communicate_allowed: bool,
394 ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
395 let ftype = if self.is_tty(communicate_allowed) { "S_IFCHR" } else { "S_IFIFO" };
396 interp_ok(Either::Right(ftype))
397 }
398
399 fn is_tty(&self, communicate_allowed: bool) -> bool {
400 !communicate_allowed || self.stderr.is_terminal()
402 }
403
404 fn readiness_watched(&self) -> Option<&ReadinessWatched> {
405 Some(&self.watched)
406 }
407
408 fn readiness(&self) -> Readiness {
409 let mut readiness = Readiness::EMPTY;
411 readiness.writable = true;
412 readiness
413 }
414
415 fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
416 self
417 }
418}
419
420#[derive(Debug)]
422pub struct NullOutput {
423 watched: ReadinessWatched,
424}
425
426impl NullOutput {
427 fn new() -> Self {
428 Self { watched: ReadinessWatched::default() }
429 }
430}
431
432impl FileDescription for NullOutput {
433 fn name(&self) -> &'static str {
434 "null output"
435 }
436
437 fn write<'tcx>(
438 self: FileDescriptionRef<Self>,
439 _communicate_allowed: bool,
440 _ptr: Pointer,
441 len: u64,
442 ecx: &mut MiriInterpCx<'tcx>,
443 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
444 ) -> InterpResult<'tcx> {
445 finish.call(ecx, Ok(len))
447 }
448
449 fn metadata<'tcx>(
450 &self,
451 _communicate_allowed: bool,
452 ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
453 interp_ok(Either::Right("S_IFIFO"))
454 }
455
456 fn readiness_watched(&self) -> Option<&ReadinessWatched> {
457 Some(&self.watched)
458 }
459
460 fn readiness(&self) -> Readiness {
461 let mut readiness = Readiness::EMPTY;
463 readiness.writable = true;
464 readiness
465 }
466
467 fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
468 self
469 }
470}
471
472#[derive(Debug)]
473pub struct FileHandle {
474 pub(crate) file: fs::File,
475 pub(crate) file_type: fs::FileType,
476 pub(crate) readable: bool,
477 pub(crate) writable: bool,
478 pub(crate) append: bool,
479}
480
481impl FileDescription for FileHandle {
482 fn name(&self) -> &'static str {
483 "file"
484 }
485
486 fn read<'tcx>(
487 self: FileDescriptionRef<Self>,
488 communicate_allowed: bool,
489 ptr: Pointer,
490 len: u64,
491 ecx: &mut MiriInterpCx<'tcx>,
492 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
493 ) -> InterpResult<'tcx> {
494 assert!(communicate_allowed, "isolation should have prevented even opening a file");
495
496 if !self.readable {
497 let err = if ecx.target_os_is_unix() {
499 LibcError("EBADF")
500 } else {
501 ErrorKind::PermissionDenied.into()
502 };
503 return finish.call(ecx, Err(err));
504 }
505
506 let mut file = &self.file;
507 let result = ecx.read_from_host(ptr, len, |buf| file.read(buf))?;
508 finish.call(ecx, result)
509 }
510
511 fn write<'tcx>(
512 self: FileDescriptionRef<Self>,
513 communicate_allowed: bool,
514 ptr: Pointer,
515 len: u64,
516 ecx: &mut MiriInterpCx<'tcx>,
517 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
518 ) -> InterpResult<'tcx> {
519 assert!(communicate_allowed, "isolation should have prevented even opening a file");
520
521 if !self.writable {
522 let err = if ecx.target_os_is_unix() {
524 LibcError("EBADF")
525 } else {
526 ErrorKind::PermissionDenied.into()
527 };
528 return finish.call(ecx, Err(err));
529 }
530 let result = ecx.write_to_host(ptr, len, |buf| (&self.file).write(buf))?;
531 finish.call(ecx, result)
532 }
533
534 fn seek<'tcx>(
535 &self,
536 communicate_allowed: bool,
537 offset: SeekFrom,
538 ) -> InterpResult<'tcx, io::Result<u64>> {
539 assert!(communicate_allowed, "isolation should have prevented even opening a file");
540 interp_ok((&mut &self.file).seek(offset))
541 }
542
543 fn metadata<'tcx>(
544 &self,
545 communicate_allowed: bool,
546 ) -> InterpResult<'tcx, Either<io::Result<fs::Metadata>, &'static str>> {
547 assert!(communicate_allowed);
548 interp_ok(Either::Left(
549 self.file.metadata().inspect(|m| assert_eq!(m.file_type(), self.file_type)),
550 ))
551 }
552
553 fn is_tty(&self, communicate_allowed: bool) -> bool {
554 assert!(communicate_allowed);
555 self.file.is_terminal()
556 }
557
558 fn short_fd_operations(&self) -> bool {
559 self.file_type.is_file()
563 }
564
565 fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
566 self
567 }
568}
569
570#[derive(Debug)]
571pub struct DirHandle {
572 pub(super) dir: fs::Dir,
573}
574
575impl FileDescription for DirHandle {
576 fn name(&self) -> &'static str {
577 "directory"
578 }
579
580 fn metadata<'tcx>(
581 &self,
582 communicate_allowed: bool,
583 ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
584 assert!(communicate_allowed);
585
586 interp_ok(Either::Left(self.dir.self_metadata()))
587 }
588
589 fn read<'tcx>(
590 self: FileDescriptionRef<Self>,
591 _communicate_allowed: bool,
592 _ptr: Pointer,
593 _len: u64,
594 ecx: &mut MiriInterpCx<'tcx>,
595 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
596 ) -> InterpResult<'tcx> {
597 if ecx.target_os_is_unix() {
598 finish.call(ecx, Err(LibcError("EISDIR")))
599 } else {
600 throw_unsup_format!("reading directories is not supported on this target");
602 }
603 }
604
605 fn write<'tcx>(
606 self: FileDescriptionRef<Self>,
607 _communicate_allowed: bool,
608 _ptr: Pointer,
609 _len: u64,
610 ecx: &mut MiriInterpCx<'tcx>,
611 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
612 ) -> InterpResult<'tcx> {
613 if ecx.target_os_is_unix() {
614 finish.call(ecx, Err(LibcError("EBADF")))
616 } else {
617 throw_unsup_format!("writing directories is not supported on this target");
619 }
620 }
621
622 fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
623 self
624 }
625}
626
627#[derive(Debug)]
629pub struct FdTable {
630 fds: BTreeMap<FdNum, DynFileDescriptionRef>,
631 next_file_description_id: FdId,
633}
634
635impl VisitProvenance for FdTable {
636 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
637 }
639}
640
641impl FdTable {
642 fn new() -> Self {
643 FdTable { fds: BTreeMap::new(), next_file_description_id: FdId(0) }
644 }
645 pub(crate) fn init(mute_stdout_stderr: bool) -> FdTable {
646 let mut fds = FdTable::new();
647 fds.insert_new(Stdin::new());
648 if mute_stdout_stderr {
649 assert_eq!(fds.insert_new(NullOutput::new()).unwrap(), 1);
650 assert_eq!(fds.insert_new(NullOutput::new()).unwrap(), 2);
651 } else {
652 assert_eq!(fds.insert_new(Stdout::new()).unwrap(), 1);
653 assert_eq!(fds.insert_new(Stderr::new()).unwrap(), 2);
654 }
655 fds
656 }
657
658 pub fn new_ref<T: FileDescription>(&mut self, fd: T) -> FileDescriptionRef<T> {
659 let file_handle =
660 FileDescriptionRef(Rc::new(FdIdWith { id: self.next_file_description_id, inner: fd }));
661 self.next_file_description_id = FdId(self.next_file_description_id.0.strict_add(1));
662 file_handle
663 }
664
665 pub fn fd_num_valid(fd_num: FdNum) -> bool {
666 (0..FD_LIMIT).contains(&fd_num)
667 }
668
669 pub fn insert_new(&mut self, fd: impl FileDescription) -> Option<FdNum> {
671 let fd_ref = self.new_ref(fd);
672 self.insert(fd_ref)
673 }
674
675 pub fn insert(&mut self, fd_ref: DynFileDescriptionRef) -> Option<FdNum> {
677 self.insert_with_min_num(fd_ref, 0)
678 }
679
680 pub fn insert_with_min_num(
682 &mut self,
683 file_handle: DynFileDescriptionRef,
684 min_fd_num: FdNum,
685 ) -> Option<FdNum> {
686 let mut candidate = min_fd_num;
687 for (&fd_num, _) in self.fds.range(min_fd_num..) {
688 if fd_num == candidate {
689 candidate = candidate.strict_add(1);
691 } else {
692 break;
694 }
695 }
696 if !Self::fd_num_valid(candidate) {
701 return None;
702 }
703
704 self.fds.try_insert(candidate, file_handle).unwrap();
705 Some(candidate)
706 }
707
708 pub fn get(&self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
709 let fd = self.fds.get(&fd_num)?;
710 Some(fd.clone())
711 }
712
713 pub fn remove(&mut self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
714 self.fds.remove(&fd_num)
715 }
716
717 pub fn is_fd_num(&self, fd_num: FdNum) -> bool {
718 self.fds.contains_key(&fd_num)
719 }
720}
721
722impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
723pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
724 fn read_from_host(
727 &mut self,
728 ptr: Pointer,
729 len: u64,
730 read_cb: impl FnOnce(&mut [u8]) -> io::Result<usize>,
731 ) -> InterpResult<'tcx, Result<u64, IoError>> {
732 let ecx = self.eval_context_mut();
733
734 let len = usize::saturating_cast_from(len);
735 let mut bytes = vec![0; len];
736 let result = read_cb(&mut bytes);
737 match result {
738 Ok(read_size) => {
739 ecx.write_bytes_ptr(ptr, bytes[..read_size].iter().copied())?;
743 interp_ok(Ok(read_size.to_u64()))
744 }
745 Err(e) => interp_ok(Err(IoError::HostError(e))),
746 }
747 }
748
749 fn write_to_host(
751 &self,
752 ptr: Pointer,
753 len: u64,
754 write_cb: impl FnOnce(&[u8]) -> io::Result<usize>,
755 ) -> InterpResult<'tcx, Result<u64, IoError>> {
756 let ecx = self.eval_context_ref();
757
758 let len = usize::saturating_cast_from(len);
759 let bytes = ecx.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
760 let result = write_cb(bytes);
761 interp_ok(result.map_err(IoError::HostError).map(|written_size| written_size.to_u64()))
762 }
763}
764
765pub fn open_file_or_dir(
769 root: Option<&fs::Dir>,
770 path: &std::path::Path,
771 opts: &fs::OpenOptions,
772) -> io::Result<(Either<fs::File, fs::Dir>, fs::FileType)> {
773 let file = match root {
777 Some(root) => root.open_file_with(path, opts),
778 None => opts.open(path),
779 };
780 #[cfg(windows)]
781 let file = file.or_else(|err| {
782 use std::os::windows::io::OwnedHandle;
783
784 if err.kind() == io::ErrorKind::PermissionDenied {
785 let dir = match root {
788 Some(root) => root.open_dir_with(path, opts),
789 None => fs::Dir::open_with(path, opts),
790 };
791 match dir {
792 Ok(dir) => Ok(fs::File::from(OwnedHandle::from(dir))),
794 Err(err2) => {
795 Err(if err2.kind() == io::ErrorKind::NotADirectory { err } else { err2 })
800 }
801 }
802 } else {
803 Err(err)
804 }
805 });
806 let file = file?;
807
808 let file_type = file.metadata().expect("just-opened file/dir should have metadata").file_type();
809 #[cfg(not(bootstrap))]
810 assert!(!file_type.is_symlink()); if file_type.is_dir() {
812 cfg_select! {
814 unix => {
815 use std::os::fd::OwnedFd;
816 Ok((Either::Right(OwnedFd::from(file).into()), file_type))
817 }
818 windows => {
819 use std::os::windows::io::OwnedHandle;
820 Ok((Either::Right(OwnedHandle::from(file).into()), file_type))
821 }
822 }
823 } else {
824 Ok((Either::Left(file), file_type))
825 }
826}