1 use std::collections::BTreeMap;
2 use std::convert::{TryFrom, TryInto};
3 use std::fs::{remove_dir, remove_file, rename, DirBuilder, 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> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
67 trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
68 /// Emulate `stat` or `lstat` on the `macos` platform. This function is not intended to be
69 /// called directly from `emulate_foreign_item_by_name`, so it does not check if isolation is
70 /// disabled or if the target platform is the correct one. Please use `macos_stat` or
71 /// `macos_lstat` instead.
72 fn macos_stat_or_lstat(
75 path_op: OpTy<'tcx, Tag>,
76 buf_op: OpTy<'tcx, Tag>,
77 ) -> InterpResult<'tcx, i32> {
78 let this = self.eval_context_mut();
80 let path_scalar = this.read_scalar(path_op)?.not_undef()?;
81 let path: PathBuf = this.read_os_str_from_c_str(path_scalar)?.into();
83 let metadata = match FileMetadata::from_path(this, path, follow_symlink)? {
84 Some(metadata) => metadata,
85 None => return Ok(-1),
87 this.macos_stat_write_buf(metadata, buf_op)
90 fn macos_stat_write_buf(
92 metadata: FileMetadata,
93 buf_op: OpTy<'tcx, Tag>,
94 ) -> InterpResult<'tcx, i32> {
95 let this = self.eval_context_mut();
97 let mode: u16 = metadata.mode.to_u16()?;
99 let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
100 let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
101 let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
103 let dev_t_layout = this.libc_ty_layout("dev_t")?;
104 let mode_t_layout = this.libc_ty_layout("mode_t")?;
105 let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
106 let ino_t_layout = this.libc_ty_layout("ino_t")?;
107 let uid_t_layout = this.libc_ty_layout("uid_t")?;
108 let gid_t_layout = this.libc_ty_layout("gid_t")?;
109 let time_t_layout = this.libc_ty_layout("time_t")?;
110 let long_layout = this.libc_ty_layout("c_long")?;
111 let off_t_layout = this.libc_ty_layout("off_t")?;
112 let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
113 let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
114 let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
116 // We need to add 32 bits of padding after `st_rdev` if we are on a 64-bit platform.
117 let pad_layout = if this.tcx.sess.target.ptr_width == 64 {
120 this.layout_of(this.tcx.mk_unit())?
124 immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
125 immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
126 immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
127 immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
128 immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
129 immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
130 immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
131 immty_from_uint_checked(0u128, pad_layout)?, // padding for 64-bit targets
132 immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
133 immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
134 immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
135 immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
136 immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
137 immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
138 immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
139 immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
140 immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
141 immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
142 immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
143 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
144 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
147 let buf = this.deref_operand(buf_op)?;
148 this.write_packed_immediates(buf, &imms)?;
153 /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
154 /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
155 /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
156 /// types (like `read`, that returns an `i64`).
157 fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
158 let this = self.eval_context_mut();
159 let ebadf = this.eval_libc("EBADF")?;
160 this.set_last_error(ebadf)?;
165 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
166 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
169 path_op: OpTy<'tcx, Tag>,
170 flag_op: OpTy<'tcx, Tag>,
171 ) -> InterpResult<'tcx, i32> {
172 let this = self.eval_context_mut();
174 this.check_no_isolation("open")?;
176 let flag = this.read_scalar(flag_op)?.to_i32()?;
178 let mut options = OpenOptions::new();
180 let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
181 let o_wronly = this.eval_libc_i32("O_WRONLY")?;
182 let o_rdwr = this.eval_libc_i32("O_RDWR")?;
183 // The first two bits of the flag correspond to the access mode in linux, macOS and
184 // windows. We need to check that in fact the access mode flags for the current platform
185 // only use these two bits, otherwise we are in an unsupported platform and should error.
186 if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
187 throw_unsup_format!("Access mode flags on this platform are unsupported");
189 let mut writable = true;
191 // Now we check the access mode
192 let access_mode = flag & 0b11;
194 if access_mode == o_rdonly {
197 } else if access_mode == o_wronly {
199 } else if access_mode == o_rdwr {
200 options.read(true).write(true);
202 throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
204 // We need to check that there aren't unsupported options in `flag`. For this we try to
205 // reproduce the content of `flag` in the `mirror` variable using only the supported
207 let mut mirror = access_mode;
209 let o_append = this.eval_libc_i32("O_APPEND")?;
210 if flag & o_append != 0 {
211 options.append(true);
214 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
215 if flag & o_trunc != 0 {
216 options.truncate(true);
219 let o_creat = this.eval_libc_i32("O_CREAT")?;
220 if flag & o_creat != 0 {
221 options.create(true);
224 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
225 if flag & o_cloexec != 0 {
226 // We do not need to do anything for this flag because `std` already sets it.
227 // (Technically we do not support *not* setting this flag, but we ignore that.)
230 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
231 // then we throw an error.
233 throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
236 let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
238 let fd = options.open(&path).map(|file| {
239 let fh = &mut this.machine.file_handler;
240 fh.insert_fd(FileHandle { file, writable })
243 this.try_unwrap_io_result(fd)
248 fd_op: OpTy<'tcx, Tag>,
249 cmd_op: OpTy<'tcx, Tag>,
250 start_op: Option<OpTy<'tcx, Tag>>,
251 ) -> InterpResult<'tcx, i32> {
252 let this = self.eval_context_mut();
254 this.check_no_isolation("fcntl")?;
256 let fd = this.read_scalar(fd_op)?.to_i32()?;
257 let cmd = this.read_scalar(cmd_op)?.to_i32()?;
258 // We only support getting the flags for a descriptor.
259 if cmd == this.eval_libc_i32("F_GETFD")? {
260 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
261 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
262 // always sets this flag when opening a file. However we still need to check that the
263 // file itself is open.
264 if this.machine.file_handler.handles.contains_key(&fd) {
265 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
267 this.handle_not_found()
269 } else if cmd == this.eval_libc_i32("F_DUPFD")?
270 || cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
272 // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
273 // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
274 // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
275 // thus they can share the same implementation here.
276 if fd < MIN_NORMAL_FILE_FD {
277 throw_unsup_format!("Duplicating file descriptors for stdin, stdout, or stderr is not supported")
279 let start_op = start_op.ok_or_else(|| {
281 "fcntl with command F_DUPFD or F_DUPFD_CLOEXEC requires a third argument"
284 let start = this.read_scalar(start_op)?.to_i32()?;
285 let fh = &mut this.machine.file_handler;
286 let (file_result, writable) = match fh.handles.get(&fd) {
287 Some(FileHandle { file, writable }) => (file.try_clone(), *writable),
288 None => return this.handle_not_found(),
290 let fd_result = file_result.map(|duplicated| {
291 fh.insert_fd_with_min_fd(FileHandle { file: duplicated, writable }, start)
293 this.try_unwrap_io_result(fd_result)
295 throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
299 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
300 let this = self.eval_context_mut();
302 this.check_no_isolation("close")?;
304 let fd = this.read_scalar(fd_op)?.to_i32()?;
306 if let Some(FileHandle { file, writable }) = this.machine.file_handler.handles.remove(&fd) {
307 // We sync the file if it was opened in a mode different than read-only.
309 // `File::sync_all` does the checks that are done when closing a file. We do this to
310 // to handle possible errors correctly.
311 let result = this.try_unwrap_io_result(file.sync_all().map(|_| 0i32));
312 // Now we actually close the file.
314 // And return the result.
317 // We drop the file, this closes it but ignores any errors produced when closing
318 // it. This is done because `File::sync_all` cannot be done over files like
319 // `/dev/urandom` which are read-only. Check
320 // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439 for a deeper
326 this.handle_not_found()
332 fd_op: OpTy<'tcx, Tag>,
333 buf_op: OpTy<'tcx, Tag>,
334 count_op: OpTy<'tcx, Tag>,
335 ) -> InterpResult<'tcx, i64> {
336 let this = self.eval_context_mut();
338 this.check_no_isolation("read")?;
340 let fd = this.read_scalar(fd_op)?.to_i32()?;
341 let buf = this.read_scalar(buf_op)?.not_undef()?;
342 let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
344 // Check that the *entire* buffer is actually valid memory.
345 this.memory.check_ptr_access(
347 Size::from_bytes(count),
348 Align::from_bytes(1).unwrap(),
351 // We cap the number of read bytes to the largest value that we are able to fit in both the
352 // host's and target's `isize`. This saves us from having to handle overflows later.
353 let count = count.min(this.isize_max() as u64).min(isize::max_value() as u64);
355 if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
356 // This can never fail because `count` was capped to be smaller than
357 // `isize::max_value()`.
358 let count = isize::try_from(count).unwrap();
359 // We want to read at most `count` bytes. We are sure that `count` is not negative
360 // because it was a target's `usize`. Also we are sure that its smaller than
361 // `usize::max_value()` because it is a host's `isize`.
362 let mut bytes = vec![0; count as usize];
365 // `File::read` never returns a value larger than `count`, so this cannot fail.
366 .map(|c| i64::try_from(c).unwrap());
370 // If reading to `bytes` did not fail, we write those bytes to the buffer.
371 this.memory.write_bytes(buf, bytes)?;
375 this.set_last_error_from_io_error(e)?;
380 this.handle_not_found()
386 fd_op: OpTy<'tcx, Tag>,
387 buf_op: OpTy<'tcx, Tag>,
388 count_op: OpTy<'tcx, Tag>,
389 ) -> InterpResult<'tcx, i64> {
390 let this = self.eval_context_mut();
392 this.check_no_isolation("write")?;
394 let fd = this.read_scalar(fd_op)?.to_i32()?;
395 let buf = this.read_scalar(buf_op)?.not_undef()?;
396 let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
398 // Check that the *entire* buffer is actually valid memory.
399 this.memory.check_ptr_access(
401 Size::from_bytes(count),
402 Align::from_bytes(1).unwrap(),
405 // We cap the number of written bytes to the largest value that we are able to fit in both the
406 // host's and target's `isize`. This saves us from having to handle overflows later.
407 let count = count.min(this.isize_max() as u64).min(isize::max_value() as u64);
409 if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
410 let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
411 let result = file.write(&bytes).map(|c| i64::try_from(c).unwrap());
412 this.try_unwrap_io_result(result)
414 this.handle_not_found()
420 fd_op: OpTy<'tcx, Tag>,
421 offset_op: OpTy<'tcx, Tag>,
422 whence_op: OpTy<'tcx, Tag>,
423 ) -> InterpResult<'tcx, i64> {
424 let this = self.eval_context_mut();
426 this.check_no_isolation("lseek64")?;
428 let fd = this.read_scalar(fd_op)?.to_i32()?;
429 let offset = this.read_scalar(offset_op)?.to_i64()?;
430 let whence = this.read_scalar(whence_op)?.to_i32()?;
432 let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
433 SeekFrom::Start(offset as u64)
434 } else if whence == this.eval_libc_i32("SEEK_CUR")? {
435 SeekFrom::Current(offset)
436 } else if whence == this.eval_libc_i32("SEEK_END")? {
437 SeekFrom::End(offset)
439 let einval = this.eval_libc("EINVAL")?;
440 this.set_last_error(einval)?;
444 if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
445 let result = file.seek(seek_from).map(|offset| offset as i64);
446 this.try_unwrap_io_result(result)
448 this.handle_not_found()
452 fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
453 let this = self.eval_context_mut();
455 this.check_no_isolation("unlink")?;
457 let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
459 let result = remove_file(path).map(|_| 0);
461 this.try_unwrap_io_result(result)
466 target_op: OpTy<'tcx, Tag>,
467 linkpath_op: OpTy<'tcx, Tag>
468 ) -> InterpResult<'tcx, i32> {
469 #[cfg(target_family = "unix")]
470 fn create_link(src: PathBuf, dst: PathBuf) -> std::io::Result<()> {
471 std::os::unix::fs::symlink(src, dst)
474 #[cfg(target_family = "windows")]
475 fn create_link(src: PathBuf, dst: PathBuf) -> std::io::Result<()> {
476 use std::os::windows::fs;
478 fs::symlink_dir(src, dst)
480 fs::symlink_file(src, dst)
484 let this = self.eval_context_mut();
486 this.check_no_isolation("symlink")?;
488 let target = this.read_os_str_from_c_str(this.read_scalar(target_op)?.not_undef()?)?.into();
489 let linkpath = this.read_os_str_from_c_str(this.read_scalar(linkpath_op)?.not_undef()?)?.into();
491 this.try_unwrap_io_result(create_link(target, linkpath).map(|_| 0))
496 path_op: OpTy<'tcx, Tag>,
497 buf_op: OpTy<'tcx, Tag>,
498 ) -> InterpResult<'tcx, i32> {
499 let this = self.eval_context_mut();
500 this.check_no_isolation("stat")?;
501 this.assert_platform("macos", "stat");
502 // `stat` always follows symlinks.
503 this.macos_stat_or_lstat(true, path_op, buf_op)
506 // `lstat` is used to get symlink metadata.
509 path_op: OpTy<'tcx, Tag>,
510 buf_op: OpTy<'tcx, Tag>,
511 ) -> InterpResult<'tcx, i32> {
512 let this = self.eval_context_mut();
513 this.check_no_isolation("lstat")?;
514 this.assert_platform("macos", "lstat");
515 this.macos_stat_or_lstat(false, path_op, buf_op)
520 fd_op: OpTy<'tcx, Tag>,
521 buf_op: OpTy<'tcx, Tag>,
522 ) -> InterpResult<'tcx, i32> {
523 let this = self.eval_context_mut();
525 this.check_no_isolation("fstat")?;
526 this.assert_platform("macos", "fstat");
528 let fd = this.read_scalar(fd_op)?.to_i32()?;
530 let metadata = match FileMetadata::from_fd(this, fd)? {
531 Some(metadata) => metadata,
532 None => return Ok(-1),
534 this.macos_stat_write_buf(metadata, buf_op)
539 dirfd_op: OpTy<'tcx, Tag>, // Should be an `int`
540 pathname_op: OpTy<'tcx, Tag>, // Should be a `const char *`
541 flags_op: OpTy<'tcx, Tag>, // Should be an `int`
542 _mask_op: OpTy<'tcx, Tag>, // Should be an `unsigned int`
543 statxbuf_op: OpTy<'tcx, Tag>, // Should be a `struct statx *`
544 ) -> InterpResult<'tcx, i32> {
545 let this = self.eval_context_mut();
547 this.check_no_isolation("statx")?;
548 this.assert_platform("linux", "statx");
550 let statxbuf_scalar = this.read_scalar(statxbuf_op)?.not_undef()?;
551 let pathname_scalar = this.read_scalar(pathname_op)?.not_undef()?;
553 // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
554 if this.is_null(statxbuf_scalar)? || this.is_null(pathname_scalar)? {
555 let efault = this.eval_libc("EFAULT")?;
556 this.set_last_error(efault)?;
560 // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
561 // proper `MemPlace` and then write the results of this function to it. However, the
562 // `syscall` function is untyped. This means that all the `statx` parameters are provided
563 // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
564 // `statxbuf_op` by using the `libc::statx` struct type.
565 let statxbuf_place = {
566 // FIXME: This long path is required because `libc::statx` is an struct and also a
567 // function and `resolve_path` is returning the latter.
569 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])?
570 .monomorphic_ty(*this.tcx);
571 let statxbuf_ty = this.tcx.mk_mut_ptr(statx_ty);
572 let statxbuf_layout = this.layout_of(statxbuf_ty)?;
573 let statxbuf_imm = ImmTy::from_scalar(statxbuf_scalar, statxbuf_layout);
574 this.ref_to_mplace(statxbuf_imm)?
577 let path: PathBuf = this.read_os_str_from_c_str(pathname_scalar)?.into();
578 // `flags` should be a `c_int` but the `syscall` function provides an `isize`.
580 this.read_scalar(flags_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
581 err_unsup_format!("Failed to convert pointer sized operand to integer: {}", e)
583 let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
584 // `dirfd` should be a `c_int` but the `syscall` function provides an `isize`.
586 this.read_scalar(dirfd_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
587 err_unsup_format!("Failed to convert pointer sized operand to integer: {}", e)
590 // * interpreting `path` as an absolute directory,
591 // * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
592 // * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
594 // Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
595 // found this error, please open an issue reporting it.
597 path.is_absolute() ||
598 dirfd == this.eval_libc_i32("AT_FDCWD")? ||
599 (path.as_os_str().is_empty() && empty_path_flag)
602 "Using statx is only supported with absolute paths, relative paths with the file \
603 descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
608 // the `_mask_op` paramter specifies the file information that the caller requested.
609 // However `statx` is allowed to return information that was not requested or to not
610 // return information that was requested. This `mask` represents the information we can
611 // actually provide in any host platform.
613 this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
615 // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
617 let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
619 // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
620 // represented by dirfd, whether it's a directory or otherwise.
621 let metadata = if path.as_os_str().is_empty() && empty_path_flag {
622 FileMetadata::from_fd(this, dirfd)?
624 FileMetadata::from_path(this, path, follow_symlink)?
626 let metadata = match metadata {
627 Some(metadata) => metadata,
628 None => return Ok(-1),
631 // The `mode` field specifies the type of the file and the permissions over the file for
632 // the owner, its group and other users. Given that we can only provide the file type
633 // without using platform specific methods, we only set the bits corresponding to the file
634 // type. This should be an `__u16` but `libc` provides its values as `u32`.
635 let mode: u16 = metadata
639 .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
641 // We need to set the corresponding bits of `mask` if the access, creation and modification
642 // times were available. Otherwise we let them be zero.
643 let (access_sec, access_nsec) = metadata.accessed.map(|tup| {
644 mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
645 InterpResult::Ok(tup)
646 }).unwrap_or(Ok((0, 0)))?;
648 let (created_sec, created_nsec) = metadata.created.map(|tup| {
649 mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
650 InterpResult::Ok(tup)
651 }).unwrap_or(Ok((0, 0)))?;
653 let (modified_sec, modified_nsec) = metadata.modified.map(|tup| {
654 mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
655 InterpResult::Ok(tup)
656 }).unwrap_or(Ok((0, 0)))?;
658 let __u32_layout = this.libc_ty_layout("__u32")?;
659 let __u64_layout = this.libc_ty_layout("__u64")?;
660 let __u16_layout = this.libc_ty_layout("__u16")?;
662 // Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
663 // zero for the unavailable fields.
665 immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
666 immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
667 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
668 immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
669 immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
670 immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
671 immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
672 immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
673 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
674 immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
675 immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
676 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
677 immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
678 immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
679 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
680 immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
681 immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
682 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
683 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
684 immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
685 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
686 immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
687 immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
688 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
689 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
690 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
691 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
692 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
695 this.write_packed_immediates(statxbuf_place, &imms)?;
702 oldpath_op: OpTy<'tcx, Tag>,
703 newpath_op: OpTy<'tcx, Tag>,
704 ) -> InterpResult<'tcx, i32> {
705 let this = self.eval_context_mut();
707 this.check_no_isolation("rename")?;
709 let oldpath_scalar = this.read_scalar(oldpath_op)?.not_undef()?;
710 let newpath_scalar = this.read_scalar(newpath_op)?.not_undef()?;
712 if this.is_null(oldpath_scalar)? || this.is_null(newpath_scalar)? {
713 let efault = this.eval_libc("EFAULT")?;
714 this.set_last_error(efault)?;
718 let oldpath = this.read_os_str_from_c_str(oldpath_scalar)?;
719 let newpath = this.read_os_str_from_c_str(newpath_scalar)?;
721 let result = rename(oldpath, newpath).map(|_| 0);
723 this.try_unwrap_io_result(result)
728 path_op: OpTy<'tcx, Tag>,
729 mode_op: OpTy<'tcx, Tag>,
730 ) -> InterpResult<'tcx, i32> {
731 let this = self.eval_context_mut();
733 this.check_no_isolation("mkdir")?;
735 let mode = this.read_scalar(mode_op)?.to_u32()?;
737 let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
739 let mut builder = DirBuilder::new();
740 #[cfg(target_family = "unix")]
742 use std::os::unix::fs::DirBuilderExt;
745 let result = builder.create(path).map(|_| 0i32);
747 this.try_unwrap_io_result(result)
752 path_op: OpTy<'tcx, Tag>,
753 ) -> InterpResult<'tcx, i32> {
754 let this = self.eval_context_mut();
756 this.check_no_isolation("rmdir")?;
758 let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
760 let result = remove_dir(path).map(|_| 0i32);
762 this.try_unwrap_io_result(result)
766 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
767 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
769 fn extract_sec_and_nsec<'tcx>(
770 time: std::io::Result<SystemTime>
771 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
772 time.ok().map(|time| {
773 let duration = system_time_to_duration(&time)?;
774 Ok((duration.as_secs(), duration.subsec_nanos()))
778 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
780 struct FileMetadata {
783 created: Option<(u64, u32)>,
784 accessed: Option<(u64, u32)>,
785 modified: Option<(u64, u32)>,
789 fn from_path<'tcx, 'mir>(
790 ecx: &mut MiriEvalContext<'mir, 'tcx>,
793 ) -> InterpResult<'tcx, Option<FileMetadata>> {
794 let metadata = if follow_symlink {
795 std::fs::metadata(path)
797 std::fs::symlink_metadata(path)
800 FileMetadata::from_meta(ecx, metadata)
803 fn from_fd<'tcx, 'mir>(
804 ecx: &mut MiriEvalContext<'mir, 'tcx>,
806 ) -> InterpResult<'tcx, Option<FileMetadata>> {
807 let option = ecx.machine.file_handler.handles.get(&fd);
808 let file = match option {
809 Some(FileHandle { file, writable: _ }) => file,
810 None => return ecx.handle_not_found().map(|_: i32| None),
812 let metadata = file.metadata();
814 FileMetadata::from_meta(ecx, metadata)
817 fn from_meta<'tcx, 'mir>(
818 ecx: &mut MiriEvalContext<'mir, 'tcx>,
819 metadata: Result<std::fs::Metadata, std::io::Error>,
820 ) -> InterpResult<'tcx, Option<FileMetadata>> {
821 let metadata = match metadata {
822 Ok(metadata) => metadata,
824 ecx.set_last_error_from_io_error(e)?;
829 let file_type = metadata.file_type();
831 let mode_name = if file_type.is_file() {
833 } else if file_type.is_dir() {
839 let mode = ecx.eval_libc(mode_name)?;
841 let size = metadata.len();
843 let created = extract_sec_and_nsec(metadata.created())?;
844 let accessed = extract_sec_and_nsec(metadata.accessed())?;
845 let modified = extract_sec_and_nsec(metadata.modified())?;
847 // FIXME: Provide more fields using platform specific methods.
848 Ok(Some(FileMetadata { mode, size, created, accessed, modified }))