1use std::any::Any;
2use std::collections::BTreeMap;
3use std::fs::{File, Metadata};
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>>);
44
45impl<T: ?Sized> Clone for FileDescriptionRef<T> {
46 fn clone(&self) -> Self {
47 FileDescriptionRef(self.0.clone())
48 }
49}
50
51impl<T: ?Sized> Deref for FileDescriptionRef<T> {
52 type Target = T;
53 fn deref(&self) -> &T {
54 &self.0.inner
55 }
56}
57
58impl<T: ?Sized> FileDescriptionRef<T> {
59 pub fn id(&self) -> FdId {
60 self.0.id
61 }
62}
63
64#[derive(Debug)]
66pub struct WeakFileDescriptionRef<T: ?Sized>(Weak<FdIdWith<T>>);
67
68impl<T: ?Sized> Clone for WeakFileDescriptionRef<T> {
69 fn clone(&self) -> Self {
70 WeakFileDescriptionRef(self.0.clone())
71 }
72}
73
74impl<T: ?Sized> FileDescriptionRef<T> {
75 pub fn downgrade(this: &Self) -> WeakFileDescriptionRef<T> {
76 WeakFileDescriptionRef(Rc::downgrade(&this.0))
77 }
78}
79
80impl<T: ?Sized> WeakFileDescriptionRef<T> {
81 pub fn upgrade(&self) -> Option<FileDescriptionRef<T>> {
82 self.0.upgrade().map(FileDescriptionRef)
83 }
84}
85
86impl<T> VisitProvenance for WeakFileDescriptionRef<T> {
87 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
88 }
92}
93
94pub trait FileDescriptionExt: 'static {
98 fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any>;
99
100 fn close_ref<'tcx>(
103 self: FileDescriptionRef<Self>,
104 communicate_allowed: bool,
105 ecx: &mut MiriInterpCx<'tcx>,
106 ) -> InterpResult<'tcx, io::Result<()>>;
107}
108
109impl<T: FileDescription + 'static> FileDescriptionExt for T {
110 fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any> {
111 self.0
112 }
113
114 fn close_ref<'tcx>(
115 self: FileDescriptionRef<Self>,
116 communicate_allowed: bool,
117 ecx: &mut MiriInterpCx<'tcx>,
118 ) -> InterpResult<'tcx, io::Result<()>> {
119 match Rc::into_inner(self.0) {
120 Some(fd) => {
121 ecx.machine.epoll_interests.remove_epolls(fd.id);
123
124 fd.inner.destroy(fd.id, communicate_allowed, ecx)
125 }
126 None => {
127 interp_ok(Ok(()))
129 }
130 }
131 }
132}
133
134pub type DynFileDescriptionRef = FileDescriptionRef<dyn FileDescription>;
135
136impl FileDescriptionRef<dyn FileDescription> {
137 pub fn downcast<T: FileDescription + 'static>(self) -> Option<FileDescriptionRef<T>> {
138 let inner = self.into_rc_any().downcast::<FdIdWith<T>>().ok()?;
139 Some(FileDescriptionRef(inner))
140 }
141}
142
143pub trait FileDescription: std::fmt::Debug + FileDescriptionExt {
145 fn name(&self) -> &'static str;
146
147 fn read<'tcx>(
154 self: FileDescriptionRef<Self>,
155 _communicate_allowed: bool,
156 _ptr: Pointer,
157 _len: usize,
158 _ecx: &mut MiriInterpCx<'tcx>,
159 _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
160 ) -> InterpResult<'tcx> {
161 throw_unsup_format!("cannot read from {}", self.name());
162 }
163
164 fn write<'tcx>(
171 self: FileDescriptionRef<Self>,
172 _communicate_allowed: bool,
173 _ptr: Pointer,
174 _len: usize,
175 _ecx: &mut MiriInterpCx<'tcx>,
176 _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
177 ) -> InterpResult<'tcx> {
178 throw_unsup_format!("cannot write to {}", self.name());
179 }
180
181 fn short_fd_operations(&self) -> bool {
183 false
185 }
186
187 fn seek<'tcx>(
190 &self,
191 _communicate_allowed: bool,
192 _offset: SeekFrom,
193 ) -> InterpResult<'tcx, io::Result<u64>> {
194 throw_unsup_format!("cannot seek on {}", self.name());
195 }
196
197 fn destroy<'tcx>(
201 self,
202 _self_id: FdId,
203 _communicate_allowed: bool,
204 _ecx: &mut MiriInterpCx<'tcx>,
205 ) -> InterpResult<'tcx, io::Result<()>>
206 where
207 Self: Sized,
208 {
209 throw_unsup_format!("cannot close {}", self.name());
210 }
211
212 fn metadata<'tcx>(&self) -> InterpResult<'tcx, io::Result<fs::Metadata>> {
213 throw_unsup_format!("obtaining metadata is only supported on file-backed file descriptors");
214 }
215
216 fn is_tty(&self, _communicate_allowed: bool) -> bool {
217 false
220 }
221
222 fn as_unix<'tcx>(&self, _ecx: &MiriInterpCx<'tcx>) -> &dyn UnixFileDescription {
223 panic!("Not a unix file descriptor: {}", self.name());
224 }
225
226 fn get_flags<'tcx>(&self, _ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
228 throw_unsup_format!("fcntl: {} is not supported for F_GETFL", self.name());
229 }
230
231 fn set_flags<'tcx>(
233 &self,
234 _flag: i32,
235 _ecx: &mut MiriInterpCx<'tcx>,
236 ) -> InterpResult<'tcx, Scalar> {
237 throw_unsup_format!("fcntl: {} is not supported for F_SETFL", self.name());
238 }
239}
240
241impl FileDescription for io::Stdin {
242 fn name(&self) -> &'static str {
243 "stdin"
244 }
245
246 fn read<'tcx>(
247 self: FileDescriptionRef<Self>,
248 communicate_allowed: bool,
249 ptr: Pointer,
250 len: usize,
251 ecx: &mut MiriInterpCx<'tcx>,
252 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
253 ) -> InterpResult<'tcx> {
254 if !communicate_allowed {
255 helpers::isolation_abort_error("`read` from stdin")?;
257 }
258
259 let mut stdin = &*self;
260 let result = ecx.read_from_host(|buf| stdin.read(buf), len, ptr)?;
261 finish.call(ecx, result)
262 }
263
264 fn destroy<'tcx>(
265 self,
266 _self_id: FdId,
267 _communicate_allowed: bool,
268 _ecx: &mut MiriInterpCx<'tcx>,
269 ) -> InterpResult<'tcx, io::Result<()>> {
270 interp_ok(Ok(()))
271 }
272
273 fn is_tty(&self, communicate_allowed: bool) -> bool {
274 communicate_allowed && self.is_terminal()
275 }
276}
277
278impl FileDescription for io::Stdout {
279 fn name(&self) -> &'static str {
280 "stdout"
281 }
282
283 fn write<'tcx>(
284 self: FileDescriptionRef<Self>,
285 _communicate_allowed: bool,
286 ptr: Pointer,
287 len: usize,
288 ecx: &mut MiriInterpCx<'tcx>,
289 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
290 ) -> InterpResult<'tcx> {
291 let result = ecx.write_to_host(&*self, len, ptr)?;
293 io::stdout().flush().unwrap();
299
300 finish.call(ecx, result)
301 }
302
303 fn destroy<'tcx>(
304 self,
305 _self_id: FdId,
306 _communicate_allowed: bool,
307 _ecx: &mut MiriInterpCx<'tcx>,
308 ) -> InterpResult<'tcx, io::Result<()>> {
309 interp_ok(Ok(()))
310 }
311
312 fn is_tty(&self, communicate_allowed: bool) -> bool {
313 communicate_allowed && self.is_terminal()
314 }
315}
316
317impl FileDescription for io::Stderr {
318 fn name(&self) -> &'static str {
319 "stderr"
320 }
321
322 fn destroy<'tcx>(
323 self,
324 _self_id: FdId,
325 _communicate_allowed: bool,
326 _ecx: &mut MiriInterpCx<'tcx>,
327 ) -> InterpResult<'tcx, io::Result<()>> {
328 interp_ok(Ok(()))
329 }
330
331 fn write<'tcx>(
332 self: FileDescriptionRef<Self>,
333 _communicate_allowed: bool,
334 ptr: Pointer,
335 len: usize,
336 ecx: &mut MiriInterpCx<'tcx>,
337 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
338 ) -> InterpResult<'tcx> {
339 let result = ecx.write_to_host(&*self, len, ptr)?;
341 finish.call(ecx, result)
343 }
344
345 fn is_tty(&self, communicate_allowed: bool) -> bool {
346 communicate_allowed && self.is_terminal()
347 }
348}
349
350#[derive(Debug)]
351pub struct FileHandle {
352 pub(crate) file: File,
353 pub(crate) writable: bool,
354}
355
356impl FileDescription for FileHandle {
357 fn name(&self) -> &'static str {
358 "file"
359 }
360
361 fn read<'tcx>(
362 self: FileDescriptionRef<Self>,
363 communicate_allowed: bool,
364 ptr: Pointer,
365 len: usize,
366 ecx: &mut MiriInterpCx<'tcx>,
367 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
368 ) -> InterpResult<'tcx> {
369 assert!(communicate_allowed, "isolation should have prevented even opening a file");
370
371 let mut file = &self.file;
372 let result = ecx.read_from_host(|buf| file.read(buf), len, ptr)?;
373 finish.call(ecx, result)
374 }
375
376 fn write<'tcx>(
377 self: FileDescriptionRef<Self>,
378 communicate_allowed: bool,
379 ptr: Pointer,
380 len: usize,
381 ecx: &mut MiriInterpCx<'tcx>,
382 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
383 ) -> InterpResult<'tcx> {
384 assert!(communicate_allowed, "isolation should have prevented even opening a file");
385
386 if !self.writable {
387 return finish.call(ecx, Err(ErrorKind::PermissionDenied.into()));
394 }
395 let result = ecx.write_to_host(&self.file, len, ptr)?;
396 finish.call(ecx, result)
397 }
398
399 fn seek<'tcx>(
400 &self,
401 communicate_allowed: bool,
402 offset: SeekFrom,
403 ) -> InterpResult<'tcx, io::Result<u64>> {
404 assert!(communicate_allowed, "isolation should have prevented even opening a file");
405 interp_ok((&mut &self.file).seek(offset))
406 }
407
408 fn destroy<'tcx>(
409 self,
410 _self_id: FdId,
411 communicate_allowed: bool,
412 _ecx: &mut MiriInterpCx<'tcx>,
413 ) -> InterpResult<'tcx, io::Result<()>> {
414 assert!(communicate_allowed, "isolation should have prevented even opening a file");
415 if self.writable {
417 let result = self.file.sync_all();
420 drop(self.file);
422 interp_ok(result)
423 } else {
424 drop(self.file);
431 interp_ok(Ok(()))
432 }
433 }
434
435 fn metadata<'tcx>(&self) -> InterpResult<'tcx, io::Result<Metadata>> {
436 interp_ok(self.file.metadata())
437 }
438
439 fn is_tty(&self, communicate_allowed: bool) -> bool {
440 communicate_allowed && self.file.is_terminal()
441 }
442
443 fn short_fd_operations(&self) -> bool {
444 true
448 }
449
450 fn as_unix<'tcx>(&self, ecx: &MiriInterpCx<'tcx>) -> &dyn UnixFileDescription {
451 assert!(
452 ecx.target_os_is_unix(),
453 "unix file operations are only available for unix targets"
454 );
455 self
456 }
457}
458
459#[derive(Debug)]
461pub struct NullOutput;
462
463impl FileDescription for NullOutput {
464 fn name(&self) -> &'static str {
465 "stderr and stdout"
466 }
467
468 fn write<'tcx>(
469 self: FileDescriptionRef<Self>,
470 _communicate_allowed: bool,
471 _ptr: Pointer,
472 len: usize,
473 ecx: &mut MiriInterpCx<'tcx>,
474 finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
475 ) -> InterpResult<'tcx> {
476 finish.call(ecx, Ok(len))
478 }
479
480 fn destroy<'tcx>(
481 self,
482 _self_id: FdId,
483 _communicate_allowed: bool,
484 _ecx: &mut MiriInterpCx<'tcx>,
485 ) -> InterpResult<'tcx, io::Result<()>> {
486 interp_ok(Ok(()))
487 }
488}
489
490pub type FdNum = i32;
492
493#[derive(Debug)]
495pub struct FdTable {
496 pub fds: BTreeMap<FdNum, DynFileDescriptionRef>,
497 next_file_description_id: FdId,
499}
500
501impl VisitProvenance for FdTable {
502 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
503 }
505}
506
507impl FdTable {
508 fn new() -> Self {
509 FdTable { fds: BTreeMap::new(), next_file_description_id: FdId(0) }
510 }
511 pub(crate) fn init(mute_stdout_stderr: bool) -> FdTable {
512 let mut fds = FdTable::new();
513 fds.insert_new(io::stdin());
514 if mute_stdout_stderr {
515 assert_eq!(fds.insert_new(NullOutput), 1);
516 assert_eq!(fds.insert_new(NullOutput), 2);
517 } else {
518 assert_eq!(fds.insert_new(io::stdout()), 1);
519 assert_eq!(fds.insert_new(io::stderr()), 2);
520 }
521 fds
522 }
523
524 pub fn new_ref<T: FileDescription>(&mut self, fd: T) -> FileDescriptionRef<T> {
525 let file_handle =
526 FileDescriptionRef(Rc::new(FdIdWith { id: self.next_file_description_id, inner: fd }));
527 self.next_file_description_id = FdId(self.next_file_description_id.0.strict_add(1));
528 file_handle
529 }
530
531 pub fn insert_new(&mut self, fd: impl FileDescription) -> FdNum {
533 let fd_ref = self.new_ref(fd);
534 self.insert(fd_ref)
535 }
536
537 pub fn insert(&mut self, fd_ref: DynFileDescriptionRef) -> FdNum {
538 self.insert_with_min_num(fd_ref, 0)
539 }
540
541 pub fn insert_with_min_num(
543 &mut self,
544 file_handle: DynFileDescriptionRef,
545 min_fd_num: FdNum,
546 ) -> FdNum {
547 let candidate_new_fd =
552 self.fds.range(min_fd_num..).zip(min_fd_num..).find_map(|((fd_num, _fd), counter)| {
553 if *fd_num != counter {
554 Some(counter)
557 } else {
558 None
560 }
561 });
562 let new_fd_num = candidate_new_fd.unwrap_or_else(|| {
563 self.fds.last_key_value().map(|(fd_num, _)| fd_num.strict_add(1)).unwrap_or(min_fd_num)
566 });
567
568 self.fds.try_insert(new_fd_num, file_handle).unwrap();
569 new_fd_num
570 }
571
572 pub fn get(&self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
573 let fd = self.fds.get(&fd_num)?;
574 Some(fd.clone())
575 }
576
577 pub fn remove(&mut self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
578 self.fds.remove(&fd_num)
579 }
580
581 pub fn is_fd_num(&self, fd_num: FdNum) -> bool {
582 self.fds.contains_key(&fd_num)
583 }
584}
585
586impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
587pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
588 fn read_from_host(
591 &mut self,
592 mut read_cb: impl FnMut(&mut [u8]) -> io::Result<usize>,
593 len: usize,
594 ptr: Pointer,
595 ) -> InterpResult<'tcx, Result<usize, IoError>> {
596 let this = self.eval_context_mut();
597
598 let mut bytes = vec![0; len];
599 let result = read_cb(&mut bytes);
600 match result {
601 Ok(read_size) => {
602 this.write_bytes_ptr(ptr, bytes[..read_size].iter().copied())?;
606 interp_ok(Ok(read_size))
607 }
608 Err(e) => interp_ok(Err(IoError::HostError(e))),
609 }
610 }
611
612 fn write_to_host(
614 &mut self,
615 mut file: impl io::Write,
616 len: usize,
617 ptr: Pointer,
618 ) -> InterpResult<'tcx, Result<usize, IoError>> {
619 let this = self.eval_context_mut();
620
621 let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
622 let result = file.write(bytes);
623 interp_ok(result.map_err(IoError::HostError))
624 }
625}