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;
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_target::abi::{Align, LayoutOf, Size};
16 use stacked_borrows::Tag;
17 use helpers::{check_arg_count, immty_from_int_checked, immty_from_uint_checked};
18 use shims::time::system_time_to_duration;
26 trait FileDescriptor : std::fmt::Debug {
27 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle>;
29 fn read<'tcx>(&mut self, communicate_allowed: bool, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>>;
30 fn write<'tcx>(&mut self, communicate_allowed: bool, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>>;
31 fn seek<'tcx>(&mut self, communicate_allowed: bool, offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>>;
32 fn close<'tcx>(self: Box<Self>, _communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>>;
34 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>>;
37 impl FileDescriptor for FileHandle {
38 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
42 fn read<'tcx>(&mut self, communicate_allowed: bool, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
43 assert!(communicate_allowed, "isolation should have prevented even opening a file");
44 Ok(self.file.read(bytes))
47 fn write<'tcx>(&mut self, communicate_allowed: bool, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
48 assert!(communicate_allowed, "isolation should have prevented even opening a file");
49 Ok(self.file.write(bytes))
52 fn seek<'tcx>(&mut self, communicate_allowed: bool, offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
53 assert!(communicate_allowed, "isolation should have prevented even opening a file");
54 Ok(self.file.seek(offset))
57 fn close<'tcx>(self: Box<Self>, communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>> {
58 assert!(communicate_allowed, "isolation should have prevented even opening a file");
59 // We sync the file if it was opened in a mode different than read-only.
61 // `File::sync_all` does the checks that are done when closing a file. We do this to
62 // to handle possible errors correctly.
63 let result = self.file.sync_all().map(|_| 0i32);
64 // Now we actually close the file.
66 // And return the result.
69 // We drop the file, this closes it but ignores any errors
70 // produced when closing it. This is done because
71 // `File::sync_all` cannot be done over files like
72 // `/dev/urandom` which are read-only. Check
73 // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439
74 // for a deeper discussion.
80 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
81 let duplicated = self.file.try_clone()?;
82 Ok(Box::new(FileHandle { file: duplicated, writable: self.writable }))
86 impl FileDescriptor for io::Stdin {
87 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
88 throw_unsup_format!("stdin cannot be used as FileHandle");
91 fn read<'tcx>(&mut self, communicate_allowed: bool, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
92 if !communicate_allowed {
93 // We want isolation mode to be deterministic, so we have to disallow all reads, even stdin.
94 helpers::isolation_error("`read` from stdin")?;
96 Ok(Read::read(self, bytes))
99 fn write<'tcx>(&mut self, _communicate_allowed: bool, _bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
100 throw_unsup_format!("cannot write to stdin");
103 fn seek<'tcx>(&mut self, _communicate_allowed: bool, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
104 throw_unsup_format!("cannot seek on stdin");
107 fn close<'tcx>(self: Box<Self>, _communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>> {
108 throw_unsup_format!("stdin cannot be closed");
111 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
112 Ok(Box::new(io::stdin()))
116 impl FileDescriptor for io::Stdout {
117 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
118 throw_unsup_format!("stdout cannot be used as FileHandle");
121 fn read<'tcx>(&mut self, _communicate_allowed: bool, _bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
122 throw_unsup_format!("cannot read from stdout");
125 fn write<'tcx>(&mut self, _communicate_allowed: bool, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
126 // We allow writing to stderr even with isolation enabled.
127 let result = Write::write(self, bytes);
128 // Stdout is buffered, flush to make sure it appears on the
129 // screen. This is the write() syscall of the interpreted
130 // program, we want it to correspond to a write() syscall on
131 // the host -- there is no good in adding extra buffering
133 io::stdout().flush().unwrap();
138 fn seek<'tcx>(&mut self, _communicate_allowed: bool, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
139 throw_unsup_format!("cannot seek on stdout");
142 fn close<'tcx>(self: Box<Self>, _communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>> {
143 throw_unsup_format!("stdout cannot be closed");
146 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
147 Ok(Box::new(io::stdout()))
151 impl FileDescriptor for io::Stderr {
152 fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
153 throw_unsup_format!("stderr cannot be used as FileHandle");
156 fn read<'tcx>(&mut self, _communicate_allowed: bool, _bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
157 throw_unsup_format!("cannot read from stderr");
160 fn write<'tcx>(&mut self, _communicate_allowed: bool, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
161 // We allow writing to stderr even with isolation enabled.
162 // No need to flush, stderr is not buffered.
163 Ok(Write::write(self, bytes))
166 fn seek<'tcx>(&mut self, _communicate_allowed: bool, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
167 throw_unsup_format!("cannot seek on stderr");
170 fn close<'tcx>(self: Box<Self>, _communicate_allowed: bool) -> InterpResult<'tcx, io::Result<i32>> {
171 throw_unsup_format!("stderr cannot be closed");
174 fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
175 Ok(Box::new(io::stderr()))
180 pub struct FileHandler {
181 handles: BTreeMap<i32, Box<dyn FileDescriptor>>,
184 impl<'tcx> Default for FileHandler {
185 fn default() -> Self {
186 let mut handles: BTreeMap<_, Box<dyn FileDescriptor>> = BTreeMap::new();
187 handles.insert(0i32, Box::new(io::stdin()));
188 handles.insert(1i32, Box::new(io::stdout()));
189 handles.insert(2i32, Box::new(io::stderr()));
196 impl<'tcx> FileHandler {
197 fn insert_fd(&mut self, file_handle: Box<dyn FileDescriptor>) -> i32 {
198 self.insert_fd_with_min_fd(file_handle, 0)
201 fn insert_fd_with_min_fd(&mut self, file_handle: Box<dyn FileDescriptor>, min_fd: i32) -> i32 {
202 // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
203 // between used FDs, the find_map combinator will return it. If the first such unused FD
204 // is after all other used FDs, the find_map combinator will return None, and we will use
205 // the FD following the greatest FD thus far.
206 let candidate_new_fd = self
210 .find_map(|((fd, _fh), counter)| {
212 // There was a gap in the fds stored, return the first unused one
213 // (note that this relies on BTreeMap iterating in key order)
216 // This fd is used, keep going
220 let new_fd = candidate_new_fd.unwrap_or_else(|| {
221 // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
222 // maximum fd in the map
223 self.handles.last_key_value().map(|(fd, _)| fd.checked_add(1).unwrap()).unwrap_or(min_fd)
226 self.handles.insert(new_fd, file_handle).unwrap_none();
231 impl<'mir, 'tcx: 'mir> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
232 trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
233 /// Emulate `stat` or `lstat` on `macos`. This function is not intended to be
234 /// called directly from `emulate_foreign_item_by_name`, so it does not check if isolation is
235 /// disabled or if the target OS is the correct one. Please use `macos_stat` or
236 /// `macos_lstat` instead.
237 fn macos_stat_or_lstat(
239 follow_symlink: bool,
240 path_op: OpTy<'tcx, Tag>,
241 buf_op: OpTy<'tcx, Tag>,
242 ) -> InterpResult<'tcx, i32> {
243 let this = self.eval_context_mut();
245 let path_scalar = this.read_scalar(path_op)?.check_init()?;
246 let path = this.read_path_from_c_str(path_scalar)?.into_owned();
248 let metadata = match FileMetadata::from_path(this, &path, follow_symlink)? {
249 Some(metadata) => metadata,
250 None => return Ok(-1),
252 this.macos_stat_write_buf(metadata, buf_op)
255 fn macos_stat_write_buf(
257 metadata: FileMetadata,
258 buf_op: OpTy<'tcx, Tag>,
259 ) -> InterpResult<'tcx, i32> {
260 let this = self.eval_context_mut();
262 let mode: u16 = metadata.mode.to_u16()?;
264 let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
265 let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
266 let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
268 let dev_t_layout = this.libc_ty_layout("dev_t")?;
269 let mode_t_layout = this.libc_ty_layout("mode_t")?;
270 let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
271 let ino_t_layout = this.libc_ty_layout("ino_t")?;
272 let uid_t_layout = this.libc_ty_layout("uid_t")?;
273 let gid_t_layout = this.libc_ty_layout("gid_t")?;
274 let time_t_layout = this.libc_ty_layout("time_t")?;
275 let long_layout = this.libc_ty_layout("c_long")?;
276 let off_t_layout = this.libc_ty_layout("off_t")?;
277 let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
278 let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
279 let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
282 immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
283 immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
284 immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
285 immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
286 immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
287 immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
288 immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
289 immty_from_uint_checked(0u128, uint32_t_layout)?, // padding
290 immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
291 immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
292 immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
293 immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
294 immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
295 immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
296 immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
297 immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
298 immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
299 immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
300 immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
301 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
302 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
305 let buf = this.deref_operand(buf_op)?;
306 this.write_packed_immediates(buf, &imms)?;
311 /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
312 /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
313 /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
314 /// types (like `read`, that returns an `i64`).
315 fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
316 let this = self.eval_context_mut();
317 let ebadf = this.eval_libc("EBADF")?;
318 this.set_last_error(ebadf)?;
322 fn file_type_to_d_type(&mut self, file_type: std::io::Result<FileType>) -> InterpResult<'tcx, i32> {
323 let this = self.eval_context_mut();
326 if file_type.is_dir() {
327 Ok(this.eval_libc("DT_DIR")?.to_u8()?.into())
328 } else if file_type.is_file() {
329 Ok(this.eval_libc("DT_REG")?.to_u8()?.into())
330 } else if file_type.is_symlink() {
331 Ok(this.eval_libc("DT_LNK")?.to_u8()?.into())
333 // Certain file types are only supported when the host is a Unix system.
334 // (i.e. devices and sockets) If it is, check those cases, if not, fall back to
335 // DT_UNKNOWN sooner.
339 use std::os::unix::fs::FileTypeExt;
340 if file_type.is_block_device() {
341 Ok(this.eval_libc("DT_BLK")?.to_u8()?.into())
342 } else if file_type.is_char_device() {
343 Ok(this.eval_libc("DT_CHR")?.to_u8()?.into())
344 } else if file_type.is_fifo() {
345 Ok(this.eval_libc("DT_FIFO")?.to_u8()?.into())
346 } else if file_type.is_socket() {
347 Ok(this.eval_libc("DT_SOCK")?.to_u8()?.into())
349 Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
353 Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
356 Err(e) => return match e.raw_os_error() {
357 Some(error) => Ok(error),
358 None => throw_unsup_format!("the error {} couldn't be converted to a return value", e),
365 pub struct DirHandler {
366 /// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
369 /// When opendir is called, a directory iterator is created on the host for the target
370 /// directory, and an entry is stored in this hash map, indexed by an ID which represents
371 /// the directory stream. When readdir is called, the directory stream ID is used to look up
372 /// the corresponding ReadDir iterator from this map, and information from the next
373 /// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
375 streams: FxHashMap<u64, ReadDir>,
376 /// ID number to be used by the next call to opendir
381 fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
382 let id = self.next_id;
384 self.streams.insert(id, read_dir).unwrap_none();
389 impl Default for DirHandler {
390 fn default() -> DirHandler {
392 streams: FxHashMap::default(),
393 // Skip 0 as an ID, because it looks like a null pointer to libc
399 fn maybe_sync_file(file: &File, writable: bool, operation: fn(&File) -> std::io::Result<()>) -> std::io::Result<i32> {
400 if !writable && cfg!(windows) {
401 // sync_all() and sync_data() will return an error on Windows hosts if the file is not opened
402 // for writing. (FlushFileBuffers requires that the file handle have the
403 // GENERIC_WRITE right)
406 let result = operation(file);
411 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
412 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
415 path_op: OpTy<'tcx, Tag>,
416 flag_op: OpTy<'tcx, Tag>,
417 mode_op: OpTy<'tcx, Tag>,
418 ) -> InterpResult<'tcx, i32> {
419 let this = self.eval_context_mut();
421 this.check_no_isolation("`open`")?;
423 let flag = this.read_scalar(flag_op)?.to_i32()?;
425 // Get the mode. On macOS, the argument type `mode_t` is actually `u16`, but
426 // C integer promotion rules mean that on the ABI level, it gets passed as `u32`
427 // (see https://github.com/rust-lang/rust/issues/71915).
428 let mode = this.read_scalar(mode_op)?.to_u32()?;
430 throw_unsup_format!("non-default mode 0o{:o} is not supported", mode);
433 let mut options = OpenOptions::new();
435 let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
436 let o_wronly = this.eval_libc_i32("O_WRONLY")?;
437 let o_rdwr = this.eval_libc_i32("O_RDWR")?;
438 // The first two bits of the flag correspond to the access mode in linux, macOS and
439 // windows. We need to check that in fact the access mode flags for the current target
440 // only use these two bits, otherwise we are in an unsupported target and should error.
441 if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
442 throw_unsup_format!("access mode flags on this target are unsupported");
444 let mut writable = true;
446 // Now we check the access mode
447 let access_mode = flag & 0b11;
449 if access_mode == o_rdonly {
452 } else if access_mode == o_wronly {
454 } else if access_mode == o_rdwr {
455 options.read(true).write(true);
457 throw_unsup_format!("unsupported access mode {:#x}", access_mode);
459 // We need to check that there aren't unsupported options in `flag`. For this we try to
460 // reproduce the content of `flag` in the `mirror` variable using only the supported
462 let mut mirror = access_mode;
464 let o_append = this.eval_libc_i32("O_APPEND")?;
465 if flag & o_append != 0 {
466 options.append(true);
469 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
470 if flag & o_trunc != 0 {
471 options.truncate(true);
474 let o_creat = this.eval_libc_i32("O_CREAT")?;
475 if flag & o_creat != 0 {
478 let o_excl = this.eval_libc_i32("O_EXCL")?;
479 if flag & o_excl != 0 {
481 options.create_new(true);
483 options.create(true);
486 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
487 if flag & o_cloexec != 0 {
488 // We do not need to do anything for this flag because `std` already sets it.
489 // (Technically we do not support *not* setting this flag, but we ignore that.)
492 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
493 // then we throw an error.
495 throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
498 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
500 let fd = options.open(&path).map(|file| {
501 let fh = &mut this.machine.file_handler;
502 fh.insert_fd(Box::new(FileHandle { file, writable }))
505 this.try_unwrap_io_result(fd)
510 args: &[OpTy<'tcx, Tag>],
511 ) -> InterpResult<'tcx, i32> {
512 let this = self.eval_context_mut();
514 this.check_no_isolation("`fcntl`")?;
517 throw_ub_format!("incorrect number of arguments for fcntl: got {}, expected at least 2", args.len());
519 let fd = this.read_scalar(args[0])?.to_i32()?;
520 let cmd = this.read_scalar(args[1])?.to_i32()?;
521 // We only support getting the flags for a descriptor.
522 if cmd == this.eval_libc_i32("F_GETFD")? {
523 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
524 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
525 // always sets this flag when opening a file. However we still need to check that the
526 // file itself is open.
527 let &[_, _] = check_arg_count(args)?;
528 if this.machine.file_handler.handles.contains_key(&fd) {
529 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
531 this.handle_not_found()
533 } else if cmd == this.eval_libc_i32("F_DUPFD")?
534 || cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
536 // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
537 // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
538 // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
539 // thus they can share the same implementation here.
540 let &[_, _, start] = check_arg_count(args)?;
541 let start = this.read_scalar(start)?.to_i32()?;
543 let fh = &mut this.machine.file_handler;
545 match fh.handles.get_mut(&fd) {
546 Some(file_descriptor) => {
547 let dup_result = file_descriptor.dup();
549 Ok(dup_fd) => Ok(fh.insert_fd_with_min_fd(dup_fd, start)),
551 this.set_last_error_from_io_error(e)?;
556 None => return this.handle_not_found(),
558 } else if this.tcx.sess.target.target_os == "macos"
559 && cmd == this.eval_libc_i32("F_FULLFSYNC")?
561 let &[_, _] = check_arg_count(args)?;
562 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
563 // FIXME: Support fullfsync for all FDs
564 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
565 let io_result = maybe_sync_file(&file, *writable, File::sync_all);
566 this.try_unwrap_io_result(io_result)
568 this.handle_not_found()
571 throw_unsup_format!("the {:#x} command is not supported for `fcntl`)", cmd);
575 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
576 let this = self.eval_context_mut();
578 let fd = this.read_scalar(fd_op)?.to_i32()?;
580 if let Some(file_descriptor) = this.machine.file_handler.handles.remove(&fd) {
581 let result = file_descriptor.close(this.machine.communicate)?;
582 this.try_unwrap_io_result(result)
584 this.handle_not_found()
593 ) -> InterpResult<'tcx, i64> {
594 let this = self.eval_context_mut();
596 // Isolation check is done via `FileDescriptor` trait.
598 trace!("Reading from FD {}, size {}", fd, count);
600 // Check that the *entire* buffer is actually valid memory.
601 this.memory.check_ptr_access(
603 Size::from_bytes(count),
604 Align::from_bytes(1).unwrap(),
607 // We cap the number of read bytes to the largest value that we are able to fit in both the
608 // host's and target's `isize`. This saves us from having to handle overflows later.
609 let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
611 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
612 trace!("read: FD mapped to {:?}", file_descriptor);
613 // We want to read at most `count` bytes. We are sure that `count` is not negative
614 // because it was a target's `usize`. Also we are sure that its smaller than
615 // `usize::MAX` because it is a host's `isize`.
616 let mut bytes = vec![0; count as usize];
617 // `File::read` never returns a value larger than `count`,
618 // so this cannot fail.
619 let result = file_descriptor
620 .read(this.machine.communicate, &mut bytes)?
621 .map(|c| i64::try_from(c).unwrap());
625 // If reading to `bytes` did not fail, we write those bytes to the buffer.
626 this.memory.write_bytes(buf, bytes)?;
630 this.set_last_error_from_io_error(e)?;
635 trace!("read: FD not found");
636 this.handle_not_found()
645 ) -> InterpResult<'tcx, i64> {
646 let this = self.eval_context_mut();
648 // Isolation check is done via `FileDescriptor` trait.
650 // Check that the *entire* buffer is actually valid memory.
651 this.memory.check_ptr_access(
653 Size::from_bytes(count),
654 Align::from_bytes(1).unwrap(),
657 // We cap the number of written bytes to the largest value that we are able to fit in both the
658 // host's and target's `isize`. This saves us from having to handle overflows later.
659 let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
661 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
662 let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
663 let result = file_descriptor
664 .write(this.machine.communicate, &bytes)?
665 .map(|c| i64::try_from(c).unwrap());
666 this.try_unwrap_io_result(result)
668 this.handle_not_found()
674 fd_op: OpTy<'tcx, Tag>,
675 offset_op: OpTy<'tcx, Tag>,
676 whence_op: OpTy<'tcx, Tag>,
677 ) -> InterpResult<'tcx, i64> {
678 let this = self.eval_context_mut();
680 // Isolation check is done via `FileDescriptor` trait.
682 let fd = this.read_scalar(fd_op)?.to_i32()?;
683 let offset = this.read_scalar(offset_op)?.to_i64()?;
684 let whence = this.read_scalar(whence_op)?.to_i32()?;
686 let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
687 SeekFrom::Start(u64::try_from(offset).unwrap())
688 } else if whence == this.eval_libc_i32("SEEK_CUR")? {
689 SeekFrom::Current(offset)
690 } else if whence == this.eval_libc_i32("SEEK_END")? {
691 SeekFrom::End(offset)
693 let einval = this.eval_libc("EINVAL")?;
694 this.set_last_error(einval)?;
698 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
699 let result = file_descriptor
700 .seek(this.machine.communicate, seek_from)?
701 .map(|offset| i64::try_from(offset).unwrap());
702 this.try_unwrap_io_result(result)
704 this.handle_not_found()
708 fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
709 let this = self.eval_context_mut();
711 this.check_no_isolation("`unlink`")?;
713 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
715 let result = remove_file(path).map(|_| 0);
716 this.try_unwrap_io_result(result)
721 target_op: OpTy<'tcx, Tag>,
722 linkpath_op: OpTy<'tcx, Tag>
723 ) -> InterpResult<'tcx, i32> {
725 fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
726 std::os::unix::fs::symlink(src, dst)
730 fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
731 use std::os::windows::fs;
733 fs::symlink_dir(src, dst)
735 fs::symlink_file(src, dst)
739 let this = self.eval_context_mut();
741 this.check_no_isolation("`symlink`")?;
743 let target = this.read_path_from_c_str(this.read_scalar(target_op)?.check_init()?)?;
744 let linkpath = this.read_path_from_c_str(this.read_scalar(linkpath_op)?.check_init()?)?;
746 let result = create_link(&target, &linkpath).map(|_| 0);
747 this.try_unwrap_io_result(result)
752 path_op: OpTy<'tcx, Tag>,
753 buf_op: OpTy<'tcx, Tag>,
754 ) -> InterpResult<'tcx, i32> {
755 let this = self.eval_context_mut();
756 this.assert_target_os("macos", "stat");
757 this.check_no_isolation("`stat`")?;
758 // `stat` always follows symlinks.
759 this.macos_stat_or_lstat(true, path_op, buf_op)
762 // `lstat` is used to get symlink metadata.
765 path_op: OpTy<'tcx, Tag>,
766 buf_op: OpTy<'tcx, Tag>,
767 ) -> InterpResult<'tcx, i32> {
768 let this = self.eval_context_mut();
769 this.assert_target_os("macos", "lstat");
770 this.check_no_isolation("`lstat`")?;
771 this.macos_stat_or_lstat(false, path_op, buf_op)
776 fd_op: OpTy<'tcx, Tag>,
777 buf_op: OpTy<'tcx, Tag>,
778 ) -> InterpResult<'tcx, i32> {
779 let this = self.eval_context_mut();
781 this.assert_target_os("macos", "fstat");
782 this.check_no_isolation("`fstat`")?;
784 let fd = this.read_scalar(fd_op)?.to_i32()?;
786 let metadata = match FileMetadata::from_fd(this, fd)? {
787 Some(metadata) => metadata,
788 None => return Ok(-1),
790 this.macos_stat_write_buf(metadata, buf_op)
795 dirfd_op: OpTy<'tcx, Tag>, // Should be an `int`
796 pathname_op: OpTy<'tcx, Tag>, // Should be a `const char *`
797 flags_op: OpTy<'tcx, Tag>, // Should be an `int`
798 _mask_op: OpTy<'tcx, Tag>, // Should be an `unsigned int`
799 statxbuf_op: OpTy<'tcx, Tag>, // Should be a `struct statx *`
800 ) -> InterpResult<'tcx, i32> {
801 let this = self.eval_context_mut();
803 this.assert_target_os("linux", "statx");
804 this.check_no_isolation("`statx`")?;
806 let statxbuf_scalar = this.read_scalar(statxbuf_op)?.check_init()?;
807 let pathname_scalar = this.read_scalar(pathname_op)?.check_init()?;
809 // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
810 if this.is_null(statxbuf_scalar)? || this.is_null(pathname_scalar)? {
811 let efault = this.eval_libc("EFAULT")?;
812 this.set_last_error(efault)?;
816 // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
817 // proper `MemPlace` and then write the results of this function to it. However, the
818 // `syscall` function is untyped. This means that all the `statx` parameters are provided
819 // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
820 // `statxbuf_op` by using the `libc::statx` struct type.
821 let statxbuf_place = {
822 // FIXME: This long path is required because `libc::statx` is an struct and also a
823 // function and `resolve_path` is returning the latter.
825 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])
826 .ty(*this.tcx, ty::ParamEnv::reveal_all());
827 let statxbuf_ty = this.tcx.mk_mut_ptr(statx_ty);
828 let statxbuf_layout = this.layout_of(statxbuf_ty)?;
829 let statxbuf_imm = ImmTy::from_scalar(statxbuf_scalar, statxbuf_layout);
830 this.ref_to_mplace(statxbuf_imm)?
833 let path = this.read_path_from_c_str(pathname_scalar)?.into_owned();
834 // `flags` should be a `c_int` but the `syscall` function provides an `isize`.
836 this.read_scalar(flags_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
837 err_unsup_format!("failed to convert pointer sized operand to integer: {}", e)
839 let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
840 // `dirfd` should be a `c_int` but the `syscall` function provides an `isize`.
842 this.read_scalar(dirfd_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
843 err_unsup_format!("failed to convert pointer sized operand to integer: {}", e)
846 // * interpreting `path` as an absolute directory,
847 // * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
848 // * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
850 // Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
851 // found this error, please open an issue reporting it.
853 path.is_absolute() ||
854 dirfd == this.eval_libc_i32("AT_FDCWD")? ||
855 (path.as_os_str().is_empty() && empty_path_flag)
858 "using statx is only supported with absolute paths, relative paths with the file \
859 descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
864 // the `_mask_op` paramter specifies the file information that the caller requested.
865 // However `statx` is allowed to return information that was not requested or to not
866 // return information that was requested. This `mask` represents the information we can
867 // actually provide for any target.
869 this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
871 // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
873 let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
875 // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
876 // represented by dirfd, whether it's a directory or otherwise.
877 let metadata = if path.as_os_str().is_empty() && empty_path_flag {
878 FileMetadata::from_fd(this, dirfd)?
880 FileMetadata::from_path(this, &path, follow_symlink)?
882 let metadata = match metadata {
883 Some(metadata) => metadata,
884 None => return Ok(-1),
887 // The `mode` field specifies the type of the file and the permissions over the file for
888 // the owner, its group and other users. Given that we can only provide the file type
889 // without using platform specific methods, we only set the bits corresponding to the file
890 // type. This should be an `__u16` but `libc` provides its values as `u32`.
891 let mode: u16 = metadata
895 .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
897 // We need to set the corresponding bits of `mask` if the access, creation and modification
898 // times were available. Otherwise we let them be zero.
899 let (access_sec, access_nsec) = metadata.accessed.map(|tup| {
900 mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
901 InterpResult::Ok(tup)
902 }).unwrap_or(Ok((0, 0)))?;
904 let (created_sec, created_nsec) = metadata.created.map(|tup| {
905 mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
906 InterpResult::Ok(tup)
907 }).unwrap_or(Ok((0, 0)))?;
909 let (modified_sec, modified_nsec) = metadata.modified.map(|tup| {
910 mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
911 InterpResult::Ok(tup)
912 }).unwrap_or(Ok((0, 0)))?;
914 let __u32_layout = this.libc_ty_layout("__u32")?;
915 let __u64_layout = this.libc_ty_layout("__u64")?;
916 let __u16_layout = this.libc_ty_layout("__u16")?;
918 // Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
919 // zero for the unavailable fields.
921 immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
922 immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
923 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
924 immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
925 immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
926 immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
927 immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
928 immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
929 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
930 immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
931 immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
932 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
933 immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
934 immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
935 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
936 immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
937 immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
938 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
939 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
940 immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
941 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
942 immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
943 immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
944 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
945 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
946 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
947 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
948 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
951 this.write_packed_immediates(statxbuf_place, &imms)?;
958 oldpath_op: OpTy<'tcx, Tag>,
959 newpath_op: OpTy<'tcx, Tag>,
960 ) -> InterpResult<'tcx, i32> {
961 let this = self.eval_context_mut();
963 this.check_no_isolation("`rename`")?;
965 let oldpath_scalar = this.read_scalar(oldpath_op)?.check_init()?;
966 let newpath_scalar = this.read_scalar(newpath_op)?.check_init()?;
968 if this.is_null(oldpath_scalar)? || this.is_null(newpath_scalar)? {
969 let efault = this.eval_libc("EFAULT")?;
970 this.set_last_error(efault)?;
974 let oldpath = this.read_path_from_c_str(oldpath_scalar)?;
975 let newpath = this.read_path_from_c_str(newpath_scalar)?;
977 let result = rename(oldpath, newpath).map(|_| 0);
979 this.try_unwrap_io_result(result)
984 path_op: OpTy<'tcx, Tag>,
985 mode_op: OpTy<'tcx, Tag>,
986 ) -> InterpResult<'tcx, i32> {
987 let this = self.eval_context_mut();
989 this.check_no_isolation("`mkdir`")?;
991 #[cfg_attr(not(unix), allow(unused_variables))]
992 let mode = if this.tcx.sess.target.target_os == "macos" {
993 u32::from(this.read_scalar(mode_op)?.check_init()?.to_u16()?)
995 this.read_scalar(mode_op)?.to_u32()?
998 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
1000 #[cfg_attr(not(unix), allow(unused_mut))]
1001 let mut builder = DirBuilder::new();
1003 // If the host supports it, forward on the mode of the directory
1004 // (i.e. permission bits and the sticky bit)
1007 use std::os::unix::fs::DirBuilderExt;
1008 builder.mode(mode.into());
1011 let result = builder.create(path).map(|_| 0i32);
1013 this.try_unwrap_io_result(result)
1018 path_op: OpTy<'tcx, Tag>,
1019 ) -> InterpResult<'tcx, i32> {
1020 let this = self.eval_context_mut();
1022 this.check_no_isolation("`rmdir`")?;
1024 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
1026 let result = remove_dir(path).map(|_| 0i32);
1028 this.try_unwrap_io_result(result)
1031 fn opendir(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
1032 let this = self.eval_context_mut();
1034 this.check_no_isolation("`opendir`")?;
1036 let name = this.read_path_from_c_str(this.read_scalar(name_op)?.check_init()?)?;
1038 let result = read_dir(name);
1042 let id = this.machine.dir_handler.insert_new(dir_iter);
1044 // The libc API for opendir says that this method returns a pointer to an opaque
1045 // structure, but we are returning an ID number. Thus, pass it as a scalar of
1047 Ok(Scalar::from_machine_usize(id, this))
1050 this.set_last_error_from_io_error(e)?;
1051 Ok(Scalar::null_ptr(this))
1056 fn linux_readdir64_r(
1058 dirp_op: OpTy<'tcx, Tag>,
1059 entry_op: OpTy<'tcx, Tag>,
1060 result_op: OpTy<'tcx, Tag>,
1061 ) -> InterpResult<'tcx, i32> {
1062 let this = self.eval_context_mut();
1064 this.assert_target_os("linux", "readdir64_r");
1065 this.check_no_isolation("`readdir64_r`")?;
1067 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1069 let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1070 err_unsup_format!("the DIR pointer passed to readdir64_r did not come from opendir")
1072 match dir_iter.next() {
1073 Some(Ok(dir_entry)) => {
1074 // Write into entry, write pointer to result, return 0 on success.
1075 // The name is written with write_os_str_to_c_str, while the rest of the
1076 // dirent64 struct is written using write_packed_immediates.
1079 // pub struct dirent64 {
1080 // pub d_ino: ino64_t,
1081 // pub d_off: off64_t,
1082 // pub d_reclen: c_ushort,
1083 // pub d_type: c_uchar,
1084 // pub d_name: [c_char; 256],
1087 let entry_place = this.deref_operand(entry_op)?;
1088 let name_place = this.mplace_field(entry_place, 4)?;
1090 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1091 let (name_fits, _) = this.write_os_str_to_c_str(
1094 name_place.layout.size.bytes(),
1097 throw_unsup_format!("a directory entry had a name too large to fit in libc::dirent64");
1100 let entry_place = this.deref_operand(entry_op)?;
1101 let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
1102 let off64_t_layout = this.libc_ty_layout("off64_t")?;
1103 let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
1104 let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
1106 // If the host is a Unix system, fill in the inode number with its real value.
1107 // If not, use 0 as a fallback value.
1109 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1113 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1116 immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
1117 immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
1118 immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1119 immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
1121 this.write_packed_immediates(entry_place, &imms)?;
1123 let result_place = this.deref_operand(result_op)?;
1124 this.write_scalar(this.read_scalar(entry_op)?, result_place.into())?;
1129 // end of stream: return 0, assign *result=NULL
1130 this.write_null(this.deref_operand(result_op)?.into())?;
1133 Some(Err(e)) => match e.raw_os_error() {
1134 // return positive error number on error
1135 Some(error) => Ok(error),
1137 throw_unsup_format!("the error {} couldn't be converted to a return value", e)
1145 dirp_op: OpTy<'tcx, Tag>,
1146 entry_op: OpTy<'tcx, Tag>,
1147 result_op: OpTy<'tcx, Tag>,
1148 ) -> InterpResult<'tcx, i32> {
1149 let this = self.eval_context_mut();
1151 this.assert_target_os("macos", "readdir_r");
1152 this.check_no_isolation("`readdir_r`")?;
1154 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1156 let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1157 err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
1159 match dir_iter.next() {
1160 Some(Ok(dir_entry)) => {
1161 // Write into entry, write pointer to result, return 0 on success.
1162 // The name is written with write_os_str_to_c_str, while the rest of the
1163 // dirent struct is written using write_packed_Immediates.
1166 // pub struct dirent {
1168 // pub d_seekoff: u64,
1169 // pub d_reclen: u16,
1170 // pub d_namlen: u16,
1172 // pub d_name: [c_char; 1024],
1175 let entry_place = this.deref_operand(entry_op)?;
1176 let name_place = this.mplace_field(entry_place, 5)?;
1178 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1179 let (name_fits, file_name_len) = this.write_os_str_to_c_str(
1182 name_place.layout.size.bytes(),
1185 throw_unsup_format!("a directory entry had a name too large to fit in libc::dirent");
1188 let entry_place = this.deref_operand(entry_op)?;
1189 let ino_t_layout = this.libc_ty_layout("ino_t")?;
1190 let off_t_layout = this.libc_ty_layout("off_t")?;
1191 let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
1192 let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
1194 // If the host is a Unix system, fill in the inode number with its real value.
1195 // If not, use 0 as a fallback value.
1197 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1201 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1204 immty_from_uint_checked(ino, ino_t_layout)?, // d_ino
1205 immty_from_uint_checked(0u128, off_t_layout)?, // d_seekoff
1206 immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1207 immty_from_uint_checked(file_name_len, c_ushort_layout)?, // d_namlen
1208 immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
1210 this.write_packed_immediates(entry_place, &imms)?;
1212 let result_place = this.deref_operand(result_op)?;
1213 this.write_scalar(this.read_scalar(entry_op)?, result_place.into())?;
1218 // end of stream: return 0, assign *result=NULL
1219 this.write_null(this.deref_operand(result_op)?.into())?;
1222 Some(Err(e)) => match e.raw_os_error() {
1223 // return positive error number on error
1224 Some(error) => Ok(error),
1226 throw_unsup_format!("the error {} couldn't be converted to a return value", e)
1232 fn closedir(&mut self, dirp_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1233 let this = self.eval_context_mut();
1235 this.check_no_isolation("`closedir`")?;
1237 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1239 if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
1243 this.handle_not_found()
1249 fd_op: OpTy<'tcx, Tag>,
1250 length_op: OpTy<'tcx, Tag>,
1251 ) -> InterpResult<'tcx, i32> {
1252 let this = self.eval_context_mut();
1254 this.check_no_isolation("`ftruncate64`")?;
1256 let fd = this.read_scalar(fd_op)?.to_i32()?;
1257 let length = this.read_scalar(length_op)?.to_i64()?;
1258 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
1259 // FIXME: Support ftruncate64 for all FDs
1260 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1262 if let Ok(length) = length.try_into() {
1263 let result = file.set_len(length);
1264 this.try_unwrap_io_result(result.map(|_| 0i32))
1266 let einval = this.eval_libc("EINVAL")?;
1267 this.set_last_error(einval)?;
1271 // The file is not writable
1272 let einval = this.eval_libc("EINVAL")?;
1273 this.set_last_error(einval)?;
1277 this.handle_not_found()
1281 fn fsync(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1282 // On macOS, `fsync` (unlike `fcntl(F_FULLFSYNC)`) does not wait for the
1283 // underlying disk to finish writing. In the interest of host compatibility,
1284 // we conservatively implement this with `sync_all`, which
1285 // *does* wait for the disk.
1287 let this = self.eval_context_mut();
1289 this.check_no_isolation("`fsync`")?;
1291 let fd = this.read_scalar(fd_op)?.to_i32()?;
1292 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1293 // FIXME: Support fsync for all FDs
1294 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1295 let io_result = maybe_sync_file(&file, *writable, File::sync_all);
1296 this.try_unwrap_io_result(io_result)
1298 this.handle_not_found()
1302 fn fdatasync(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1303 let this = self.eval_context_mut();
1305 this.check_no_isolation("`fdatasync`")?;
1307 let fd = this.read_scalar(fd_op)?.to_i32()?;
1308 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1309 // FIXME: Support fdatasync for all FDs
1310 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1311 let io_result = maybe_sync_file(&file, *writable, File::sync_data);
1312 this.try_unwrap_io_result(io_result)
1314 this.handle_not_found()
1320 fd_op: OpTy<'tcx, Tag>,
1321 offset_op: OpTy<'tcx, Tag>,
1322 nbytes_op: OpTy<'tcx, Tag>,
1323 flags_op: OpTy<'tcx, Tag>,
1324 ) -> InterpResult<'tcx, i32> {
1325 let this = self.eval_context_mut();
1327 this.check_no_isolation("`sync_file_range`")?;
1329 let fd = this.read_scalar(fd_op)?.to_i32()?;
1330 let offset = this.read_scalar(offset_op)?.to_i64()?;
1331 let nbytes = this.read_scalar(nbytes_op)?.to_i64()?;
1332 let flags = this.read_scalar(flags_op)?.to_i32()?;
1334 if offset < 0 || nbytes < 0 {
1335 let einval = this.eval_libc("EINVAL")?;
1336 this.set_last_error(einval)?;
1339 let allowed_flags = this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_BEFORE")?
1340 | this.eval_libc_i32("SYNC_FILE_RANGE_WRITE")?
1341 | this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_AFTER")?;
1342 if flags & allowed_flags != flags {
1343 let einval = this.eval_libc("EINVAL")?;
1344 this.set_last_error(einval)?;
1348 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1349 // FIXME: Support sync_data_range for all FDs
1350 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1351 let io_result = maybe_sync_file(&file, *writable, File::sync_data);
1352 this.try_unwrap_io_result(io_result)
1354 this.handle_not_found()
1360 pathname_op: OpTy<'tcx, Tag>,
1361 buf_op: OpTy<'tcx, Tag>,
1362 bufsize_op: OpTy<'tcx, Tag>
1363 ) -> InterpResult<'tcx, i64> {
1364 let this = self.eval_context_mut();
1366 this.check_no_isolation("readlink")?;
1368 let pathname = this.read_path_from_c_str(this.read_scalar(pathname_op)?.check_init()?)?;
1369 let buf = this.read_scalar(buf_op)?.check_init()?;
1370 let bufsize = this.read_scalar(bufsize_op)?.to_machine_usize(this)?;
1372 let result = std::fs::read_link(pathname);
1375 let resolved = this.convert_path_separator(Cow::Borrowed(resolved.as_ref()), crate::shims::os_str::PathConversion::HostToTarget);
1376 let mut path_bytes = crate::shims::os_str::os_str_to_bytes(resolved.as_ref())?;
1377 let bufsize: usize = bufsize.try_into().unwrap();
1378 if path_bytes.len() > bufsize {
1379 path_bytes = &path_bytes[..bufsize]
1381 // 'readlink' truncates the resolved path if
1382 // the provided buffer is not large enough.
1383 this.memory.write_bytes(buf, path_bytes.iter().copied())?;
1384 Ok(path_bytes.len().try_into().unwrap())
1387 this.set_last_error_from_io_error(e)?;
1394 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
1395 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
1397 fn extract_sec_and_nsec<'tcx>(
1398 time: std::io::Result<SystemTime>
1399 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
1400 time.ok().map(|time| {
1401 let duration = system_time_to_duration(&time)?;
1402 Ok((duration.as_secs(), duration.subsec_nanos()))
1406 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
1408 struct FileMetadata {
1411 created: Option<(u64, u32)>,
1412 accessed: Option<(u64, u32)>,
1413 modified: Option<(u64, u32)>,
1417 fn from_path<'tcx, 'mir>(
1418 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1420 follow_symlink: bool
1421 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1422 let metadata = if follow_symlink {
1423 std::fs::metadata(path)
1425 std::fs::symlink_metadata(path)
1428 FileMetadata::from_meta(ecx, metadata)
1431 fn from_fd<'tcx, 'mir>(
1432 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1434 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1435 let option = ecx.machine.file_handler.handles.get(&fd);
1436 let file = match option {
1437 Some(file_descriptor) => &file_descriptor.as_file_handle()?.file,
1438 None => return ecx.handle_not_found().map(|_: i32| None),
1440 let metadata = file.metadata();
1442 FileMetadata::from_meta(ecx, metadata)
1445 fn from_meta<'tcx, 'mir>(
1446 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1447 metadata: Result<std::fs::Metadata, std::io::Error>,
1448 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1449 let metadata = match metadata {
1450 Ok(metadata) => metadata,
1452 ecx.set_last_error_from_io_error(e)?;
1457 let file_type = metadata.file_type();
1459 let mode_name = if file_type.is_file() {
1461 } else if file_type.is_dir() {
1467 let mode = ecx.eval_libc(mode_name)?;
1469 let size = metadata.len();
1471 let created = extract_sec_and_nsec(metadata.created())?;
1472 let accessed = extract_sec_and_nsec(metadata.accessed())?;
1473 let modified = extract_sec_and_nsec(metadata.modified())?;
1475 // FIXME: Provide more fields using platform specific methods.
1476 Ok(Some(FileMetadata { mode, size, created, accessed, modified }))