1 use std::collections::BTreeMap;
2 use std::convert::{TryFrom, TryInto};
3 use std::fs::{read_dir, remove_dir, remove_file, rename, DirBuilder, File, FileType, OpenOptions, ReadDir};
4 use std::io::{self, Read, Seek, SeekFrom, Write};
6 use std::time::SystemTime;
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_target::abi::{Align, LayoutOf, Size};
15 use stacked_borrows::Tag;
16 use helpers::{check_arg_count, immty_from_int_checked, immty_from_uint_checked};
17 use shims::time::system_time_to_duration;
25 trait FileDescriptor : std::fmt::Debug {
26 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle>;
28 fn read<'tcx>(&mut self, communicate_allowed: bool, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>>;
29 fn write<'tcx>(&mut self, communicate_allowed: bool, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>>;
30 fn seek<'tcx>(&mut self, communicate_allowed: bool, offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>>;
31 fn close<'tcx>(self: Box<Self>, _communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>>;
33 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>>;
36 impl FileDescriptor for FileHandle {
37 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
41 fn read<'tcx>(&mut self, communicate_allowed: bool, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
42 assert!(communicate_allowed, "isolation should have prevented even opening a file");
43 Ok(self.file.read(bytes))
46 fn write<'tcx>(&mut self, communicate_allowed: bool, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
47 assert!(communicate_allowed, "isolation should have prevented even opening a file");
48 Ok(self.file.write(bytes))
51 fn seek<'tcx>(&mut self, communicate_allowed: bool, offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
52 assert!(communicate_allowed, "isolation should have prevented even opening a file");
53 Ok(self.file.seek(offset))
56 fn close<'tcx>(self: Box<Self>, communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>> {
57 assert!(communicate_allowed, "isolation should have prevented even opening a file");
58 // We sync the file if it was opened in a mode different than read-only.
60 // `File::sync_all` does the checks that are done when closing a file. We do this to
61 // to handle possible errors correctly.
62 let result = self.file.sync_all().map(|_| 0i32);
63 // Now we actually close the file.
65 // And return the result.
68 // We drop the file, this closes it but ignores any errors
69 // produced when closing it. This is done because
70 // `File::sync_all` cannot be done over files like
71 // `/dev/urandom` which are read-only. Check
72 // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439
73 // for a deeper discussion.
79 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
80 let duplicated = self.file.try_clone()?;
81 Ok(Box::new(FileHandle { file: duplicated, writable: self.writable }))
85 impl FileDescriptor for io::Stdin {
86 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
87 throw_unsup_format!("stdin cannot be used as FileHandle");
90 fn read<'tcx>(&mut self, communicate_allowed: bool, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
91 if !communicate_allowed {
92 // We want isolation mode to be deterministic, so we have to disallow all reads, even stdin.
93 helpers::isolation_error("`read` from stdin")?;
95 Ok(Read::read(self, bytes))
98 fn write<'tcx>(&mut self, _communicate_allowed: bool, _bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
99 throw_unsup_format!("cannot write to stdin");
102 fn seek<'tcx>(&mut self, _communicate_allowed: bool, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
103 throw_unsup_format!("cannot seek on stdin");
106 fn close<'tcx>(self: Box<Self>, _communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>> {
107 throw_unsup_format!("stdin cannot be closed");
110 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
111 Ok(Box::new(io::stdin()))
115 impl FileDescriptor for io::Stdout {
116 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
117 throw_unsup_format!("stdout cannot be used as FileHandle");
120 fn read<'tcx>(&mut self, _communicate_allowed: bool, _bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
121 throw_unsup_format!("cannot read from stdout");
124 fn write<'tcx>(&mut self, _communicate_allowed: bool, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
125 // We allow writing to stderr even with isolation enabled.
126 let result = Write::write(self, bytes);
127 // Stdout is buffered, flush to make sure it appears on the
128 // screen. This is the write() syscall of the interpreted
129 // program, we want it to correspond to a write() syscall on
130 // the host -- there is no good in adding extra buffering
132 io::stdout().flush().unwrap();
137 fn seek<'tcx>(&mut self, _communicate_allowed: bool, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
138 throw_unsup_format!("cannot seek on stdout");
141 fn close<'tcx>(self: Box<Self>, _communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>> {
142 throw_unsup_format!("stdout cannot be closed");
145 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
146 Ok(Box::new(io::stdout()))
150 impl FileDescriptor for io::Stderr {
151 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
152 throw_unsup_format!("stderr cannot be used as FileHandle");
155 fn read<'tcx>(&mut self, _communicate_allowed: bool, _bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
156 throw_unsup_format!("cannot read from stderr");
159 fn write<'tcx>(&mut self, _communicate_allowed: bool, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
160 // We allow writing to stderr even with isolation enabled.
161 // No need to flush, stderr is not buffered.
162 Ok(Write::write(self, bytes))
165 fn seek<'tcx>(&mut self, _communicate_allowed: bool, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
166 throw_unsup_format!("cannot seek on stderr");
169 fn close<'tcx>(self: Box<Self>, _communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>> {
170 throw_unsup_format!("stderr cannot be closed");
173 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
174 Ok(Box::new(io::stderr()))
179 pub struct FileHandler {
180 handles: BTreeMap<i32, Box<dyn FileDescriptor>>,
183 impl<'tcx> Default for FileHandler {
184 fn default() -> Self {
185 let mut handles: BTreeMap<_, Box<dyn FileDescriptor>> = BTreeMap::new();
186 handles.insert(0i32, Box::new(io::stdin()));
187 handles.insert(1i32, Box::new(io::stdout()));
188 handles.insert(2i32, Box::new(io::stderr()));
195 impl<'tcx> FileHandler {
196 fn insert_fd(&mut self, file_handle: Box<dyn FileDescriptor>) -> i32 {
197 self.insert_fd_with_min_fd(file_handle, 0)
200 fn insert_fd_with_min_fd(&mut self, file_handle: Box<dyn FileDescriptor>, min_fd: i32) -> i32 {
201 // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
202 // between used FDs, the find_map combinator will return it. If the first such unused FD
203 // is after all other used FDs, the find_map combinator will return None, and we will use
204 // the FD following the greatest FD thus far.
205 let candidate_new_fd = self
209 .find_map(|((fd, _fh), counter)| {
211 // There was a gap in the fds stored, return the first unused one
212 // (note that this relies on BTreeMap iterating in key order)
215 // This fd is used, keep going
219 let new_fd = candidate_new_fd.unwrap_or_else(|| {
220 // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
221 // maximum fd in the map
222 self.handles.last_key_value().map(|(fd, _)| fd.checked_add(1).unwrap()).unwrap_or(min_fd)
225 self.handles.insert(new_fd, file_handle).unwrap_none();
230 impl<'mir, 'tcx: 'mir> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
231 trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
232 /// Emulate `stat` or `lstat` on `macos`. This function is not intended to be
233 /// called directly from `emulate_foreign_item_by_name`, so it does not check if isolation is
234 /// disabled or if the target OS is the correct one. Please use `macos_stat` or
235 /// `macos_lstat` instead.
236 fn macos_stat_or_lstat(
238 follow_symlink: bool,
239 path_op: OpTy<'tcx, Tag>,
240 buf_op: OpTy<'tcx, Tag>,
241 ) -> InterpResult<'tcx, i32> {
242 let this = self.eval_context_mut();
244 let path_scalar = this.read_scalar(path_op)?.check_init()?;
245 let path = this.read_path_from_c_str(path_scalar)?.into_owned();
247 let metadata = match FileMetadata::from_path(this, &path, follow_symlink)? {
248 Some(metadata) => metadata,
249 None => return Ok(-1),
251 this.macos_stat_write_buf(metadata, buf_op)
254 fn macos_stat_write_buf(
256 metadata: FileMetadata,
257 buf_op: OpTy<'tcx, Tag>,
258 ) -> InterpResult<'tcx, i32> {
259 let this = self.eval_context_mut();
261 let mode: u16 = metadata.mode.to_u16()?;
263 let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
264 let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
265 let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
267 let dev_t_layout = this.libc_ty_layout("dev_t")?;
268 let mode_t_layout = this.libc_ty_layout("mode_t")?;
269 let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
270 let ino_t_layout = this.libc_ty_layout("ino_t")?;
271 let uid_t_layout = this.libc_ty_layout("uid_t")?;
272 let gid_t_layout = this.libc_ty_layout("gid_t")?;
273 let time_t_layout = this.libc_ty_layout("time_t")?;
274 let long_layout = this.libc_ty_layout("c_long")?;
275 let off_t_layout = this.libc_ty_layout("off_t")?;
276 let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
277 let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
278 let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
281 immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
282 immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
283 immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
284 immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
285 immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
286 immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
287 immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
288 immty_from_uint_checked(0u128, uint32_t_layout)?, // padding
289 immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
290 immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
291 immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
292 immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
293 immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
294 immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
295 immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
296 immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
297 immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
298 immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
299 immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
300 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
301 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
304 let buf = this.deref_operand(buf_op)?;
305 this.write_packed_immediates(buf, &imms)?;
310 /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
311 /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
312 /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
313 /// types (like `read`, that returns an `i64`).
314 fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
315 let this = self.eval_context_mut();
316 let ebadf = this.eval_libc("EBADF")?;
317 this.set_last_error(ebadf)?;
321 fn file_type_to_d_type(&mut self, file_type: std::io::Result<FileType>) -> InterpResult<'tcx, i32> {
322 let this = self.eval_context_mut();
325 if file_type.is_dir() {
326 Ok(this.eval_libc("DT_DIR")?.to_u8()?.into())
327 } else if file_type.is_file() {
328 Ok(this.eval_libc("DT_REG")?.to_u8()?.into())
329 } else if file_type.is_symlink() {
330 Ok(this.eval_libc("DT_LNK")?.to_u8()?.into())
332 // Certain file types are only supported when the host is a Unix system.
333 // (i.e. devices and sockets) If it is, check those cases, if not, fall back to
334 // DT_UNKNOWN sooner.
338 use std::os::unix::fs::FileTypeExt;
339 if file_type.is_block_device() {
340 Ok(this.eval_libc("DT_BLK")?.to_u8()?.into())
341 } else if file_type.is_char_device() {
342 Ok(this.eval_libc("DT_CHR")?.to_u8()?.into())
343 } else if file_type.is_fifo() {
344 Ok(this.eval_libc("DT_FIFO")?.to_u8()?.into())
345 } else if file_type.is_socket() {
346 Ok(this.eval_libc("DT_SOCK")?.to_u8()?.into())
348 Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
352 Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
355 Err(e) => return match e.raw_os_error() {
356 Some(error) => Ok(error),
357 None => throw_unsup_format!("the error {} couldn't be converted to a return value", e),
364 pub struct DirHandler {
365 /// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
368 /// When opendir is called, a directory iterator is created on the host for the target
369 /// directory, and an entry is stored in this hash map, indexed by an ID which represents
370 /// the directory stream. When readdir is called, the directory stream ID is used to look up
371 /// the corresponding ReadDir iterator from this map, and information from the next
372 /// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
374 streams: FxHashMap<u64, ReadDir>,
375 /// ID number to be used by the next call to opendir
380 fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
381 let id = self.next_id;
383 self.streams.insert(id, read_dir).unwrap_none();
388 impl Default for DirHandler {
389 fn default() -> DirHandler {
391 streams: FxHashMap::default(),
392 // Skip 0 as an ID, because it looks like a null pointer to libc
398 fn maybe_sync_file(file: &File, writable: bool, operation: fn(&File) -> std::io::Result<()>) -> std::io::Result<i32> {
399 if !writable && cfg!(windows) {
400 // sync_all() and sync_data() will return an error on Windows hosts if the file is not opened
401 // for writing. (FlushFileBuffers requires that the file handle have the
402 // GENERIC_WRITE right)
405 let result = operation(file);
410 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
411 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
414 path_op: OpTy<'tcx, Tag>,
415 flag_op: OpTy<'tcx, Tag>,
416 mode_op: OpTy<'tcx, Tag>,
417 ) -> InterpResult<'tcx, i32> {
418 let this = self.eval_context_mut();
420 this.check_no_isolation("`open`")?;
422 let flag = this.read_scalar(flag_op)?.to_i32()?;
424 // Get the mode. On macOS, the argument type `mode_t` is actually `u16`, but
425 // C integer promotion rules mean that on the ABI level, it gets passed as `u32`
426 // (see https://github.com/rust-lang/rust/issues/71915).
427 let mode = this.read_scalar(mode_op)?.to_u32()?;
429 throw_unsup_format!("non-default mode 0o{:o} is not supported", mode);
432 let mut options = OpenOptions::new();
434 let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
435 let o_wronly = this.eval_libc_i32("O_WRONLY")?;
436 let o_rdwr = this.eval_libc_i32("O_RDWR")?;
437 // The first two bits of the flag correspond to the access mode in linux, macOS and
438 // windows. We need to check that in fact the access mode flags for the current target
439 // only use these two bits, otherwise we are in an unsupported target and should error.
440 if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
441 throw_unsup_format!("access mode flags on this target are unsupported");
443 let mut writable = true;
445 // Now we check the access mode
446 let access_mode = flag & 0b11;
448 if access_mode == o_rdonly {
451 } else if access_mode == o_wronly {
453 } else if access_mode == o_rdwr {
454 options.read(true).write(true);
456 throw_unsup_format!("unsupported access mode {:#x}", access_mode);
458 // We need to check that there aren't unsupported options in `flag`. For this we try to
459 // reproduce the content of `flag` in the `mirror` variable using only the supported
461 let mut mirror = access_mode;
463 let o_append = this.eval_libc_i32("O_APPEND")?;
464 if flag & o_append != 0 {
465 options.append(true);
468 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
469 if flag & o_trunc != 0 {
470 options.truncate(true);
473 let o_creat = this.eval_libc_i32("O_CREAT")?;
474 if flag & o_creat != 0 {
477 let o_excl = this.eval_libc_i32("O_EXCL")?;
478 if flag & o_excl != 0 {
480 options.create_new(true);
482 options.create(true);
485 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
486 if flag & o_cloexec != 0 {
487 // We do not need to do anything for this flag because `std` already sets it.
488 // (Technically we do not support *not* setting this flag, but we ignore that.)
491 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
492 // then we throw an error.
494 throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
497 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
499 let fd = options.open(&path).map(|file| {
500 let fh = &mut this.machine.file_handler;
501 fh.insert_fd(Box::new(FileHandle { file, writable }))
504 this.try_unwrap_io_result(fd)
509 args: &[OpTy<'tcx, Tag>],
510 ) -> InterpResult<'tcx, i32> {
511 let this = self.eval_context_mut();
513 this.check_no_isolation("`fcntl`")?;
516 throw_ub_format!("incorrect number of arguments for fcntl: got {}, expected at least 2", args.len());
518 let fd = this.read_scalar(args[0])?.to_i32()?;
519 let cmd = this.read_scalar(args[1])?.to_i32()?;
520 // We only support getting the flags for a descriptor.
521 if cmd == this.eval_libc_i32("F_GETFD")? {
522 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
523 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
524 // always sets this flag when opening a file. However we still need to check that the
525 // file itself is open.
526 let &[_, _] = check_arg_count(args)?;
527 if this.machine.file_handler.handles.contains_key(&fd) {
528 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
530 this.handle_not_found()
532 } else if cmd == this.eval_libc_i32("F_DUPFD")?
533 || cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
535 // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
536 // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
537 // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
538 // thus they can share the same implementation here.
539 let &[_, _, start] = check_arg_count(args)?;
540 let start = this.read_scalar(start)?.to_i32()?;
542 let fh = &mut this.machine.file_handler;
544 match fh.handles.get_mut(&fd) {
545 Some(file_descriptor) => {
546 let dup_result = file_descriptor.dup();
548 Ok(dup_fd) => Ok(fh.insert_fd_with_min_fd(dup_fd, start)),
550 this.set_last_error_from_io_error(e)?;
555 None => return this.handle_not_found(),
557 } else if this.tcx.sess.target.target.target_os == "macos"
558 && cmd == this.eval_libc_i32("F_FULLFSYNC")?
560 let &[_, _] = check_arg_count(args)?;
561 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
562 // FIXME: Support fullfsync for all FDs
563 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
564 let io_result = maybe_sync_file(&file, *writable, File::sync_all);
565 this.try_unwrap_io_result(io_result)
567 this.handle_not_found()
570 throw_unsup_format!("the {:#x} command is not supported for `fcntl`)", cmd);
574 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
575 let this = self.eval_context_mut();
577 let fd = this.read_scalar(fd_op)?.to_i32()?;
579 if let Some(file_descriptor) = this.machine.file_handler.handles.remove(&fd) {
580 let result = file_descriptor.close(this.machine.communicate)?;
581 this.try_unwrap_io_result(result)
583 this.handle_not_found()
592 ) -> InterpResult<'tcx, i64> {
593 let this = self.eval_context_mut();
595 // Isolation check is done via `FileDescriptor` trait.
597 trace!("Reading from FD {}, size {}", fd, count);
599 // Check that the *entire* buffer is actually valid memory.
600 this.memory.check_ptr_access(
602 Size::from_bytes(count),
603 Align::from_bytes(1).unwrap(),
606 // We cap the number of read bytes to the largest value that we are able to fit in both the
607 // host's and target's `isize`. This saves us from having to handle overflows later.
608 let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
610 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
611 trace!("read: FD mapped to {:?}", file_descriptor);
612 // We want to read at most `count` bytes. We are sure that `count` is not negative
613 // because it was a target's `usize`. Also we are sure that its smaller than
614 // `usize::MAX` because it is a host's `isize`.
615 let mut bytes = vec![0; count as usize];
616 // `File::read` never returns a value larger than `count`,
617 // so this cannot fail.
618 let result = file_descriptor
619 .read(this.machine.communicate, &mut bytes)?
620 .map(|c| i64::try_from(c).unwrap());
624 // If reading to `bytes` did not fail, we write those bytes to the buffer.
625 this.memory.write_bytes(buf, bytes)?;
629 this.set_last_error_from_io_error(e)?;
634 trace!("read: FD not found");
635 this.handle_not_found()
644 ) -> InterpResult<'tcx, i64> {
645 let this = self.eval_context_mut();
647 // Isolation check is done via `FileDescriptor` trait.
649 // Check that the *entire* buffer is actually valid memory.
650 this.memory.check_ptr_access(
652 Size::from_bytes(count),
653 Align::from_bytes(1).unwrap(),
656 // We cap the number of written bytes to the largest value that we are able to fit in both the
657 // host's and target's `isize`. This saves us from having to handle overflows later.
658 let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
660 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
661 let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
662 let result = file_descriptor
663 .write(this.machine.communicate, &bytes)?
664 .map(|c| i64::try_from(c).unwrap());
665 this.try_unwrap_io_result(result)
667 this.handle_not_found()
673 fd_op: OpTy<'tcx, Tag>,
674 offset_op: OpTy<'tcx, Tag>,
675 whence_op: OpTy<'tcx, Tag>,
676 ) -> InterpResult<'tcx, i64> {
677 let this = self.eval_context_mut();
679 // Isolation check is done via `FileDescriptor` trait.
681 let fd = this.read_scalar(fd_op)?.to_i32()?;
682 let offset = this.read_scalar(offset_op)?.to_i64()?;
683 let whence = this.read_scalar(whence_op)?.to_i32()?;
685 let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
686 SeekFrom::Start(u64::try_from(offset).unwrap())
687 } else if whence == this.eval_libc_i32("SEEK_CUR")? {
688 SeekFrom::Current(offset)
689 } else if whence == this.eval_libc_i32("SEEK_END")? {
690 SeekFrom::End(offset)
692 let einval = this.eval_libc("EINVAL")?;
693 this.set_last_error(einval)?;
697 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
698 let result = file_descriptor
699 .seek(this.machine.communicate, seek_from)?
700 .map(|offset| i64::try_from(offset).unwrap());
701 this.try_unwrap_io_result(result)
703 this.handle_not_found()
707 fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
708 let this = self.eval_context_mut();
710 this.check_no_isolation("`unlink`")?;
712 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
714 let result = remove_file(path).map(|_| 0);
715 this.try_unwrap_io_result(result)
720 target_op: OpTy<'tcx, Tag>,
721 linkpath_op: OpTy<'tcx, Tag>
722 ) -> InterpResult<'tcx, i32> {
724 fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
725 std::os::unix::fs::symlink(src, dst)
729 fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
730 use std::os::windows::fs;
732 fs::symlink_dir(src, dst)
734 fs::symlink_file(src, dst)
738 let this = self.eval_context_mut();
740 this.check_no_isolation("`symlink`")?;
742 let target = this.read_path_from_c_str(this.read_scalar(target_op)?.check_init()?)?;
743 let linkpath = this.read_path_from_c_str(this.read_scalar(linkpath_op)?.check_init()?)?;
745 let result = create_link(&target, &linkpath).map(|_| 0);
746 this.try_unwrap_io_result(result)
751 path_op: OpTy<'tcx, Tag>,
752 buf_op: OpTy<'tcx, Tag>,
753 ) -> InterpResult<'tcx, i32> {
754 let this = self.eval_context_mut();
755 this.assert_target_os("macos", "stat");
756 this.check_no_isolation("`stat`")?;
757 // `stat` always follows symlinks.
758 this.macos_stat_or_lstat(true, path_op, buf_op)
761 // `lstat` is used to get symlink metadata.
764 path_op: OpTy<'tcx, Tag>,
765 buf_op: OpTy<'tcx, Tag>,
766 ) -> InterpResult<'tcx, i32> {
767 let this = self.eval_context_mut();
768 this.assert_target_os("macos", "lstat");
769 this.check_no_isolation("`lstat`")?;
770 this.macos_stat_or_lstat(false, path_op, buf_op)
775 fd_op: OpTy<'tcx, Tag>,
776 buf_op: OpTy<'tcx, Tag>,
777 ) -> InterpResult<'tcx, i32> {
778 let this = self.eval_context_mut();
780 this.assert_target_os("macos", "fstat");
781 this.check_no_isolation("`fstat`")?;
783 let fd = this.read_scalar(fd_op)?.to_i32()?;
785 let metadata = match FileMetadata::from_fd(this, fd)? {
786 Some(metadata) => metadata,
787 None => return Ok(-1),
789 this.macos_stat_write_buf(metadata, buf_op)
794 dirfd_op: OpTy<'tcx, Tag>, // Should be an `int`
795 pathname_op: OpTy<'tcx, Tag>, // Should be a `const char *`
796 flags_op: OpTy<'tcx, Tag>, // Should be an `int`
797 _mask_op: OpTy<'tcx, Tag>, // Should be an `unsigned int`
798 statxbuf_op: OpTy<'tcx, Tag>, // Should be a `struct statx *`
799 ) -> InterpResult<'tcx, i32> {
800 let this = self.eval_context_mut();
802 this.assert_target_os("linux", "statx");
803 this.check_no_isolation("`statx`")?;
805 let statxbuf_scalar = this.read_scalar(statxbuf_op)?.check_init()?;
806 let pathname_scalar = this.read_scalar(pathname_op)?.check_init()?;
808 // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
809 if this.is_null(statxbuf_scalar)? || this.is_null(pathname_scalar)? {
810 let efault = this.eval_libc("EFAULT")?;
811 this.set_last_error(efault)?;
815 // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
816 // proper `MemPlace` and then write the results of this function to it. However, the
817 // `syscall` function is untyped. This means that all the `statx` parameters are provided
818 // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
819 // `statxbuf_op` by using the `libc::statx` struct type.
820 let statxbuf_place = {
821 // FIXME: This long path is required because `libc::statx` is an struct and also a
822 // function and `resolve_path` is returning the latter.
824 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])
825 .ty(*this.tcx, ty::ParamEnv::reveal_all());
826 let statxbuf_ty = this.tcx.mk_mut_ptr(statx_ty);
827 let statxbuf_layout = this.layout_of(statxbuf_ty)?;
828 let statxbuf_imm = ImmTy::from_scalar(statxbuf_scalar, statxbuf_layout);
829 this.ref_to_mplace(statxbuf_imm)?
832 let path = this.read_path_from_c_str(pathname_scalar)?.into_owned();
833 // `flags` should be a `c_int` but the `syscall` function provides an `isize`.
835 this.read_scalar(flags_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
836 err_unsup_format!("failed to convert pointer sized operand to integer: {}", e)
838 let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
839 // `dirfd` should be a `c_int` but the `syscall` function provides an `isize`.
841 this.read_scalar(dirfd_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
842 err_unsup_format!("failed to convert pointer sized operand to integer: {}", e)
845 // * interpreting `path` as an absolute directory,
846 // * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
847 // * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
849 // Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
850 // found this error, please open an issue reporting it.
852 path.is_absolute() ||
853 dirfd == this.eval_libc_i32("AT_FDCWD")? ||
854 (path.as_os_str().is_empty() && empty_path_flag)
857 "using statx is only supported with absolute paths, relative paths with the file \
858 descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
863 // the `_mask_op` paramter specifies the file information that the caller requested.
864 // However `statx` is allowed to return information that was not requested or to not
865 // return information that was requested. This `mask` represents the information we can
866 // actually provide for any target.
868 this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
870 // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
872 let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
874 // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
875 // represented by dirfd, whether it's a directory or otherwise.
876 let metadata = if path.as_os_str().is_empty() && empty_path_flag {
877 FileMetadata::from_fd(this, dirfd)?
879 FileMetadata::from_path(this, &path, follow_symlink)?
881 let metadata = match metadata {
882 Some(metadata) => metadata,
883 None => return Ok(-1),
886 // The `mode` field specifies the type of the file and the permissions over the file for
887 // the owner, its group and other users. Given that we can only provide the file type
888 // without using platform specific methods, we only set the bits corresponding to the file
889 // type. This should be an `__u16` but `libc` provides its values as `u32`.
890 let mode: u16 = metadata
894 .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
896 // We need to set the corresponding bits of `mask` if the access, creation and modification
897 // times were available. Otherwise we let them be zero.
898 let (access_sec, access_nsec) = metadata.accessed.map(|tup| {
899 mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
900 InterpResult::Ok(tup)
901 }).unwrap_or(Ok((0, 0)))?;
903 let (created_sec, created_nsec) = metadata.created.map(|tup| {
904 mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
905 InterpResult::Ok(tup)
906 }).unwrap_or(Ok((0, 0)))?;
908 let (modified_sec, modified_nsec) = metadata.modified.map(|tup| {
909 mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
910 InterpResult::Ok(tup)
911 }).unwrap_or(Ok((0, 0)))?;
913 let __u32_layout = this.libc_ty_layout("__u32")?;
914 let __u64_layout = this.libc_ty_layout("__u64")?;
915 let __u16_layout = this.libc_ty_layout("__u16")?;
917 // Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
918 // zero for the unavailable fields.
920 immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
921 immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
922 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
923 immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
924 immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
925 immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
926 immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
927 immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
928 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
929 immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
930 immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
931 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
932 immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
933 immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
934 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
935 immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
936 immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
937 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
938 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
939 immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
940 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
941 immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
942 immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
943 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
944 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
945 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
946 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
947 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
950 this.write_packed_immediates(statxbuf_place, &imms)?;
957 oldpath_op: OpTy<'tcx, Tag>,
958 newpath_op: OpTy<'tcx, Tag>,
959 ) -> InterpResult<'tcx, i32> {
960 let this = self.eval_context_mut();
962 this.check_no_isolation("`rename`")?;
964 let oldpath_scalar = this.read_scalar(oldpath_op)?.check_init()?;
965 let newpath_scalar = this.read_scalar(newpath_op)?.check_init()?;
967 if this.is_null(oldpath_scalar)? || this.is_null(newpath_scalar)? {
968 let efault = this.eval_libc("EFAULT")?;
969 this.set_last_error(efault)?;
973 let oldpath = this.read_path_from_c_str(oldpath_scalar)?;
974 let newpath = this.read_path_from_c_str(newpath_scalar)?;
976 let result = rename(oldpath, newpath).map(|_| 0);
978 this.try_unwrap_io_result(result)
983 path_op: OpTy<'tcx, Tag>,
984 mode_op: OpTy<'tcx, Tag>,
985 ) -> InterpResult<'tcx, i32> {
986 let this = self.eval_context_mut();
988 this.check_no_isolation("`mkdir`")?;
990 #[cfg_attr(not(unix), allow(unused_variables))]
991 let mode = if this.tcx.sess.target.target.target_os == "macos" {
992 u32::from(this.read_scalar(mode_op)?.check_init()?.to_u16()?)
994 this.read_scalar(mode_op)?.to_u32()?
997 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
999 #[cfg_attr(not(unix), allow(unused_mut))]
1000 let mut builder = DirBuilder::new();
1002 // If the host supports it, forward on the mode of the directory
1003 // (i.e. permission bits and the sticky bit)
1006 use std::os::unix::fs::DirBuilderExt;
1007 builder.mode(mode.into());
1010 let result = builder.create(path).map(|_| 0i32);
1012 this.try_unwrap_io_result(result)
1017 path_op: OpTy<'tcx, Tag>,
1018 ) -> InterpResult<'tcx, i32> {
1019 let this = self.eval_context_mut();
1021 this.check_no_isolation("`rmdir`")?;
1023 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
1025 let result = remove_dir(path).map(|_| 0i32);
1027 this.try_unwrap_io_result(result)
1030 fn opendir(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
1031 let this = self.eval_context_mut();
1033 this.check_no_isolation("`opendir`")?;
1035 let name = this.read_path_from_c_str(this.read_scalar(name_op)?.check_init()?)?;
1037 let result = read_dir(name);
1041 let id = this.machine.dir_handler.insert_new(dir_iter);
1043 // The libc API for opendir says that this method returns a pointer to an opaque
1044 // structure, but we are returning an ID number. Thus, pass it as a scalar of
1046 Ok(Scalar::from_machine_usize(id, this))
1049 this.set_last_error_from_io_error(e)?;
1050 Ok(Scalar::null_ptr(this))
1055 fn linux_readdir64_r(
1057 dirp_op: OpTy<'tcx, Tag>,
1058 entry_op: OpTy<'tcx, Tag>,
1059 result_op: OpTy<'tcx, Tag>,
1060 ) -> InterpResult<'tcx, i32> {
1061 let this = self.eval_context_mut();
1063 this.assert_target_os("linux", "readdir64_r");
1064 this.check_no_isolation("`readdir64_r`")?;
1066 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1068 let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1069 err_unsup_format!("the DIR pointer passed to readdir64_r did not come from opendir")
1071 match dir_iter.next() {
1072 Some(Ok(dir_entry)) => {
1073 // Write into entry, write pointer to result, return 0 on success.
1074 // The name is written with write_os_str_to_c_str, while the rest of the
1075 // dirent64 struct is written using write_packed_immediates.
1078 // pub struct dirent64 {
1079 // pub d_ino: ino64_t,
1080 // pub d_off: off64_t,
1081 // pub d_reclen: c_ushort,
1082 // pub d_type: c_uchar,
1083 // pub d_name: [c_char; 256],
1086 let entry_place = this.deref_operand(entry_op)?;
1087 let name_place = this.mplace_field(entry_place, 4)?;
1089 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1090 let (name_fits, _) = this.write_os_str_to_c_str(
1093 name_place.layout.size.bytes(),
1096 throw_unsup_format!("a directory entry had a name too large to fit in libc::dirent64");
1099 let entry_place = this.deref_operand(entry_op)?;
1100 let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
1101 let off64_t_layout = this.libc_ty_layout("off64_t")?;
1102 let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
1103 let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
1105 // If the host is a Unix system, fill in the inode number with its real value.
1106 // If not, use 0 as a fallback value.
1108 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1112 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1115 immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
1116 immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
1117 immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1118 immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
1120 this.write_packed_immediates(entry_place, &imms)?;
1122 let result_place = this.deref_operand(result_op)?;
1123 this.write_scalar(this.read_scalar(entry_op)?, result_place.into())?;
1128 // end of stream: return 0, assign *result=NULL
1129 this.write_null(this.deref_operand(result_op)?.into())?;
1132 Some(Err(e)) => match e.raw_os_error() {
1133 // return positive error number on error
1134 Some(error) => Ok(error),
1136 throw_unsup_format!("the error {} couldn't be converted to a return value", e)
1144 dirp_op: OpTy<'tcx, Tag>,
1145 entry_op: OpTy<'tcx, Tag>,
1146 result_op: OpTy<'tcx, Tag>,
1147 ) -> InterpResult<'tcx, i32> {
1148 let this = self.eval_context_mut();
1150 this.assert_target_os("macos", "readdir_r");
1151 this.check_no_isolation("`readdir_r`")?;
1153 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1155 let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1156 err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
1158 match dir_iter.next() {
1159 Some(Ok(dir_entry)) => {
1160 // Write into entry, write pointer to result, return 0 on success.
1161 // The name is written with write_os_str_to_c_str, while the rest of the
1162 // dirent struct is written using write_packed_Immediates.
1165 // pub struct dirent {
1167 // pub d_seekoff: u64,
1168 // pub d_reclen: u16,
1169 // pub d_namlen: u16,
1171 // pub d_name: [c_char; 1024],
1174 let entry_place = this.deref_operand(entry_op)?;
1175 let name_place = this.mplace_field(entry_place, 5)?;
1177 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1178 let (name_fits, file_name_len) = this.write_os_str_to_c_str(
1181 name_place.layout.size.bytes(),
1184 throw_unsup_format!("a directory entry had a name too large to fit in libc::dirent");
1187 let entry_place = this.deref_operand(entry_op)?;
1188 let ino_t_layout = this.libc_ty_layout("ino_t")?;
1189 let off_t_layout = this.libc_ty_layout("off_t")?;
1190 let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
1191 let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
1193 // If the host is a Unix system, fill in the inode number with its real value.
1194 // If not, use 0 as a fallback value.
1196 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1200 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1203 immty_from_uint_checked(ino, ino_t_layout)?, // d_ino
1204 immty_from_uint_checked(0u128, off_t_layout)?, // d_seekoff
1205 immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1206 immty_from_uint_checked(file_name_len, c_ushort_layout)?, // d_namlen
1207 immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
1209 this.write_packed_immediates(entry_place, &imms)?;
1211 let result_place = this.deref_operand(result_op)?;
1212 this.write_scalar(this.read_scalar(entry_op)?, result_place.into())?;
1217 // end of stream: return 0, assign *result=NULL
1218 this.write_null(this.deref_operand(result_op)?.into())?;
1221 Some(Err(e)) => match e.raw_os_error() {
1222 // return positive error number on error
1223 Some(error) => Ok(error),
1225 throw_unsup_format!("the error {} couldn't be converted to a return value", e)
1231 fn closedir(&mut self, dirp_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1232 let this = self.eval_context_mut();
1234 this.check_no_isolation("`closedir`")?;
1236 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1238 if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
1242 this.handle_not_found()
1248 fd_op: OpTy<'tcx, Tag>,
1249 length_op: OpTy<'tcx, Tag>,
1250 ) -> InterpResult<'tcx, i32> {
1251 let this = self.eval_context_mut();
1253 this.check_no_isolation("`ftruncate64`")?;
1255 let fd = this.read_scalar(fd_op)?.to_i32()?;
1256 let length = this.read_scalar(length_op)?.to_i64()?;
1257 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
1258 // FIXME: Support ftruncate64 for all FDs
1259 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1261 if let Ok(length) = length.try_into() {
1262 let result = file.set_len(length);
1263 this.try_unwrap_io_result(result.map(|_| 0i32))
1265 let einval = this.eval_libc("EINVAL")?;
1266 this.set_last_error(einval)?;
1270 // The file is not writable
1271 let einval = this.eval_libc("EINVAL")?;
1272 this.set_last_error(einval)?;
1276 this.handle_not_found()
1280 fn fsync(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1281 // On macOS, `fsync` (unlike `fcntl(F_FULLFSYNC)`) does not wait for the
1282 // underlying disk to finish writing. In the interest of host compatibility,
1283 // we conservatively implement this with `sync_all`, which
1284 // *does* wait for the disk.
1286 let this = self.eval_context_mut();
1288 this.check_no_isolation("`fsync`")?;
1290 let fd = this.read_scalar(fd_op)?.to_i32()?;
1291 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1292 // FIXME: Support fsync for all FDs
1293 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1294 let io_result = maybe_sync_file(&file, *writable, File::sync_all);
1295 this.try_unwrap_io_result(io_result)
1297 this.handle_not_found()
1301 fn fdatasync(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1302 let this = self.eval_context_mut();
1304 this.check_no_isolation("`fdatasync`")?;
1306 let fd = this.read_scalar(fd_op)?.to_i32()?;
1307 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1308 // FIXME: Support fdatasync for all FDs
1309 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1310 let io_result = maybe_sync_file(&file, *writable, File::sync_data);
1311 this.try_unwrap_io_result(io_result)
1313 this.handle_not_found()
1319 fd_op: OpTy<'tcx, Tag>,
1320 offset_op: OpTy<'tcx, Tag>,
1321 nbytes_op: OpTy<'tcx, Tag>,
1322 flags_op: OpTy<'tcx, Tag>,
1323 ) -> InterpResult<'tcx, i32> {
1324 let this = self.eval_context_mut();
1326 this.check_no_isolation("`sync_file_range`")?;
1328 let fd = this.read_scalar(fd_op)?.to_i32()?;
1329 let offset = this.read_scalar(offset_op)?.to_i64()?;
1330 let nbytes = this.read_scalar(nbytes_op)?.to_i64()?;
1331 let flags = this.read_scalar(flags_op)?.to_i32()?;
1333 if offset < 0 || nbytes < 0 {
1334 let einval = this.eval_libc("EINVAL")?;
1335 this.set_last_error(einval)?;
1338 let allowed_flags = this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_BEFORE")?
1339 | this.eval_libc_i32("SYNC_FILE_RANGE_WRITE")?
1340 | this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_AFTER")?;
1341 if flags & allowed_flags != flags {
1342 let einval = this.eval_libc("EINVAL")?;
1343 this.set_last_error(einval)?;
1347 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1348 // FIXME: Support sync_data_range for all FDs
1349 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1350 let io_result = maybe_sync_file(&file, *writable, File::sync_data);
1351 this.try_unwrap_io_result(io_result)
1353 this.handle_not_found()
1358 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
1359 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
1361 fn extract_sec_and_nsec<'tcx>(
1362 time: std::io::Result<SystemTime>
1363 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
1364 time.ok().map(|time| {
1365 let duration = system_time_to_duration(&time)?;
1366 Ok((duration.as_secs(), duration.subsec_nanos()))
1370 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
1372 struct FileMetadata {
1375 created: Option<(u64, u32)>,
1376 accessed: Option<(u64, u32)>,
1377 modified: Option<(u64, u32)>,
1381 fn from_path<'tcx, 'mir>(
1382 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1384 follow_symlink: bool
1385 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1386 let metadata = if follow_symlink {
1387 std::fs::metadata(path)
1389 std::fs::symlink_metadata(path)
1392 FileMetadata::from_meta(ecx, metadata)
1395 fn from_fd<'tcx, 'mir>(
1396 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1398 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1399 let option = ecx.machine.file_handler.handles.get(&fd);
1400 let file = match option {
1401 Some(file_descriptor) => &file_descriptor.as_file_handle()?.file,
1402 None => return ecx.handle_not_found().map(|_: i32| None),
1404 let metadata = file.metadata();
1406 FileMetadata::from_meta(ecx, metadata)
1409 fn from_meta<'tcx, 'mir>(
1410 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1411 metadata: Result<std::fs::Metadata, std::io::Error>,
1412 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1413 let metadata = match metadata {
1414 Ok(metadata) => metadata,
1416 ecx.set_last_error_from_io_error(e)?;
1421 let file_type = metadata.file_type();
1423 let mode_name = if file_type.is_file() {
1425 } else if file_type.is_dir() {
1431 let mode = ecx.eval_libc(mode_name)?;
1433 let size = metadata.len();
1435 let created = extract_sec_and_nsec(metadata.created())?;
1436 let accessed = extract_sec_and_nsec(metadata.accessed())?;
1437 let modified = extract_sec_and_nsec(metadata.modified())?;
1439 // FIXME: Provide more fields using platform specific methods.
1440 Ok(Some(FileMetadata { mode, size, created, accessed, modified }))