1use std::any::Any;
2use std::collections::BTreeMap;
3use std::fs::{Dir, File};
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
15#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
20pub struct FdId(usize);
21
22impl FdId {
23 pub fn to_usize(self) -> usize {
24 self.0
25 }
26
27 pub fn new_unchecked(id: usize) -> Self {
29 Self(id)
30 }
31}
32
33#[derive(Debug, Clone)]
34struct FdIdWith<T: ?Sized> {
35 id: FdId,
36 inner: T,
37}
38
39#[repr(transparent)]
42#[derive(CoercePointee, Debug)]
43pub struct FileDescriptionRef<T: ?Sized>(Rc<FdIdWith<T>>);
45
46impl<T: ?Sized> Clone for FileDescriptionRef<T> {
47 fn clone(&self) -> Self {
48 FileDescriptionRef(self.0.clone())
49 }
50}
51
52impl<T: ?Sized> Deref for FileDescriptionRef<T> {
53 type Target = T;
54 fn deref(&self) -> &T {
55 &self.0.inner
56 }
57}
58
59impl<T: ?Sized> FileDescriptionRef<T> {
60 pub fn id(&self) -> FdId {
61 self.0.id
62 }
63}
64
65impl<T: ?Sized> PartialEq for FileDescriptionRef<T> {
66 fn eq(&self, other: &Self) -> bool {
67 self.0.id == other.0.id
68 }
69}
70
71impl<T: ?Sized> Eq for FileDescriptionRef<T> {}
72
73#[derive(Debug)]
75pub struct WeakFileDescriptionRef<T: ?Sized>(Weak<FdIdWith<T>>);
76
77impl<T: ?Sized> Clone for WeakFileDescriptionRef<T> {
78 fn clone(&self) -> Self {
79 WeakFileDescriptionRef(self.0.clone())
80 }
81}
82
83impl<T: ?Sized> FileDescriptionRef<T> {
84 pub fn downgrade(this: &Self) -> WeakFileDescriptionRef<T> {
85 WeakFileDescriptionRef(Rc::downgrade(&this.0))
86 }
87}
88
89impl<T: ?Sized> WeakFileDescriptionRef<T> {
90 pub fn upgrade(&self) -> Option<FileDescriptionRef<T>> {
91 self.0.upgrade().map(FileDescriptionRef)
92 }
93
94 pub fn is_closed(&self) -> bool {
97 self.0.strong_count() == 0
98 }
99}
100
101impl<T> VisitProvenance for FileDescriptionRef<T> {
102 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
103 }
105}
106
107pub trait FileDescriptionExt: 'static {
111 fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any>;
112}
113
114impl<T: FileDescription + 'static> FileDescriptionExt for T {
115 fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any> {
116 self.0
117 }
118}
119
120pub type DynFileDescriptionRef = FileDescriptionRef<dyn FileDescription>;
121pub type WeakDynFileDescriptionRef = WeakFileDescriptionRef<dyn FileDescription>;
122
123impl FileDescriptionRef<dyn FileDescription> {
124 pub fn downcast<T: FileDescription + 'static>(self) -> Option<FileDescriptionRef<T>> {
125 let inner = self.into_rc_any().downcast::<FdIdWith<T>>().ok()?;
126 Some(FileDescriptionRef(inner))
127 }
128}
129
130pub trait FileDescription: std::fmt::Debug + FileDescriptionExt {
132 fn name(&self) -> &'static str;
133
134 fn read<'tcx>(
141 self: FileDescriptionRef<Self>,
142 _communicate_allowed: bool,
143 _ptr: Pointer,
144 _len: usize,
145 _ecx: &mut MiriInterpCx<'tcx>,
146 _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
147 ) -> InterpResult<'tcx> {
148 throw_unsup_format!("cannot read from {}", self.name());
149 }
150
151 fn write<'tcx>(
158 self: FileDescriptionRef<Self>,
159 _communicate_allowed: bool,
160 _ptr: Pointer,
161 _len: usize,
162 _ecx: &mut MiriInterpCx<'tcx>,
163 _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
164 ) -> InterpResult<'tcx> {
165 throw_unsup_format!("cannot write to {}", self.name());
166 }
167
168 fn short_fd_operations(&self) -> bool {
170 false
172 }
173
174 fn seek<'tcx>(
177 &self,
178 _communicate_allowed: bool,
179 _offset: SeekFrom,
180 ) -> InterpResult<'tcx, io::Result<u64>> {
181 throw_unsup_format!("cannot seek on {}", self.name());
182 }
183
184 fn metadata<'tcx>(&self) -> InterpResult<'tcx, Either<io::Result<fs::Metadata>, &'static str>> {
189 throw_unsup_format!("obtaining metadata is only supported on file-backed file descriptors");
190 }
191
192 fn is_tty(&self, _communicate_allowed: bool) -> bool {
193 false
196 }
197
198 fn as_unix<'tcx>(
199 self: FileDescriptionRef<Self>,
200 _ecx: &MiriInterpCx<'tcx>,
201 ) -> FileDescriptionRef<dyn UnixFileDescription> {
202 panic!("Not a unix file descriptor: {}", self.name());
203 }
204
205 fn get_flags<'tcx>(&self, _ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
207 throw_unsup_format!("fcntl: {} is not supported for F_GETFL", self.name());
208 }
209
210 fn set_flags<'tcx>(
212 &self,
213 _flag: i32,
214 _ecx: &mut MiriInterpCx<'tcx>,
215 ) -> InterpResult<'tcx, Scalar> {
216 throw_unsup_format!("fcntl: {} is not supported for F_SETFL", self.name());
217 }
218
219 fn readiness_watched(&self) -> Option<&ReadinessWatched> {
221 None
222 }
223
224 fn readiness(&self) -> Readiness {
226 panic!("FD type {} implements `readiness_watched` but not `readiness`", self.name());
227 }
228}
229
230impl FileDescription for io::Stdin {
231 fn name(&self) -> &'static str {
232 "stdin"
233 }
234
235 fn read<'tcx>(
236 self: FileDescriptionRef<Self>,
237 communicate_allowed: bool,
238 ptr: Pointer,
239 len: usize,
240 ecx: &mut MiriInterpCx<'tcx>,
241 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
242 ) -> InterpResult<'tcx> {
243 if !communicate_allowed {
244 helpers::isolation_abort_error("`read` from stdin")?;
246 }
247
248 let mut stdin = &*self;
249 let result = ecx.read_from_host(|buf| stdin.read(buf), len, ptr)?;
250 finish.call(ecx, result)
251 }
252
253 fn is_tty(&self, communicate_allowed: bool) -> bool {
254 communicate_allowed && self.is_terminal()
255 }
256}
257
258impl FileDescription for io::Stdout {
259 fn name(&self) -> &'static str {
260 "stdout"
261 }
262
263 fn write<'tcx>(
264 self: FileDescriptionRef<Self>,
265 _communicate_allowed: bool,
266 ptr: Pointer,
267 len: usize,
268 ecx: &mut MiriInterpCx<'tcx>,
269 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
270 ) -> InterpResult<'tcx> {
271 let result = ecx.write_to_host(&*self, len, ptr)?;
273 io::stdout().flush().unwrap();
279
280 finish.call(ecx, result)
281 }
282
283 fn is_tty(&self, communicate_allowed: bool) -> bool {
284 communicate_allowed && self.is_terminal()
285 }
286}
287
288impl FileDescription for io::Stderr {
289 fn name(&self) -> &'static str {
290 "stderr"
291 }
292
293 fn write<'tcx>(
294 self: FileDescriptionRef<Self>,
295 _communicate_allowed: bool,
296 ptr: Pointer,
297 len: usize,
298 ecx: &mut MiriInterpCx<'tcx>,
299 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
300 ) -> InterpResult<'tcx> {
301 let result = ecx.write_to_host(&*self, len, ptr)?;
303 finish.call(ecx, result)
305 }
306
307 fn is_tty(&self, communicate_allowed: bool) -> bool {
308 communicate_allowed && self.is_terminal()
309 }
310}
311
312#[derive(Debug)]
313pub struct FileHandle {
314 pub(crate) file: File,
315 pub(crate) readable: bool,
316 pub(crate) writable: bool,
317}
318
319impl FileDescription for FileHandle {
320 fn name(&self) -> &'static str {
321 "file"
322 }
323
324 fn read<'tcx>(
325 self: FileDescriptionRef<Self>,
326 communicate_allowed: bool,
327 ptr: Pointer,
328 len: usize,
329 ecx: &mut MiriInterpCx<'tcx>,
330 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
331 ) -> InterpResult<'tcx> {
332 assert!(communicate_allowed, "isolation should have prevented even opening a file");
333
334 if !self.readable {
335 return finish.call(ecx, Err(ErrorKind::PermissionDenied.into()));
336 }
337
338 let mut file = &self.file;
339 let result = ecx.read_from_host(|buf| file.read(buf), len, ptr)?;
340 finish.call(ecx, result)
341 }
342
343 fn write<'tcx>(
344 self: FileDescriptionRef<Self>,
345 communicate_allowed: bool,
346 ptr: Pointer,
347 len: usize,
348 ecx: &mut MiriInterpCx<'tcx>,
349 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
350 ) -> InterpResult<'tcx> {
351 assert!(communicate_allowed, "isolation should have prevented even opening a file");
352
353 if !self.writable {
354 return finish.call(ecx, Err(ErrorKind::PermissionDenied.into()));
361 }
362 let result = ecx.write_to_host(&self.file, len, ptr)?;
363 finish.call(ecx, result)
364 }
365
366 fn seek<'tcx>(
367 &self,
368 communicate_allowed: bool,
369 offset: SeekFrom,
370 ) -> InterpResult<'tcx, io::Result<u64>> {
371 assert!(communicate_allowed, "isolation should have prevented even opening a file");
372 interp_ok((&mut &self.file).seek(offset))
373 }
374
375 fn metadata<'tcx>(&self) -> InterpResult<'tcx, Either<io::Result<fs::Metadata>, &'static str>> {
376 interp_ok(Either::Left(self.file.metadata()))
377 }
378
379 fn is_tty(&self, communicate_allowed: bool) -> bool {
380 communicate_allowed && self.file.is_terminal()
381 }
382
383 fn short_fd_operations(&self) -> bool {
384 true
388 }
389
390 fn as_unix<'tcx>(
391 self: FileDescriptionRef<Self>,
392 ecx: &MiriInterpCx<'tcx>,
393 ) -> FileDescriptionRef<dyn UnixFileDescription> {
394 assert!(
395 ecx.target_os_is_unix(),
396 "unix file operations are only available for unix targets"
397 );
398 self
399 }
400}
401
402#[derive(Debug)]
403pub struct DirHandle {
404 pub(crate) dir: Dir,
405}
406
407impl FileDescription for DirHandle {
408 fn name(&self) -> &'static str {
409 "directory"
410 }
411
412 fn metadata<'tcx>(
413 &self,
414 ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
415 interp_ok(Either::Left(self.dir.metadata()))
416 }
417}
418
419#[derive(Debug)]
421pub struct NullOutput;
422
423impl FileDescription for NullOutput {
424 fn name(&self) -> &'static str {
425 "stderr and stdout"
426 }
427
428 fn write<'tcx>(
429 self: FileDescriptionRef<Self>,
430 _communicate_allowed: bool,
431 _ptr: Pointer,
432 len: usize,
433 ecx: &mut MiriInterpCx<'tcx>,
434 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
435 ) -> InterpResult<'tcx> {
436 finish.call(ecx, Ok(len))
438 }
439}
440
441pub type FdNum = i32;
443
444#[derive(Debug)]
446pub struct FdTable {
447 fds: BTreeMap<FdNum, DynFileDescriptionRef>,
448 next_file_description_id: FdId,
450}
451
452impl VisitProvenance for FdTable {
453 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
454 }
456}
457
458impl FdTable {
459 fn new() -> Self {
460 FdTable { fds: BTreeMap::new(), next_file_description_id: FdId(0) }
461 }
462 pub(crate) fn init(mute_stdout_stderr: bool) -> FdTable {
463 let mut fds = FdTable::new();
464 fds.insert_new(io::stdin());
465 if mute_stdout_stderr {
466 assert_eq!(fds.insert_new(NullOutput), 1);
467 assert_eq!(fds.insert_new(NullOutput), 2);
468 } else {
469 assert_eq!(fds.insert_new(io::stdout()), 1);
470 assert_eq!(fds.insert_new(io::stderr()), 2);
471 }
472 fds
473 }
474
475 pub fn new_ref<T: FileDescription>(&mut self, fd: T) -> FileDescriptionRef<T> {
476 let file_handle =
477 FileDescriptionRef(Rc::new(FdIdWith { id: self.next_file_description_id, inner: fd }));
478 self.next_file_description_id = FdId(self.next_file_description_id.0.strict_add(1));
479 file_handle
480 }
481
482 pub fn insert_new(&mut self, fd: impl FileDescription) -> FdNum {
484 let fd_ref = self.new_ref(fd);
485 self.insert(fd_ref)
486 }
487
488 pub fn insert(&mut self, fd_ref: DynFileDescriptionRef) -> FdNum {
490 self.insert_with_min_num(fd_ref, 0)
491 }
492
493 pub fn insert_with_min_num(
495 &mut self,
496 file_handle: DynFileDescriptionRef,
497 min_fd_num: FdNum,
498 ) -> FdNum {
499 let mut candidate = min_fd_num;
500 for (&fd_num, _) in self.fds.range(min_fd_num..) {
501 if fd_num == candidate {
502 candidate = candidate.strict_add(1);
504 } else {
505 break;
507 }
508 }
509 self.fds.try_insert(candidate, file_handle).unwrap();
513 candidate
514 }
515
516 pub fn get(&self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
517 let fd = self.fds.get(&fd_num)?;
518 Some(fd.clone())
519 }
520
521 pub fn remove(&mut self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
522 self.fds.remove(&fd_num)
523 }
524
525 pub fn is_fd_num(&self, fd_num: FdNum) -> bool {
526 self.fds.contains_key(&fd_num)
527 }
528}
529
530impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
531pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
532 fn read_from_host(
535 &mut self,
536 mut read_cb: impl FnMut(&mut [u8]) -> io::Result<usize>,
537 len: usize,
538 ptr: Pointer,
539 ) -> InterpResult<'tcx, Result<usize, IoError>> {
540 let this = self.eval_context_mut();
541
542 let mut bytes = vec![0; len];
543 let result = read_cb(&mut bytes);
544 match result {
545 Ok(read_size) => {
546 this.write_bytes_ptr(ptr, bytes[..read_size].iter().copied())?;
550 interp_ok(Ok(read_size))
551 }
552 Err(e) => interp_ok(Err(IoError::HostError(e))),
553 }
554 }
555
556 fn write_to_host(
558 &mut self,
559 mut file: impl io::Write,
560 len: usize,
561 ptr: Pointer,
562 ) -> InterpResult<'tcx, Result<usize, IoError>> {
563 let this = self.eval_context_mut();
564
565 let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
566 let result = file.write(bytes);
567 interp_ok(result.map_err(IoError::HostError))
568 }
569}