2 use std::collections::BTreeMap;
3 use std::convert::{TryFrom, TryInto};
5 read_dir, remove_dir, remove_file, rename, DirBuilder, File, FileType, OpenOptions, ReadDir,
7 use std::io::{self, ErrorKind, Read, Seek, SeekFrom, Write};
9 use std::time::SystemTime;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_middle::ty::{self, layout::LayoutOf};
15 use rustc_target::abi::{Align, Size};
18 use shims::os_str::os_str_to_bytes;
19 use shims::time::system_time_to_duration;
27 trait FileDescriptor: std::fmt::Debug {
28 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle>;
32 communicate_allowed: bool,
34 ) -> InterpResult<'tcx, io::Result<usize>>;
37 communicate_allowed: bool,
39 ) -> InterpResult<'tcx, io::Result<usize>>;
42 communicate_allowed: bool,
44 ) -> InterpResult<'tcx, io::Result<u64>>;
47 _communicate_allowed: bool,
48 ) -> InterpResult<'tcx, io::Result<i32>>;
50 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>>;
53 impl FileDescriptor for FileHandle {
54 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
60 communicate_allowed: bool,
62 ) -> InterpResult<'tcx, io::Result<usize>> {
63 assert!(communicate_allowed, "isolation should have prevented even opening a file");
64 Ok(self.file.read(bytes))
69 communicate_allowed: bool,
71 ) -> InterpResult<'tcx, io::Result<usize>> {
72 assert!(communicate_allowed, "isolation should have prevented even opening a file");
73 Ok((&mut &self.file).write(bytes))
78 communicate_allowed: bool,
80 ) -> InterpResult<'tcx, io::Result<u64>> {
81 assert!(communicate_allowed, "isolation should have prevented even opening a file");
82 Ok(self.file.seek(offset))
87 communicate_allowed: bool,
88 ) -> InterpResult<'tcx, io::Result<i32>> {
89 assert!(communicate_allowed, "isolation should have prevented even opening a file");
90 // We sync the file if it was opened in a mode different than read-only.
92 // `File::sync_all` does the checks that are done when closing a file. We do this to
93 // to handle possible errors correctly.
94 let result = self.file.sync_all().map(|_| 0i32);
95 // Now we actually close the file.
97 // And return the result.
100 // We drop the file, this closes it but ignores any errors
101 // produced when closing it. This is done because
102 // `File::sync_all` cannot be done over files like
103 // `/dev/urandom` which are read-only. Check
104 // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439
105 // for a deeper discussion.
111 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
112 let duplicated = self.file.try_clone()?;
113 Ok(Box::new(FileHandle { file: duplicated, writable: self.writable }))
117 impl FileDescriptor for io::Stdin {
118 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
119 throw_unsup_format!("stdin cannot be used as FileHandle");
124 communicate_allowed: bool,
126 ) -> InterpResult<'tcx, io::Result<usize>> {
127 if !communicate_allowed {
128 // We want isolation mode to be deterministic, so we have to disallow all reads, even stdin.
129 helpers::isolation_abort_error("`read` from stdin")?;
131 Ok(Read::read(self, bytes))
136 _communicate_allowed: bool,
138 ) -> InterpResult<'tcx, io::Result<usize>> {
139 throw_unsup_format!("cannot write to stdin");
144 _communicate_allowed: bool,
146 ) -> InterpResult<'tcx, io::Result<u64>> {
147 throw_unsup_format!("cannot seek on stdin");
152 _communicate_allowed: bool,
153 ) -> InterpResult<'tcx, io::Result<i32>> {
154 throw_unsup_format!("stdin cannot be closed");
157 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
158 Ok(Box::new(io::stdin()))
162 impl FileDescriptor for io::Stdout {
163 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
164 throw_unsup_format!("stdout cannot be used as FileHandle");
169 _communicate_allowed: bool,
171 ) -> InterpResult<'tcx, io::Result<usize>> {
172 throw_unsup_format!("cannot read from stdout");
177 _communicate_allowed: bool,
179 ) -> InterpResult<'tcx, io::Result<usize>> {
180 // We allow writing to stderr even with isolation enabled.
181 let result = Write::write(&mut { self }, bytes);
182 // Stdout is buffered, flush to make sure it appears on the
183 // screen. This is the write() syscall of the interpreted
184 // program, we want it to correspond to a write() syscall on
185 // the host -- there is no good in adding extra buffering
187 io::stdout().flush().unwrap();
194 _communicate_allowed: bool,
196 ) -> InterpResult<'tcx, io::Result<u64>> {
197 throw_unsup_format!("cannot seek on stdout");
202 _communicate_allowed: bool,
203 ) -> InterpResult<'tcx, io::Result<i32>> {
204 throw_unsup_format!("stdout cannot be closed");
207 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
208 Ok(Box::new(io::stdout()))
212 impl FileDescriptor for io::Stderr {
213 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
214 throw_unsup_format!("stderr cannot be used as FileHandle");
219 _communicate_allowed: bool,
221 ) -> InterpResult<'tcx, io::Result<usize>> {
222 throw_unsup_format!("cannot read from stderr");
227 _communicate_allowed: bool,
229 ) -> InterpResult<'tcx, io::Result<usize>> {
230 // We allow writing to stderr even with isolation enabled.
231 // No need to flush, stderr is not buffered.
232 Ok(Write::write(&mut { self }, bytes))
237 _communicate_allowed: bool,
239 ) -> InterpResult<'tcx, io::Result<u64>> {
240 throw_unsup_format!("cannot seek on stderr");
245 _communicate_allowed: bool,
246 ) -> InterpResult<'tcx, io::Result<i32>> {
247 throw_unsup_format!("stderr cannot be closed");
250 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
251 Ok(Box::new(io::stderr()))
256 pub struct FileHandler {
257 handles: BTreeMap<i32, Box<dyn FileDescriptor>>,
260 impl<'tcx> Default for FileHandler {
261 fn default() -> Self {
262 let mut handles: BTreeMap<_, Box<dyn FileDescriptor>> = BTreeMap::new();
263 handles.insert(0i32, Box::new(io::stdin()));
264 handles.insert(1i32, Box::new(io::stdout()));
265 handles.insert(2i32, Box::new(io::stderr()));
266 FileHandler { handles }
270 impl<'tcx> FileHandler {
271 fn insert_fd(&mut self, file_handle: Box<dyn FileDescriptor>) -> i32 {
272 self.insert_fd_with_min_fd(file_handle, 0)
275 fn insert_fd_with_min_fd(&mut self, file_handle: Box<dyn FileDescriptor>, min_fd: i32) -> i32 {
276 // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
277 // between used FDs, the find_map combinator will return it. If the first such unused FD
278 // is after all other used FDs, the find_map combinator will return None, and we will use
279 // the FD following the greatest FD thus far.
280 let candidate_new_fd =
281 self.handles.range(min_fd..).zip(min_fd..).find_map(|((fd, _fh), counter)| {
283 // There was a gap in the fds stored, return the first unused one
284 // (note that this relies on BTreeMap iterating in key order)
287 // This fd is used, keep going
291 let new_fd = candidate_new_fd.unwrap_or_else(|| {
292 // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
293 // maximum fd in the map
296 .map(|(fd, _)| fd.checked_add(1).unwrap())
300 self.handles.try_insert(new_fd, file_handle).unwrap();
305 impl<'mir, 'tcx: 'mir> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
306 trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
307 fn macos_stat_write_buf(
309 metadata: FileMetadata,
310 buf_op: &OpTy<'tcx, Tag>,
311 ) -> InterpResult<'tcx, i32> {
312 let this = self.eval_context_mut();
314 let mode: u16 = metadata.mode.to_u16()?;
316 let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
317 let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
318 let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
320 let buf = this.deref_operand(buf_op)?;
321 this.write_int_fields_named(
324 ("st_mode", mode.into()),
330 ("st_atime", access_sec.into()),
331 ("st_atime_nsec", access_nsec.into()),
332 ("st_mtime", modified_sec.into()),
333 ("st_mtime_nsec", modified_nsec.into()),
335 ("st_ctime_nsec", 0),
336 ("st_birthtime", created_sec.into()),
337 ("st_birthtime_nsec", created_nsec.into()),
338 ("st_size", metadata.size.into()),
350 /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
351 /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
352 /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
353 /// types (like `read`, that returns an `i64`).
354 fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
355 let this = self.eval_context_mut();
356 let ebadf = this.eval_libc("EBADF")?;
357 this.set_last_error(ebadf)?;
361 fn file_type_to_d_type(
363 file_type: std::io::Result<FileType>,
364 ) -> InterpResult<'tcx, i32> {
365 let this = self.eval_context_mut();
368 if file_type.is_dir() {
369 Ok(this.eval_libc("DT_DIR")?.to_u8()?.into())
370 } else if file_type.is_file() {
371 Ok(this.eval_libc("DT_REG")?.to_u8()?.into())
372 } else if file_type.is_symlink() {
373 Ok(this.eval_libc("DT_LNK")?.to_u8()?.into())
375 // Certain file types are only supported when the host is a Unix system.
376 // (i.e. devices and sockets) If it is, check those cases, if not, fall back to
377 // DT_UNKNOWN sooner.
381 use std::os::unix::fs::FileTypeExt;
382 if file_type.is_block_device() {
383 Ok(this.eval_libc("DT_BLK")?.to_u8()?.into())
384 } else if file_type.is_char_device() {
385 Ok(this.eval_libc("DT_CHR")?.to_u8()?.into())
386 } else if file_type.is_fifo() {
387 Ok(this.eval_libc("DT_FIFO")?.to_u8()?.into())
388 } else if file_type.is_socket() {
389 Ok(this.eval_libc("DT_SOCK")?.to_u8()?.into())
391 Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
395 Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
399 return match e.raw_os_error() {
400 Some(error) => Ok(error),
403 "the error {} couldn't be converted to a return value",
411 /// An open directory, tracked by DirHandler.
414 /// The directory reader on the host.
416 /// The most recent entry returned by readdir()
417 entry: Pointer<Option<Tag>>,
421 fn new(read_dir: ReadDir) -> Self {
422 // We rely on `free` being a NOP on null pointers.
423 Self { read_dir, entry: Pointer::null() }
428 pub struct DirHandler {
429 /// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
432 /// When opendir is called, a directory iterator is created on the host for the target
433 /// directory, and an entry is stored in this hash map, indexed by an ID which represents
434 /// the directory stream. When readdir is called, the directory stream ID is used to look up
435 /// the corresponding ReadDir iterator from this map, and information from the next
436 /// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
438 streams: FxHashMap<u64, OpenDir>,
439 /// ID number to be used by the next call to opendir
444 fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
445 let id = self.next_id;
447 self.streams.try_insert(id, OpenDir::new(read_dir)).unwrap();
452 impl Default for DirHandler {
453 fn default() -> DirHandler {
455 streams: FxHashMap::default(),
456 // Skip 0 as an ID, because it looks like a null pointer to libc
465 operation: fn(&File) -> std::io::Result<()>,
466 ) -> std::io::Result<i32> {
467 if !writable && cfg!(windows) {
468 // sync_all() and sync_data() will return an error on Windows hosts if the file is not opened
469 // for writing. (FlushFileBuffers requires that the file handle have the
470 // GENERIC_WRITE right)
473 let result = operation(file);
478 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
479 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
480 fn open(&mut self, args: &[OpTy<'tcx, Tag>]) -> InterpResult<'tcx, i32> {
483 "incorrect number of arguments for `open`: got {}, expected at least 2",
488 let this = self.eval_context_mut();
490 let path = this.read_pointer(&args[0])?;
491 let flag = this.read_scalar(&args[1])?.to_i32()?;
493 let mut options = OpenOptions::new();
495 let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
496 let o_wronly = this.eval_libc_i32("O_WRONLY")?;
497 let o_rdwr = this.eval_libc_i32("O_RDWR")?;
498 // The first two bits of the flag correspond to the access mode in linux, macOS and
499 // windows. We need to check that in fact the access mode flags for the current target
500 // only use these two bits, otherwise we are in an unsupported target and should error.
501 if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
502 throw_unsup_format!("access mode flags on this target are unsupported");
504 let mut writable = true;
506 // Now we check the access mode
507 let access_mode = flag & 0b11;
509 if access_mode == o_rdonly {
512 } else if access_mode == o_wronly {
514 } else if access_mode == o_rdwr {
515 options.read(true).write(true);
517 throw_unsup_format!("unsupported access mode {:#x}", access_mode);
519 // We need to check that there aren't unsupported options in `flag`. For this we try to
520 // reproduce the content of `flag` in the `mirror` variable using only the supported
522 let mut mirror = access_mode;
524 let o_append = this.eval_libc_i32("O_APPEND")?;
525 if flag & o_append != 0 {
526 options.append(true);
529 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
530 if flag & o_trunc != 0 {
531 options.truncate(true);
534 let o_creat = this.eval_libc_i32("O_CREAT")?;
535 if flag & o_creat != 0 {
536 // Get the mode. On macOS, the argument type `mode_t` is actually `u16`, but
537 // C integer promotion rules mean that on the ABI level, it gets passed as `u32`
538 // (see https://github.com/rust-lang/rust/issues/71915).
539 let mode = if let Some(arg) = args.get(2) {
540 this.read_scalar(arg)?.to_u32()?
543 "incorrect number of arguments for `open` with `O_CREAT`: got {}, expected at least 3",
549 throw_unsup_format!("non-default mode 0o{:o} is not supported", mode);
554 let o_excl = this.eval_libc_i32("O_EXCL")?;
555 if flag & o_excl != 0 {
557 options.create_new(true);
559 options.create(true);
562 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
563 if flag & o_cloexec != 0 {
564 // We do not need to do anything for this flag because `std` already sets it.
565 // (Technically we do not support *not* setting this flag, but we ignore that.)
568 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
569 // then we throw an error.
571 throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
574 let path = this.read_path_from_c_str(path)?;
576 // Reject if isolation is enabled.
577 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
578 this.reject_in_isolation("`open`", reject_with)?;
579 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
583 let fd = options.open(&path).map(|file| {
584 let fh = &mut this.machine.file_handler;
585 fh.insert_fd(Box::new(FileHandle { file, writable }))
588 this.try_unwrap_io_result(fd)
591 fn fcntl(&mut self, args: &[OpTy<'tcx, Tag>]) -> InterpResult<'tcx, i32> {
592 let this = self.eval_context_mut();
596 "incorrect number of arguments for fcntl: got {}, expected at least 2",
600 let fd = this.read_scalar(&args[0])?.to_i32()?;
601 let cmd = this.read_scalar(&args[1])?.to_i32()?;
603 // Reject if isolation is enabled.
604 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
605 this.reject_in_isolation("`fcntl`", reject_with)?;
606 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
610 // We only support getting the flags for a descriptor.
611 if cmd == this.eval_libc_i32("F_GETFD")? {
612 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
613 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
614 // always sets this flag when opening a file. However we still need to check that the
615 // file itself is open.
616 if this.machine.file_handler.handles.contains_key(&fd) {
617 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
619 this.handle_not_found()
621 } else if cmd == this.eval_libc_i32("F_DUPFD")?
622 || cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
624 // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
625 // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
626 // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
627 // thus they can share the same implementation here.
630 "incorrect number of arguments for fcntl with cmd=`F_DUPFD`/`F_DUPFD_CLOEXEC`: got {}, expected at least 3",
634 let start = this.read_scalar(&args[2])?.to_i32()?;
636 let fh = &mut this.machine.file_handler;
638 match fh.handles.get_mut(&fd) {
639 Some(file_descriptor) => {
640 let dup_result = file_descriptor.dup();
642 Ok(dup_fd) => Ok(fh.insert_fd_with_min_fd(dup_fd, start)),
644 this.set_last_error_from_io_error(e.kind())?;
649 None => return this.handle_not_found(),
651 } else if this.tcx.sess.target.os == "macos" && cmd == this.eval_libc_i32("F_FULLFSYNC")? {
652 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
653 // FIXME: Support fullfsync for all FDs
654 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
655 let io_result = maybe_sync_file(&file, *writable, File::sync_all);
656 this.try_unwrap_io_result(io_result)
658 this.handle_not_found()
661 throw_unsup_format!("the {:#x} command is not supported for `fcntl`)", cmd);
665 fn close(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
666 let this = self.eval_context_mut();
668 let fd = this.read_scalar(fd_op)?.to_i32()?;
670 if let Some(file_descriptor) = this.machine.file_handler.handles.remove(&fd) {
671 let result = file_descriptor.close(this.machine.communicate())?;
672 this.try_unwrap_io_result(result)
674 this.handle_not_found()
678 fn read(&mut self, fd: i32, buf: Pointer<Option<Tag>>, count: u64) -> InterpResult<'tcx, i64> {
679 let this = self.eval_context_mut();
681 // Isolation check is done via `FileDescriptor` trait.
683 trace!("Reading from FD {}, size {}", fd, count);
685 // Check that the *entire* buffer is actually valid memory.
686 this.check_ptr_access_align(
688 Size::from_bytes(count),
690 CheckInAllocMsg::MemoryAccessTest,
693 // We cap the number of read bytes to the largest value that we are able to fit in both the
694 // host's and target's `isize`. This saves us from having to handle overflows later.
695 let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
696 let communicate = this.machine.communicate();
698 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
699 trace!("read: FD mapped to {:?}", file_descriptor);
700 // We want to read at most `count` bytes. We are sure that `count` is not negative
701 // because it was a target's `usize`. Also we are sure that its smaller than
702 // `usize::MAX` because it is a host's `isize`.
703 let mut bytes = vec![0; count as usize];
704 // `File::read` never returns a value larger than `count`,
705 // so this cannot fail.
707 file_descriptor.read(communicate, &mut bytes)?.map(|c| i64::try_from(c).unwrap());
711 // If reading to `bytes` did not fail, we write those bytes to the buffer.
712 this.write_bytes_ptr(buf, bytes)?;
716 this.set_last_error_from_io_error(e.kind())?;
721 trace!("read: FD not found");
722 this.handle_not_found()
726 fn write(&mut self, fd: i32, buf: Pointer<Option<Tag>>, count: u64) -> InterpResult<'tcx, i64> {
727 let this = self.eval_context_mut();
729 // Isolation check is done via `FileDescriptor` trait.
731 // Check that the *entire* buffer is actually valid memory.
732 this.check_ptr_access_align(
734 Size::from_bytes(count),
736 CheckInAllocMsg::MemoryAccessTest,
739 // We cap the number of written bytes to the largest value that we are able to fit in both the
740 // host's and target's `isize`. This saves us from having to handle overflows later.
741 let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
742 let communicate = this.machine.communicate();
744 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
745 let bytes = this.read_bytes_ptr(buf, Size::from_bytes(count))?;
747 file_descriptor.write(communicate, &bytes)?.map(|c| i64::try_from(c).unwrap());
748 this.try_unwrap_io_result(result)
750 this.handle_not_found()
756 fd_op: &OpTy<'tcx, Tag>,
757 offset_op: &OpTy<'tcx, Tag>,
758 whence_op: &OpTy<'tcx, Tag>,
759 ) -> InterpResult<'tcx, i64> {
760 let this = self.eval_context_mut();
762 // Isolation check is done via `FileDescriptor` trait.
764 let fd = this.read_scalar(fd_op)?.to_i32()?;
765 let offset = this.read_scalar(offset_op)?.to_i64()?;
766 let whence = this.read_scalar(whence_op)?.to_i32()?;
768 let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
769 SeekFrom::Start(u64::try_from(offset).unwrap())
770 } else if whence == this.eval_libc_i32("SEEK_CUR")? {
771 SeekFrom::Current(offset)
772 } else if whence == this.eval_libc_i32("SEEK_END")? {
773 SeekFrom::End(offset)
775 let einval = this.eval_libc("EINVAL")?;
776 this.set_last_error(einval)?;
780 let communicate = this.machine.communicate();
781 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
782 let result = file_descriptor
783 .seek(communicate, seek_from)?
784 .map(|offset| i64::try_from(offset).unwrap());
785 this.try_unwrap_io_result(result)
787 this.handle_not_found()
791 fn unlink(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
792 let this = self.eval_context_mut();
794 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
796 // Reject if isolation is enabled.
797 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
798 this.reject_in_isolation("`unlink`", reject_with)?;
799 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
803 let result = remove_file(path).map(|_| 0);
804 this.try_unwrap_io_result(result)
809 target_op: &OpTy<'tcx, Tag>,
810 linkpath_op: &OpTy<'tcx, Tag>,
811 ) -> InterpResult<'tcx, i32> {
813 fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
814 std::os::unix::fs::symlink(src, dst)
818 fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
819 use std::os::windows::fs;
820 if src.is_dir() { fs::symlink_dir(src, dst) } else { fs::symlink_file(src, dst) }
823 let this = self.eval_context_mut();
824 let target = this.read_path_from_c_str(this.read_pointer(target_op)?)?;
825 let linkpath = this.read_path_from_c_str(this.read_pointer(linkpath_op)?)?;
827 // Reject if isolation is enabled.
828 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
829 this.reject_in_isolation("`symlink`", reject_with)?;
830 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
834 let result = create_link(&target, &linkpath).map(|_| 0);
835 this.try_unwrap_io_result(result)
840 path_op: &OpTy<'tcx, Tag>,
841 buf_op: &OpTy<'tcx, Tag>,
842 ) -> InterpResult<'tcx, i32> {
843 let this = self.eval_context_mut();
844 this.assert_target_os("macos", "stat");
846 let path_scalar = this.read_pointer(path_op)?;
847 let path = this.read_path_from_c_str(path_scalar)?.into_owned();
849 // Reject if isolation is enabled.
850 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
851 this.reject_in_isolation("`stat`", reject_with)?;
852 let eacc = this.eval_libc("EACCES")?;
853 this.set_last_error(eacc)?;
857 // `stat` always follows symlinks.
858 let metadata = match FileMetadata::from_path(this, &path, true)? {
859 Some(metadata) => metadata,
860 None => return Ok(-1),
863 this.macos_stat_write_buf(metadata, buf_op)
866 // `lstat` is used to get symlink metadata.
869 path_op: &OpTy<'tcx, Tag>,
870 buf_op: &OpTy<'tcx, Tag>,
871 ) -> InterpResult<'tcx, i32> {
872 let this = self.eval_context_mut();
873 this.assert_target_os("macos", "lstat");
875 let path_scalar = this.read_pointer(path_op)?;
876 let path = this.read_path_from_c_str(path_scalar)?.into_owned();
878 // Reject if isolation is enabled.
879 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
880 this.reject_in_isolation("`lstat`", reject_with)?;
881 let eacc = this.eval_libc("EACCES")?;
882 this.set_last_error(eacc)?;
886 let metadata = match FileMetadata::from_path(this, &path, false)? {
887 Some(metadata) => metadata,
888 None => return Ok(-1),
891 this.macos_stat_write_buf(metadata, buf_op)
896 fd_op: &OpTy<'tcx, Tag>,
897 buf_op: &OpTy<'tcx, Tag>,
898 ) -> InterpResult<'tcx, i32> {
899 let this = self.eval_context_mut();
901 this.assert_target_os("macos", "fstat");
903 let fd = this.read_scalar(fd_op)?.to_i32()?;
905 // Reject if isolation is enabled.
906 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
907 this.reject_in_isolation("`fstat`", reject_with)?;
908 // Set error code as "EBADF" (bad fd)
909 return this.handle_not_found();
912 let metadata = match FileMetadata::from_fd(this, fd)? {
913 Some(metadata) => metadata,
914 None => return Ok(-1),
916 this.macos_stat_write_buf(metadata, buf_op)
921 dirfd_op: &OpTy<'tcx, Tag>, // Should be an `int`
922 pathname_op: &OpTy<'tcx, Tag>, // Should be a `const char *`
923 flags_op: &OpTy<'tcx, Tag>, // Should be an `int`
924 mask_op: &OpTy<'tcx, Tag>, // Should be an `unsigned int`
925 statxbuf_op: &OpTy<'tcx, Tag>, // Should be a `struct statx *`
926 ) -> InterpResult<'tcx, i32> {
927 let this = self.eval_context_mut();
929 this.assert_target_os("linux", "statx");
931 let dirfd = this.read_scalar(dirfd_op)?.to_i32()?;
932 let pathname_ptr = this.read_pointer(pathname_op)?;
933 let flags = this.read_scalar(flags_op)?.to_i32()?;
934 let _mask = this.read_scalar(mask_op)?.to_u32()?;
935 let statxbuf_ptr = this.read_pointer(statxbuf_op)?;
937 // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
938 if this.ptr_is_null(statxbuf_ptr)? || this.ptr_is_null(pathname_ptr)? {
939 let efault = this.eval_libc("EFAULT")?;
940 this.set_last_error(efault)?;
944 // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
945 // proper `MemPlace` and then write the results of this function to it. However, the
946 // `syscall` function is untyped. This means that all the `statx` parameters are provided
947 // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
948 // `statxbuf_op` by using the `libc::statx` struct type.
950 // FIXME: This long path is required because `libc::statx` is an struct and also a
951 // function and `resolve_path` is returning the latter.
953 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])
954 .ty(*this.tcx, ty::ParamEnv::reveal_all());
955 let statx_layout = this.layout_of(statx_ty)?;
956 MPlaceTy::from_aligned_ptr(statxbuf_ptr, statx_layout)
959 let path = this.read_path_from_c_str(pathname_ptr)?.into_owned();
960 // See <https://github.com/rust-lang/rust/pull/79196> for a discussion of argument sizes.
961 let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
963 // * interpreting `path` as an absolute directory,
964 // * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
965 // * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
967 // Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
968 // found this error, please open an issue reporting it.
969 if !(path.is_absolute()
970 || dirfd == this.eval_libc_i32("AT_FDCWD")?
971 || (path.as_os_str().is_empty() && empty_path_flag))
974 "using statx is only supported with absolute paths, relative paths with the file \
975 descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
980 // Reject if isolation is enabled.
981 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
982 this.reject_in_isolation("`statx`", reject_with)?;
983 let ecode = if path.is_absolute() || dirfd == this.eval_libc_i32("AT_FDCWD")? {
984 // since `path` is provided, either absolute or
985 // relative to CWD, `EACCES` is the most relevant.
986 this.eval_libc("EACCES")?
988 // `dirfd` is set to target file, and `path` is empty
989 // (or we would have hit the `throw_unsup_format`
990 // above). `EACCES` would violate the spec.
991 assert!(empty_path_flag);
992 this.eval_libc("EBADF")?
994 this.set_last_error(ecode)?;
998 // the `_mask_op` paramter specifies the file information that the caller requested.
999 // However `statx` is allowed to return information that was not requested or to not
1000 // return information that was requested. This `mask` represents the information we can
1001 // actually provide for any target.
1003 this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
1005 // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
1007 let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
1009 // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
1010 // represented by dirfd, whether it's a directory or otherwise.
1011 let metadata = if path.as_os_str().is_empty() && empty_path_flag {
1012 FileMetadata::from_fd(this, dirfd)?
1014 FileMetadata::from_path(this, &path, follow_symlink)?
1016 let metadata = match metadata {
1017 Some(metadata) => metadata,
1018 None => return Ok(-1),
1021 // The `mode` field specifies the type of the file and the permissions over the file for
1022 // the owner, its group and other users. Given that we can only provide the file type
1023 // without using platform specific methods, we only set the bits corresponding to the file
1024 // type. This should be an `__u16` but `libc` provides its values as `u32`.
1025 let mode: u16 = metadata
1029 .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
1031 // We need to set the corresponding bits of `mask` if the access, creation and modification
1032 // times were available. Otherwise we let them be zero.
1033 let (access_sec, access_nsec) = metadata
1036 mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
1037 InterpResult::Ok(tup)
1039 .unwrap_or(Ok((0, 0)))?;
1041 let (created_sec, created_nsec) = metadata
1044 mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
1045 InterpResult::Ok(tup)
1047 .unwrap_or(Ok((0, 0)))?;
1049 let (modified_sec, modified_nsec) = metadata
1052 mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
1053 InterpResult::Ok(tup)
1055 .unwrap_or(Ok((0, 0)))?;
1057 // Now we write everything to `statxbuf`. We write a zero for the unavailable fields.
1058 this.write_int_fields_named(
1060 ("stx_mask", mask.into()),
1062 ("stx_attributes", 0),
1066 ("stx_mode", mode.into()),
1068 ("stx_size", metadata.size.into()),
1070 ("stx_attributes_mask", 0),
1071 ("stx_rdev_major", 0),
1072 ("stx_rdev_minor", 0),
1073 ("stx_dev_major", 0),
1074 ("stx_dev_minor", 0),
1078 this.write_int_fields(
1080 access_sec.into(), // stx_atime.tv_sec
1081 access_nsec.into(), // stx_atime.tv_nsec
1083 &this.mplace_field_named(&statxbuf, "stx_atime")?,
1085 this.write_int_fields(
1087 created_sec.into(), // stx_btime.tv_sec
1088 created_nsec.into(), // stx_btime.tv_nsec
1090 &this.mplace_field_named(&statxbuf, "stx_btime")?,
1092 this.write_int_fields(
1094 0.into(), // stx_ctime.tv_sec
1095 0.into(), // stx_ctime.tv_nsec
1097 &this.mplace_field_named(&statxbuf, "stx_ctime")?,
1099 this.write_int_fields(
1101 modified_sec.into(), // stx_mtime.tv_sec
1102 modified_nsec.into(), // stx_mtime.tv_nsec
1104 &this.mplace_field_named(&statxbuf, "stx_mtime")?,
1112 oldpath_op: &OpTy<'tcx, Tag>,
1113 newpath_op: &OpTy<'tcx, Tag>,
1114 ) -> InterpResult<'tcx, i32> {
1115 let this = self.eval_context_mut();
1117 let oldpath_ptr = this.read_pointer(oldpath_op)?;
1118 let newpath_ptr = this.read_pointer(newpath_op)?;
1120 if this.ptr_is_null(oldpath_ptr)? || this.ptr_is_null(newpath_ptr)? {
1121 let efault = this.eval_libc("EFAULT")?;
1122 this.set_last_error(efault)?;
1126 let oldpath = this.read_path_from_c_str(oldpath_ptr)?;
1127 let newpath = this.read_path_from_c_str(newpath_ptr)?;
1129 // Reject if isolation is enabled.
1130 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1131 this.reject_in_isolation("`rename`", reject_with)?;
1132 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
1136 let result = rename(oldpath, newpath).map(|_| 0);
1138 this.try_unwrap_io_result(result)
1143 path_op: &OpTy<'tcx, Tag>,
1144 mode_op: &OpTy<'tcx, Tag>,
1145 ) -> InterpResult<'tcx, i32> {
1146 let this = self.eval_context_mut();
1148 #[cfg_attr(not(unix), allow(unused_variables))]
1149 let mode = if this.tcx.sess.target.os == "macos" {
1150 u32::from(this.read_scalar(mode_op)?.to_u16()?)
1152 this.read_scalar(mode_op)?.to_u32()?
1155 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
1157 // Reject if isolation is enabled.
1158 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1159 this.reject_in_isolation("`mkdir`", reject_with)?;
1160 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
1164 #[cfg_attr(not(unix), allow(unused_mut))]
1165 let mut builder = DirBuilder::new();
1167 // If the host supports it, forward on the mode of the directory
1168 // (i.e. permission bits and the sticky bit)
1171 use std::os::unix::fs::DirBuilderExt;
1172 builder.mode(mode.into());
1175 let result = builder.create(path).map(|_| 0i32);
1177 this.try_unwrap_io_result(result)
1180 fn rmdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1181 let this = self.eval_context_mut();
1183 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
1185 // Reject if isolation is enabled.
1186 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1187 this.reject_in_isolation("`rmdir`", reject_with)?;
1188 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
1192 let result = remove_dir(path).map(|_| 0i32);
1194 this.try_unwrap_io_result(result)
1197 fn opendir(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
1198 let this = self.eval_context_mut();
1200 let name = this.read_path_from_c_str(this.read_pointer(name_op)?)?;
1202 // Reject if isolation is enabled.
1203 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1204 this.reject_in_isolation("`opendir`", reject_with)?;
1205 let eacc = this.eval_libc("EACCES")?;
1206 this.set_last_error(eacc)?;
1207 return Ok(Scalar::null_ptr(this));
1210 let result = read_dir(name);
1214 let id = this.machine.dir_handler.insert_new(dir_iter);
1216 // The libc API for opendir says that this method returns a pointer to an opaque
1217 // structure, but we are returning an ID number. Thus, pass it as a scalar of
1219 Ok(Scalar::from_machine_usize(id, this))
1222 this.set_last_error_from_io_error(e.kind())?;
1223 Ok(Scalar::null_ptr(this))
1228 fn linux_readdir64(&mut self, dirp_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
1229 let this = self.eval_context_mut();
1231 this.assert_target_os("linux", "readdir64");
1233 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1235 // Reject if isolation is enabled.
1236 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1237 this.reject_in_isolation("`readdir`", reject_with)?;
1238 let eacc = this.eval_libc("EBADF")?;
1239 this.set_last_error(eacc)?;
1240 return Ok(Scalar::null_ptr(this));
1243 let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1244 err_unsup_format!("the DIR pointer passed to readdir64 did not come from opendir")
1247 let entry = match open_dir.read_dir.next() {
1248 Some(Ok(dir_entry)) => {
1249 // Write the directory entry into a newly allocated buffer.
1250 // The name is written with write_bytes, while the rest of the
1251 // dirent64 struct is written using write_int_fields.
1254 // pub struct dirent64 {
1255 // pub d_ino: ino64_t,
1256 // pub d_off: off64_t,
1257 // pub d_reclen: c_ushort,
1258 // pub d_type: c_uchar,
1259 // pub d_name: [c_char; 256],
1262 let mut name = dir_entry.file_name(); // not a Path as there are no separators!
1263 name.push("\0"); // Add a NUL terminator
1264 let name_bytes = os_str_to_bytes(&name)?;
1265 let name_len = u64::try_from(name_bytes.len()).unwrap();
1267 let dirent64_layout = this.libc_ty_layout("dirent64")?;
1268 let d_name_offset = dirent64_layout.fields.offset(4 /* d_name */).bytes();
1269 let size = d_name_offset.checked_add(name_len).unwrap();
1272 this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::Runtime)?;
1274 // If the host is a Unix system, fill in the inode number with its real value.
1275 // If not, use 0 as a fallback value.
1277 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1281 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1283 this.write_int_fields(
1285 ino.into(), // d_ino
1287 size.into(), // d_reclen
1288 file_type.into(), // d_type
1290 &MPlaceTy::from_aligned_ptr(entry, dirent64_layout),
1293 let name_ptr = entry.offset(Size::from_bytes(d_name_offset), this)?;
1294 this.write_bytes_ptr(name_ptr, name_bytes.iter().copied())?;
1299 // end of stream: return NULL
1303 this.set_last_error_from_io_error(e.kind())?;
1308 let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).unwrap();
1309 let old_entry = std::mem::replace(&mut open_dir.entry, entry);
1310 this.free(old_entry, MiriMemoryKind::Runtime)?;
1312 Ok(Scalar::from_maybe_pointer(entry, this))
1317 dirp_op: &OpTy<'tcx, Tag>,
1318 entry_op: &OpTy<'tcx, Tag>,
1319 result_op: &OpTy<'tcx, Tag>,
1320 ) -> InterpResult<'tcx, i32> {
1321 let this = self.eval_context_mut();
1323 this.assert_target_os("macos", "readdir_r");
1325 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1327 // Reject if isolation is enabled.
1328 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1329 this.reject_in_isolation("`readdir_r`", reject_with)?;
1330 // Set error code as "EBADF" (bad fd)
1331 return this.handle_not_found();
1334 let open_dir = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1335 err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
1337 match open_dir.read_dir.next() {
1338 Some(Ok(dir_entry)) => {
1339 // Write into entry, write pointer to result, return 0 on success.
1340 // The name is written with write_os_str_to_c_str, while the rest of the
1341 // dirent struct is written using write_int_fields.
1344 // pub struct dirent {
1346 // pub d_seekoff: u64,
1347 // pub d_reclen: u16,
1348 // pub d_namlen: u16,
1350 // pub d_name: [c_char; 1024],
1353 let entry_place = this.deref_operand(entry_op)?;
1354 let name_place = this.mplace_field(&entry_place, 5)?;
1356 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1357 let (name_fits, file_name_len) = this.write_os_str_to_c_str(
1360 name_place.layout.size.bytes(),
1363 throw_unsup_format!(
1364 "a directory entry had a name too large to fit in libc::dirent"
1368 let entry_place = this.deref_operand(entry_op)?;
1370 // If the host is a Unix system, fill in the inode number with its real value.
1371 // If not, use 0 as a fallback value.
1373 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1377 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1379 this.write_int_fields(
1381 ino.into(), // d_ino
1384 file_name_len.into(), // d_namlen
1385 file_type.into(), // d_type
1390 let result_place = this.deref_operand(result_op)?;
1391 this.write_scalar(this.read_scalar(entry_op)?, &result_place.into())?;
1396 // end of stream: return 0, assign *result=NULL
1397 this.write_null(&this.deref_operand(result_op)?.into())?;
1401 match e.raw_os_error() {
1402 // return positive error number on error
1403 Some(error) => Ok(error),
1405 throw_unsup_format!(
1406 "the error {} couldn't be converted to a return value",
1414 fn closedir(&mut self, dirp_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1415 let this = self.eval_context_mut();
1417 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1419 // Reject if isolation is enabled.
1420 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1421 this.reject_in_isolation("`closedir`", reject_with)?;
1422 // Set error code as "EBADF" (bad fd)
1423 return this.handle_not_found();
1426 if let Some(open_dir) = this.machine.dir_handler.streams.remove(&dirp) {
1427 this.free(open_dir.entry, MiriMemoryKind::Runtime)?;
1431 this.handle_not_found()
1437 fd_op: &OpTy<'tcx, Tag>,
1438 length_op: &OpTy<'tcx, Tag>,
1439 ) -> InterpResult<'tcx, i32> {
1440 let this = self.eval_context_mut();
1442 let fd = this.read_scalar(fd_op)?.to_i32()?;
1443 let length = this.read_scalar(length_op)?.to_i64()?;
1445 // Reject if isolation is enabled.
1446 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1447 this.reject_in_isolation("`ftruncate64`", reject_with)?;
1448 // Set error code as "EBADF" (bad fd)
1449 return this.handle_not_found();
1452 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
1453 // FIXME: Support ftruncate64 for all FDs
1454 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1456 if let Ok(length) = length.try_into() {
1457 let result = file.set_len(length);
1458 this.try_unwrap_io_result(result.map(|_| 0i32))
1460 let einval = this.eval_libc("EINVAL")?;
1461 this.set_last_error(einval)?;
1465 // The file is not writable
1466 let einval = this.eval_libc("EINVAL")?;
1467 this.set_last_error(einval)?;
1471 this.handle_not_found()
1475 fn fsync(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1476 // On macOS, `fsync` (unlike `fcntl(F_FULLFSYNC)`) does not wait for the
1477 // underlying disk to finish writing. In the interest of host compatibility,
1478 // we conservatively implement this with `sync_all`, which
1479 // *does* wait for the disk.
1481 let this = self.eval_context_mut();
1483 let fd = this.read_scalar(fd_op)?.to_i32()?;
1485 // Reject if isolation is enabled.
1486 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1487 this.reject_in_isolation("`fsync`", reject_with)?;
1488 // Set error code as "EBADF" (bad fd)
1489 return this.handle_not_found();
1492 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1493 // FIXME: Support fsync for all FDs
1494 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1495 let io_result = maybe_sync_file(&file, *writable, File::sync_all);
1496 this.try_unwrap_io_result(io_result)
1498 this.handle_not_found()
1502 fn fdatasync(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1503 let this = self.eval_context_mut();
1505 let fd = this.read_scalar(fd_op)?.to_i32()?;
1507 // Reject if isolation is enabled.
1508 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1509 this.reject_in_isolation("`fdatasync`", reject_with)?;
1510 // Set error code as "EBADF" (bad fd)
1511 return this.handle_not_found();
1514 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1515 // FIXME: Support fdatasync for all FDs
1516 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1517 let io_result = maybe_sync_file(&file, *writable, File::sync_data);
1518 this.try_unwrap_io_result(io_result)
1520 this.handle_not_found()
1526 fd_op: &OpTy<'tcx, Tag>,
1527 offset_op: &OpTy<'tcx, Tag>,
1528 nbytes_op: &OpTy<'tcx, Tag>,
1529 flags_op: &OpTy<'tcx, Tag>,
1530 ) -> InterpResult<'tcx, i32> {
1531 let this = self.eval_context_mut();
1533 let fd = this.read_scalar(fd_op)?.to_i32()?;
1534 let offset = this.read_scalar(offset_op)?.to_i64()?;
1535 let nbytes = this.read_scalar(nbytes_op)?.to_i64()?;
1536 let flags = this.read_scalar(flags_op)?.to_i32()?;
1538 if offset < 0 || nbytes < 0 {
1539 let einval = this.eval_libc("EINVAL")?;
1540 this.set_last_error(einval)?;
1543 let allowed_flags = this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_BEFORE")?
1544 | this.eval_libc_i32("SYNC_FILE_RANGE_WRITE")?
1545 | this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_AFTER")?;
1546 if flags & allowed_flags != flags {
1547 let einval = this.eval_libc("EINVAL")?;
1548 this.set_last_error(einval)?;
1552 // Reject if isolation is enabled.
1553 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1554 this.reject_in_isolation("`sync_file_range`", reject_with)?;
1555 // Set error code as "EBADF" (bad fd)
1556 return this.handle_not_found();
1559 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1560 // FIXME: Support sync_data_range for all FDs
1561 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1562 let io_result = maybe_sync_file(&file, *writable, File::sync_data);
1563 this.try_unwrap_io_result(io_result)
1565 this.handle_not_found()
1571 pathname_op: &OpTy<'tcx, Tag>,
1572 buf_op: &OpTy<'tcx, Tag>,
1573 bufsize_op: &OpTy<'tcx, Tag>,
1574 ) -> InterpResult<'tcx, i64> {
1575 let this = self.eval_context_mut();
1577 let pathname = this.read_path_from_c_str(this.read_pointer(pathname_op)?)?;
1578 let buf = this.read_pointer(buf_op)?;
1579 let bufsize = this.read_scalar(bufsize_op)?.to_machine_usize(this)?;
1581 // Reject if isolation is enabled.
1582 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1583 this.reject_in_isolation("`readlink`", reject_with)?;
1584 let eacc = this.eval_libc("EACCES")?;
1585 this.set_last_error(eacc)?;
1589 let result = std::fs::read_link(pathname);
1592 let resolved = this.convert_path_separator(
1593 Cow::Borrowed(resolved.as_ref()),
1594 crate::shims::os_str::PathConversion::HostToTarget,
1596 let mut path_bytes = crate::shims::os_str::os_str_to_bytes(resolved.as_ref())?;
1597 let bufsize: usize = bufsize.try_into().unwrap();
1598 if path_bytes.len() > bufsize {
1599 path_bytes = &path_bytes[..bufsize]
1601 // 'readlink' truncates the resolved path if
1602 // the provided buffer is not large enough.
1603 this.write_bytes_ptr(buf, path_bytes.iter().copied())?;
1604 Ok(path_bytes.len().try_into().unwrap())
1607 this.set_last_error_from_io_error(e.kind())?;
1614 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
1615 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
1617 fn extract_sec_and_nsec<'tcx>(
1618 time: std::io::Result<SystemTime>,
1619 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
1622 let duration = system_time_to_duration(&time)?;
1623 Ok((duration.as_secs(), duration.subsec_nanos()))
1628 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
1630 struct FileMetadata {
1633 created: Option<(u64, u32)>,
1634 accessed: Option<(u64, u32)>,
1635 modified: Option<(u64, u32)>,
1639 fn from_path<'tcx, 'mir>(
1640 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1642 follow_symlink: bool,
1643 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1645 if follow_symlink { std::fs::metadata(path) } else { std::fs::symlink_metadata(path) };
1647 FileMetadata::from_meta(ecx, metadata)
1650 fn from_fd<'tcx, 'mir>(
1651 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1653 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1654 let option = ecx.machine.file_handler.handles.get(&fd);
1655 let file = match option {
1656 Some(file_descriptor) => &file_descriptor.as_file_handle()?.file,
1657 None => return ecx.handle_not_found().map(|_: i32| None),
1659 let metadata = file.metadata();
1661 FileMetadata::from_meta(ecx, metadata)
1664 fn from_meta<'tcx, 'mir>(
1665 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1666 metadata: Result<std::fs::Metadata, std::io::Error>,
1667 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1668 let metadata = match metadata {
1669 Ok(metadata) => metadata,
1671 ecx.set_last_error_from_io_error(e.kind())?;
1676 let file_type = metadata.file_type();
1678 let mode_name = if file_type.is_file() {
1680 } else if file_type.is_dir() {
1686 let mode = ecx.eval_libc(mode_name)?;
1688 let size = metadata.len();
1690 let created = extract_sec_and_nsec(metadata.created())?;
1691 let accessed = extract_sec_and_nsec(metadata.accessed())?;
1692 let modified = extract_sec_and_nsec(metadata.modified())?;
1694 // FIXME: Provide more fields using platform specific methods.
1695 Ok(Some(FileMetadata { mode, size, created, accessed, modified }))