1 use std::collections::BTreeMap;
2 use std::convert::{TryFrom, TryInto};
3 use std::fs::{remove_file, rename, File, OpenOptions};
4 use std::io::{Read, Seek, SeekFrom, Write};
5 use std::path::PathBuf;
6 use std::time::SystemTime;
8 use rustc::ty::layout::{Align, LayoutOf, Size};
10 use crate::stacked_borrows::Tag;
12 use helpers::immty_from_uint_checked;
13 use shims::time::system_time_to_duration;
16 pub struct FileHandle {
21 #[derive(Debug, Default)]
22 pub struct FileHandler {
23 handles: BTreeMap<i32, FileHandle>,
26 // fd numbers 0, 1, and 2 are reserved for stdin, stdout, and stderr
27 const MIN_NORMAL_FILE_FD: i32 = 3;
30 fn insert_fd(&mut self, file_handle: FileHandle) -> i32 {
31 self.insert_fd_with_min_fd(file_handle, 0)
34 fn insert_fd_with_min_fd(&mut self, file_handle: FileHandle, min_fd: i32) -> i32 {
35 let min_fd = std::cmp::max(min_fd, MIN_NORMAL_FILE_FD);
37 // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
38 // between used FDs, the find_map combinator will return it. If the first such unused FD
39 // is after all other used FDs, the find_map combinator will return None, and we will use
40 // the FD following the greatest FD thus far.
41 let candidate_new_fd = self
45 .find_map(|((fd, _fh), counter)| {
47 // There was a gap in the fds stored, return the first unused one
48 // (note that this relies on BTreeMap iterating in key order)
51 // This fd is used, keep going
55 let new_fd = candidate_new_fd.unwrap_or_else(|| {
56 // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
57 // maximum fd in the map
58 self.handles.last_entry().map(|entry| entry.key() + 1).unwrap_or(min_fd)
61 self.handles.insert(new_fd, file_handle).unwrap_none();
66 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
67 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
70 path_op: OpTy<'tcx, Tag>,
71 flag_op: OpTy<'tcx, Tag>,
72 ) -> InterpResult<'tcx, i32> {
73 let this = self.eval_context_mut();
75 this.check_no_isolation("open")?;
77 let flag = this.read_scalar(flag_op)?.to_i32()?;
79 let mut options = OpenOptions::new();
81 let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
82 let o_wronly = this.eval_libc_i32("O_WRONLY")?;
83 let o_rdwr = this.eval_libc_i32("O_RDWR")?;
84 // The first two bits of the flag correspond to the access mode in linux, macOS and
85 // windows. We need to check that in fact the access mode flags for the current platform
86 // only use these two bits, otherwise we are in an unsupported platform and should error.
87 if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
88 throw_unsup_format!("Access mode flags on this platform are unsupported");
90 let mut writable = true;
92 // Now we check the access mode
93 let access_mode = flag & 0b11;
95 if access_mode == o_rdonly {
98 } else if access_mode == o_wronly {
100 } else if access_mode == o_rdwr {
101 options.read(true).write(true);
103 throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
105 // We need to check that there aren't unsupported options in `flag`. For this we try to
106 // reproduce the content of `flag` in the `mirror` variable using only the supported
108 let mut mirror = access_mode;
110 let o_append = this.eval_libc_i32("O_APPEND")?;
111 if flag & o_append != 0 {
112 options.append(true);
115 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
116 if flag & o_trunc != 0 {
117 options.truncate(true);
120 let o_creat = this.eval_libc_i32("O_CREAT")?;
121 if flag & o_creat != 0 {
122 options.create(true);
125 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
126 if flag & o_cloexec != 0 {
127 // We do not need to do anything for this flag because `std` already sets it.
128 // (Technically we do not support *not* setting this flag, but we ignore that.)
131 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
132 // then we throw an error.
134 throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
137 let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
139 let fd = options.open(&path).map(|file| {
140 let fh = &mut this.machine.file_handler;
141 fh.insert_fd(FileHandle { file, writable })
144 this.try_unwrap_io_result(fd)
149 fd_op: OpTy<'tcx, Tag>,
150 cmd_op: OpTy<'tcx, Tag>,
151 start_op: Option<OpTy<'tcx, Tag>>,
152 ) -> InterpResult<'tcx, i32> {
153 let this = self.eval_context_mut();
155 this.check_no_isolation("fcntl")?;
157 let fd = this.read_scalar(fd_op)?.to_i32()?;
158 let cmd = this.read_scalar(cmd_op)?.to_i32()?;
159 // We only support getting the flags for a descriptor.
160 if cmd == this.eval_libc_i32("F_GETFD")? {
161 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
162 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
163 // always sets this flag when opening a file. However we still need to check that the
164 // file itself is open.
165 if this.machine.file_handler.handles.contains_key(&fd) {
166 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
168 this.handle_not_found()
170 } else if cmd == this.eval_libc_i32("F_DUPFD")?
171 || cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
173 // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
174 // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
175 // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
176 // thus they can share the same implementation here.
177 if fd < MIN_NORMAL_FILE_FD {
178 throw_unsup_format!("Duplicating file descriptors for stdin, stdout, or stderr is not supported")
180 let start_op = start_op.ok_or_else(|| {
182 "fcntl with command F_DUPFD or F_DUPFD_CLOEXEC requires a third argument"
185 let start = this.read_scalar(start_op)?.to_i32()?;
186 let fh = &mut this.machine.file_handler;
187 let (file_result, writable) = match fh.handles.get(&fd) {
188 Some(FileHandle { file, writable }) => (file.try_clone(), *writable),
189 None => return this.handle_not_found(),
191 let fd_result = file_result.map(|duplicated| {
192 fh.insert_fd_with_min_fd(FileHandle { file: duplicated, writable }, start)
194 this.try_unwrap_io_result(fd_result)
196 throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
200 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
201 let this = self.eval_context_mut();
203 this.check_no_isolation("close")?;
205 let fd = this.read_scalar(fd_op)?.to_i32()?;
207 if let Some(FileHandle { file, writable }) = this.machine.file_handler.handles.remove(&fd) {
208 // We sync the file if it was opened in a mode different than read-only.
210 // `File::sync_all` does the checks that are done when closing a file. We do this to
211 // to handle possible errors correctly.
212 let result = this.try_unwrap_io_result(file.sync_all().map(|_| 0i32));
213 // Now we actually close the file.
215 // And return the result.
218 // We drop the file, this closes it but ignores any errors produced when closing
219 // it. This is done because `File::sync_all` cannot be done over files like
220 // `/dev/urandom` which are read-only. Check
221 // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439 for a deeper
227 this.handle_not_found()
233 fd_op: OpTy<'tcx, Tag>,
234 buf_op: OpTy<'tcx, Tag>,
235 count_op: OpTy<'tcx, Tag>,
236 ) -> InterpResult<'tcx, i64> {
237 let this = self.eval_context_mut();
239 this.check_no_isolation("read")?;
241 let fd = this.read_scalar(fd_op)?.to_i32()?;
242 let buf = this.read_scalar(buf_op)?.not_undef()?;
243 let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
245 // Check that the *entire* buffer is actually valid memory.
246 this.memory.check_ptr_access(
248 Size::from_bytes(count),
249 Align::from_bytes(1).unwrap(),
252 // We cap the number of read bytes to the largest value that we are able to fit in both the
253 // host's and target's `isize`. This saves us from having to handle overflows later.
254 let count = count.min(this.isize_max() as u64).min(isize::max_value() as u64);
256 if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
257 // This can never fail because `count` was capped to be smaller than
258 // `isize::max_value()`.
259 let count = isize::try_from(count).unwrap();
260 // We want to read at most `count` bytes. We are sure that `count` is not negative
261 // because it was a target's `usize`. Also we are sure that its smaller than
262 // `usize::max_value()` because it is a host's `isize`.
263 let mut bytes = vec![0; count as usize];
266 // `File::read` never returns a value larger than `count`, so this cannot fail.
267 .map(|c| i64::try_from(c).unwrap());
271 // If reading to `bytes` did not fail, we write those bytes to the buffer.
272 this.memory.write_bytes(buf, bytes)?;
276 this.set_last_error_from_io_error(e)?;
281 this.handle_not_found()
287 fd_op: OpTy<'tcx, Tag>,
288 buf_op: OpTy<'tcx, Tag>,
289 count_op: OpTy<'tcx, Tag>,
290 ) -> InterpResult<'tcx, i64> {
291 let this = self.eval_context_mut();
293 this.check_no_isolation("write")?;
295 let fd = this.read_scalar(fd_op)?.to_i32()?;
296 let buf = this.read_scalar(buf_op)?.not_undef()?;
297 let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
299 // Check that the *entire* buffer is actually valid memory.
300 this.memory.check_ptr_access(
302 Size::from_bytes(count),
303 Align::from_bytes(1).unwrap(),
306 // We cap the number of written bytes to the largest value that we are able to fit in both the
307 // host's and target's `isize`. This saves us from having to handle overflows later.
308 let count = count.min(this.isize_max() as u64).min(isize::max_value() as u64);
310 if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
311 let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
312 let result = file.write(&bytes).map(|c| i64::try_from(c).unwrap());
313 this.try_unwrap_io_result(result)
315 this.handle_not_found()
321 fd_op: OpTy<'tcx, Tag>,
322 offset_op: OpTy<'tcx, Tag>,
323 whence_op: OpTy<'tcx, Tag>,
324 ) -> InterpResult<'tcx, i64> {
325 let this = self.eval_context_mut();
327 this.check_no_isolation("lseek64")?;
329 let fd = this.read_scalar(fd_op)?.to_i32()?;
330 let offset = this.read_scalar(offset_op)?.to_i64()?;
331 let whence = this.read_scalar(whence_op)?.to_i32()?;
333 let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
334 SeekFrom::Start(offset as u64)
335 } else if whence == this.eval_libc_i32("SEEK_CUR")? {
336 SeekFrom::Current(offset)
337 } else if whence == this.eval_libc_i32("SEEK_END")? {
338 SeekFrom::End(offset)
340 let einval = this.eval_libc("EINVAL")?;
341 this.set_last_error(einval)?;
345 if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
346 let result = file.seek(seek_from).map(|offset| offset as i64);
347 this.try_unwrap_io_result(result)
349 this.handle_not_found()
353 fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
354 let this = self.eval_context_mut();
356 this.check_no_isolation("unlink")?;
358 let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
360 let result = remove_file(path).map(|_| 0);
362 this.try_unwrap_io_result(result)
367 target_op: OpTy<'tcx, Tag>,
368 linkpath_op: OpTy<'tcx, Tag>
369 ) -> InterpResult<'tcx, i32> {
370 #[cfg(target_family = "unix")]
371 fn create_link(src: PathBuf, dst: PathBuf) -> std::io::Result<()> {
372 std::os::unix::fs::symlink(src, dst)
375 #[cfg(target_family = "windows")]
376 fn create_link(src: PathBuf, dst: PathBuf) -> std::io::Result<()> {
377 use std::os::windows::fs;
379 fs::symlink_dir(src, dst)
381 fs::symlink_file(src, dst)
385 let this = self.eval_context_mut();
387 this.check_no_isolation("symlink")?;
389 let target = this.read_os_str_from_c_str(this.read_scalar(target_op)?.not_undef()?)?.into();
390 let linkpath = this.read_os_str_from_c_str(this.read_scalar(linkpath_op)?.not_undef()?)?.into();
392 this.try_unwrap_io_result(create_link(target, linkpath).map(|_| 0))
397 path_op: OpTy<'tcx, Tag>,
398 buf_op: OpTy<'tcx, Tag>,
399 ) -> InterpResult<'tcx, i32> {
400 let this = self.eval_context_mut();
401 this.check_no_isolation("stat")?;
402 this.assert_platform("macos", "stat");
403 // `stat` always follows symlinks.
404 this.macos_stat_or_lstat(true, path_op, buf_op)
407 // `lstat` is used to get symlink metadata.
410 path_op: OpTy<'tcx, Tag>,
411 buf_op: OpTy<'tcx, Tag>,
412 ) -> InterpResult<'tcx, i32> {
413 let this = self.eval_context_mut();
414 this.check_no_isolation("lstat")?;
415 this.assert_platform("macos", "lstat");
416 this.macos_stat_or_lstat(false, path_op, buf_op)
421 fd_op: OpTy<'tcx, Tag>,
422 buf_op: OpTy<'tcx, Tag>,
423 ) -> InterpResult<'tcx, i32> {
424 let this = self.eval_context_mut();
426 this.check_no_isolation("fstat")?;
427 this.assert_platform("macos", "fstat");
429 let fd = this.read_scalar(fd_op)?.to_i32()?;
431 let metadata = match FileMetadata::from_fd(this, fd)? {
432 Some(metadata) => metadata,
433 None => return Ok(-1),
435 macos_stat_write_buf(this, metadata, buf_op)
438 /// Emulate `stat` or `lstat` on the `macos` platform. This function is not intended to be
439 /// called directly from `emulate_foreign_item_by_name`, so it does not check if isolation is
440 /// disabled or if the target platform is the correct one. Please use `macos_stat` or
441 /// `macos_lstat` instead.
442 fn macos_stat_or_lstat(
444 follow_symlink: bool,
445 path_op: OpTy<'tcx, Tag>,
446 buf_op: OpTy<'tcx, Tag>,
447 ) -> InterpResult<'tcx, i32> {
448 let this = self.eval_context_mut();
450 let path_scalar = this.read_scalar(path_op)?.not_undef()?;
451 let path: PathBuf = this.read_os_str_from_c_str(path_scalar)?.into();
453 let metadata = match FileMetadata::from_path(this, path, follow_symlink)? {
454 Some(metadata) => metadata,
455 None => return Ok(-1),
457 macos_stat_write_buf(this, metadata, buf_op)
462 dirfd_op: OpTy<'tcx, Tag>, // Should be an `int`
463 pathname_op: OpTy<'tcx, Tag>, // Should be a `const char *`
464 flags_op: OpTy<'tcx, Tag>, // Should be an `int`
465 _mask_op: OpTy<'tcx, Tag>, // Should be an `unsigned int`
466 statxbuf_op: OpTy<'tcx, Tag>, // Should be a `struct statx *`
467 ) -> InterpResult<'tcx, i32> {
468 let this = self.eval_context_mut();
470 this.check_no_isolation("statx")?;
471 this.assert_platform("linux", "statx");
473 let statxbuf_scalar = this.read_scalar(statxbuf_op)?.not_undef()?;
474 let pathname_scalar = this.read_scalar(pathname_op)?.not_undef()?;
476 // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
477 if this.is_null(statxbuf_scalar)? || this.is_null(pathname_scalar)? {
478 let efault = this.eval_libc("EFAULT")?;
479 this.set_last_error(efault)?;
483 // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
484 // proper `MemPlace` and then write the results of this function to it. However, the
485 // `syscall` function is untyped. This means that all the `statx` parameters are provided
486 // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
487 // `statxbuf_op` by using the `libc::statx` struct type.
488 let statxbuf_place = {
489 // FIXME: This long path is required because `libc::statx` is an struct and also a
490 // function and `resolve_path` is returning the latter.
492 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])?
493 .monomorphic_ty(*this.tcx);
494 let statxbuf_ty = this.tcx.mk_mut_ptr(statx_ty);
495 let statxbuf_layout = this.layout_of(statxbuf_ty)?;
496 let statxbuf_imm = ImmTy::from_scalar(statxbuf_scalar, statxbuf_layout);
497 this.ref_to_mplace(statxbuf_imm)?
500 let path: PathBuf = this.read_os_str_from_c_str(pathname_scalar)?.into();
501 // `flags` should be a `c_int` but the `syscall` function provides an `isize`.
503 this.read_scalar(flags_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
504 err_unsup_format!("Failed to convert pointer sized operand to integer: {}", e)
506 let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
507 // `dirfd` should be a `c_int` but the `syscall` function provides an `isize`.
509 this.read_scalar(dirfd_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
510 err_unsup_format!("Failed to convert pointer sized operand to integer: {}", e)
513 // * interpreting `path` as an absolute directory,
514 // * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
515 // * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
517 // Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
518 // found this error, please open an issue reporting it.
520 path.is_absolute() ||
521 dirfd == this.eval_libc_i32("AT_FDCWD")? ||
522 (path.as_os_str().is_empty() && empty_path_flag)
525 "Using statx is only supported with absolute paths, relative paths with the file \
526 descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
531 // the `_mask_op` paramter specifies the file information that the caller requested.
532 // However `statx` is allowed to return information that was not requested or to not
533 // return information that was requested. This `mask` represents the information we can
534 // actually provide in any host platform.
536 this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
538 // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
540 let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
542 // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
543 // represented by dirfd, whether it's a directory or otherwise.
544 let metadata = if path.as_os_str().is_empty() && empty_path_flag {
545 FileMetadata::from_fd(this, dirfd)?
547 FileMetadata::from_path(this, path, follow_symlink)?
549 let metadata = match metadata {
550 Some(metadata) => metadata,
551 None => return Ok(-1),
554 // The `mode` field specifies the type of the file and the permissions over the file for
555 // the owner, its group and other users. Given that we can only provide the file type
556 // without using platform specific methods, we only set the bits corresponding to the file
557 // type. This should be an `__u16` but `libc` provides its values as `u32`.
558 let mode: u16 = metadata
562 .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
564 // We need to set the corresponding bits of `mask` if the access, creation and modification
565 // times were available. Otherwise we let them be zero.
566 let (access_sec, access_nsec) = metadata.accessed.map(|tup| {
567 mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
568 InterpResult::Ok(tup)
569 }).unwrap_or(Ok((0, 0)))?;
571 let (created_sec, created_nsec) = metadata.created.map(|tup| {
572 mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
573 InterpResult::Ok(tup)
574 }).unwrap_or(Ok((0, 0)))?;
576 let (modified_sec, modified_nsec) = metadata.modified.map(|tup| {
577 mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
578 InterpResult::Ok(tup)
579 }).unwrap_or(Ok((0, 0)))?;
581 let __u32_layout = this.libc_ty_layout("__u32")?;
582 let __u64_layout = this.libc_ty_layout("__u64")?;
583 let __u16_layout = this.libc_ty_layout("__u16")?;
585 // Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
586 // zero for the unavailable fields.
588 immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
589 immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
590 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
591 immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
592 immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
593 immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
594 immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
595 immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
596 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
597 immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
598 immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
599 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
600 immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
601 immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
602 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
603 immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
604 immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
605 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
606 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
607 immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
608 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
609 immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
610 immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
611 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
612 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
613 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
614 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
615 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
618 this.write_packed_immediates(statxbuf_place, &imms)?;
623 /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
624 /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
625 /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
626 /// types (like `read`, that returns an `i64`).
627 fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
628 let this = self.eval_context_mut();
629 let ebadf = this.eval_libc("EBADF")?;
630 this.set_last_error(ebadf)?;
636 oldpath_op: OpTy<'tcx, Tag>,
637 newpath_op: OpTy<'tcx, Tag>,
638 ) -> InterpResult<'tcx, i32> {
639 let this = self.eval_context_mut();
641 this.check_no_isolation("rename")?;
643 let oldpath_scalar = this.read_scalar(oldpath_op)?.not_undef()?;
644 let newpath_scalar = this.read_scalar(newpath_op)?.not_undef()?;
646 if this.is_null(oldpath_scalar)? || this.is_null(newpath_scalar)? {
647 let efault = this.eval_libc("EFAULT")?;
648 this.set_last_error(efault)?;
652 let oldpath = this.read_os_str_from_c_str(oldpath_scalar)?;
653 let newpath = this.read_os_str_from_c_str(newpath_scalar)?;
655 let result = rename(oldpath, newpath).map(|_| 0);
657 this.try_unwrap_io_result(result)
661 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
662 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
664 fn extract_sec_and_nsec<'tcx>(
665 time: std::io::Result<SystemTime>
666 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
667 time.ok().map(|time| {
668 let duration = system_time_to_duration(&time)?;
669 Ok((duration.as_secs(), duration.subsec_nanos()))
673 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
675 struct FileMetadata {
678 created: Option<(u64, u32)>,
679 accessed: Option<(u64, u32)>,
680 modified: Option<(u64, u32)>,
684 fn from_path<'tcx, 'mir>(
685 ecx: &mut MiriEvalContext<'mir, 'tcx>,
688 ) -> InterpResult<'tcx, Option<FileMetadata>> {
689 let metadata = if follow_symlink {
690 std::fs::metadata(path)
692 std::fs::symlink_metadata(path)
695 FileMetadata::from_meta(ecx, metadata)
698 fn from_fd<'tcx, 'mir>(
699 ecx: &mut MiriEvalContext<'mir, 'tcx>,
701 ) -> InterpResult<'tcx, Option<FileMetadata>> {
702 let option = ecx.machine.file_handler.handles.get(&fd);
703 let file = match option {
704 Some(FileHandle { file, writable: _ }) => file,
705 None => return ecx.handle_not_found().map(|_: i32| None),
707 let metadata = file.metadata();
709 FileMetadata::from_meta(ecx, metadata)
712 fn from_meta<'tcx, 'mir>(
713 ecx: &mut MiriEvalContext<'mir, 'tcx>,
714 metadata: Result<std::fs::Metadata, std::io::Error>,
715 ) -> InterpResult<'tcx, Option<FileMetadata>> {
716 let metadata = match metadata {
717 Ok(metadata) => metadata,
719 ecx.set_last_error_from_io_error(e)?;
724 let file_type = metadata.file_type();
726 let mode_name = if file_type.is_file() {
728 } else if file_type.is_dir() {
734 let mode = ecx.eval_libc(mode_name)?;
736 let size = metadata.len();
738 let created = extract_sec_and_nsec(metadata.created())?;
739 let accessed = extract_sec_and_nsec(metadata.accessed())?;
740 let modified = extract_sec_and_nsec(metadata.modified())?;
742 // FIXME: Provide more fields using platform specific methods.
743 Ok(Some(FileMetadata { mode, size, created, accessed, modified }))
747 fn macos_stat_write_buf<'tcx, 'mir>(
748 ecx: &mut MiriEvalContext<'mir, 'tcx>,
749 metadata: FileMetadata,
750 buf_op: OpTy<'tcx, Tag>,
751 ) -> InterpResult<'tcx, i32> {
752 let mode: u16 = metadata.mode.to_u16()?;
754 let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
755 let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
756 let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
758 let dev_t_layout = ecx.libc_ty_layout("dev_t")?;
759 let mode_t_layout = ecx.libc_ty_layout("mode_t")?;
760 let nlink_t_layout = ecx.libc_ty_layout("nlink_t")?;
761 let ino_t_layout = ecx.libc_ty_layout("ino_t")?;
762 let uid_t_layout = ecx.libc_ty_layout("uid_t")?;
763 let gid_t_layout = ecx.libc_ty_layout("gid_t")?;
764 let time_t_layout = ecx.libc_ty_layout("time_t")?;
765 let long_layout = ecx.libc_ty_layout("c_long")?;
766 let off_t_layout = ecx.libc_ty_layout("off_t")?;
767 let blkcnt_t_layout = ecx.libc_ty_layout("blkcnt_t")?;
768 let blksize_t_layout = ecx.libc_ty_layout("blksize_t")?;
769 let uint32_t_layout = ecx.libc_ty_layout("uint32_t")?;
771 // We need to add 32 bits of padding after `st_rdev` if we are on a 64-bit platform.
772 let pad_layout = if ecx.tcx.sess.target.ptr_width == 64 {
775 ecx.layout_of(ecx.tcx.mk_unit())?
779 immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
780 immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
781 immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
782 immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
783 immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
784 immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
785 immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
786 immty_from_uint_checked(0u128, pad_layout)?, // padding for 64-bit targets
787 immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
788 immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
789 immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
790 immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
791 immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
792 immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
793 immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
794 immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
795 immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
796 immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
797 immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
798 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
799 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
802 let buf = ecx.deref_operand(buf_op)?;
803 ecx.write_packed_immediates(buf, &imms)?;