1 use std::collections::BTreeMap;
2 use std::convert::{TryFrom, TryInto};
3 use std::fs::{read_dir, remove_dir, remove_file, rename, DirBuilder, File, FileType, OpenOptions, ReadDir};
4 use std::io::{self, Read, Seek, SeekFrom, Write};
6 use std::time::SystemTime;
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_target::abi::{Align, LayoutOf, Size};
15 use stacked_borrows::Tag;
16 use helpers::{check_arg_count, immty_from_int_checked, immty_from_uint_checked};
17 use shims::time::system_time_to_duration;
25 trait FileDescriptor<'tcx> : std::fmt::Debug {
26 fn as_file_handle(&self) -> InterpResult<'tcx, &FileHandle>;
28 fn read(&mut self, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>>;
29 fn write(&mut self, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>>;
30 fn seek(&mut self, offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>>;
33 impl<'tcx> FileDescriptor<'tcx> for FileHandle {
34 fn as_file_handle(&self) -> InterpResult<'tcx, &FileHandle> {
38 fn read(&mut self, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
39 Ok(self.file.read(bytes))
42 fn write(&mut self, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
43 Ok(self.file.write(bytes))
46 fn seek(&mut self, offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
47 Ok(self.file.seek(offset))
51 impl<'tcx> FileDescriptor<'tcx> for io::Stdin {
52 fn as_file_handle(&self) -> InterpResult<'tcx, &FileHandle> {
53 throw_unsup_format!("stdin cannot be used as FileHandle");
56 fn read(&mut self, bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
57 Ok(Read::read(self, bytes))
60 fn write(&mut self, _bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
61 throw_unsup_format!("cannot write to stdin");
64 fn seek(&mut self, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
65 throw_unsup_format!("cannot seek on stdin");
69 impl<'tcx> FileDescriptor<'tcx> for io::Stdout {
70 fn as_file_handle(&self) -> InterpResult<'tcx, &FileHandle> {
71 throw_unsup_format!("stdout cannot be used as FileHandle");
74 fn read(&mut self, _bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
75 throw_unsup_format!("cannot read from stdout");
78 fn write(&mut self, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
79 let result = Write::write(self, bytes);
80 // Stdout is buffered, flush to make sure it appears on the
81 // screen. This is the write() syscall of the interpreted
82 // program, we want it to correspond to a write() syscall on
83 // the host -- there is no good in adding extra buffering
85 io::stdout().flush().unwrap();
90 fn seek(&mut self, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
91 throw_unsup_format!("cannot seek on stdout");
95 impl<'tcx> FileDescriptor<'tcx> for io::Stderr {
96 fn as_file_handle(&self) -> InterpResult<'tcx, &FileHandle> {
97 throw_unsup_format!("stdout cannot be used as FileHandle");
100 fn read(&mut self, _bytes: &mut [u8]) -> InterpResult<'tcx, io::Result<usize>> {
101 throw_unsup_format!("cannot read from stderr");
104 fn write(&mut self, bytes: &[u8]) -> InterpResult<'tcx, io::Result<usize>> {
105 Ok(Write::write(self, bytes))
108 fn seek(&mut self, _offset: SeekFrom) -> InterpResult<'tcx, io::Result<u64>> {
109 throw_unsup_format!("cannot seek on stderr");
114 pub struct FileHandler<'tcx> {
115 handles: BTreeMap<i32, Box<dyn FileDescriptor<'tcx>>>,
118 impl<'tcx> Default for FileHandler<'tcx> {
119 fn default() -> Self {
120 let mut handles = BTreeMap::new();
121 handles.insert(0i32, Box::new(io::stdin()) as Box<dyn FileDescriptor<'_>>);
122 handles.insert(1i32, Box::new(io::stdout()) as Box<dyn FileDescriptor<'_>>);
123 handles.insert(2i32, Box::new(io::stderr()) as Box<dyn FileDescriptor<'_>>);
131 // fd numbers 0, 1, and 2 are reserved for stdin, stdout, and stderr
132 const MIN_NORMAL_FILE_FD: i32 = 3;
134 impl<'tcx> FileHandler<'tcx> {
135 fn insert_fd(&mut self, file_handle: FileHandle) -> i32 {
136 self.insert_fd_with_min_fd(file_handle, 0)
139 fn insert_fd_with_min_fd(&mut self, file_handle: FileHandle, min_fd: i32) -> i32 {
140 let min_fd = std::cmp::max(min_fd, MIN_NORMAL_FILE_FD);
142 // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
143 // between used FDs, the find_map combinator will return it. If the first such unused FD
144 // is after all other used FDs, the find_map combinator will return None, and we will use
145 // the FD following the greatest FD thus far.
146 let candidate_new_fd = self
150 .find_map(|((fd, _fh), counter)| {
152 // There was a gap in the fds stored, return the first unused one
153 // (note that this relies on BTreeMap iterating in key order)
156 // This fd is used, keep going
160 let new_fd = candidate_new_fd.unwrap_or_else(|| {
161 // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
162 // maximum fd in the map
163 self.handles.last_key_value().map(|(fd, _)| fd.checked_add(1).unwrap()).unwrap_or(min_fd)
166 self.handles.insert(new_fd, Box::new(file_handle)).unwrap_none();
171 impl<'mir, 'tcx: 'mir> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
172 trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
173 /// Emulate `stat` or `lstat` on `macos`. This function is not intended to be
174 /// called directly from `emulate_foreign_item_by_name`, so it does not check if isolation is
175 /// disabled or if the target OS is the correct one. Please use `macos_stat` or
176 /// `macos_lstat` instead.
177 fn macos_stat_or_lstat(
179 follow_symlink: bool,
180 path_op: OpTy<'tcx, Tag>,
181 buf_op: OpTy<'tcx, Tag>,
182 ) -> InterpResult<'tcx, i32> {
183 let this = self.eval_context_mut();
185 let path_scalar = this.read_scalar(path_op)?.check_init()?;
186 let path = this.read_path_from_c_str(path_scalar)?.into_owned();
188 let metadata = match FileMetadata::from_path(this, &path, follow_symlink)? {
189 Some(metadata) => metadata,
190 None => return Ok(-1),
192 this.macos_stat_write_buf(metadata, buf_op)
195 fn macos_stat_write_buf(
197 metadata: FileMetadata,
198 buf_op: OpTy<'tcx, Tag>,
199 ) -> InterpResult<'tcx, i32> {
200 let this = self.eval_context_mut();
202 let mode: u16 = metadata.mode.to_u16()?;
204 let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
205 let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
206 let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
208 let dev_t_layout = this.libc_ty_layout("dev_t")?;
209 let mode_t_layout = this.libc_ty_layout("mode_t")?;
210 let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
211 let ino_t_layout = this.libc_ty_layout("ino_t")?;
212 let uid_t_layout = this.libc_ty_layout("uid_t")?;
213 let gid_t_layout = this.libc_ty_layout("gid_t")?;
214 let time_t_layout = this.libc_ty_layout("time_t")?;
215 let long_layout = this.libc_ty_layout("c_long")?;
216 let off_t_layout = this.libc_ty_layout("off_t")?;
217 let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
218 let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
219 let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
222 immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
223 immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
224 immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
225 immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
226 immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
227 immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
228 immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
229 immty_from_uint_checked(0u128, uint32_t_layout)?, // padding
230 immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
231 immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
232 immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
233 immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
234 immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
235 immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
236 immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
237 immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
238 immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
239 immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
240 immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
241 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
242 immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
245 let buf = this.deref_operand(buf_op)?;
246 this.write_packed_immediates(buf, &imms)?;
251 /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
252 /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
253 /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
254 /// types (like `read`, that returns an `i64`).
255 fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
256 let this = self.eval_context_mut();
257 let ebadf = this.eval_libc("EBADF")?;
258 this.set_last_error(ebadf)?;
262 fn file_type_to_d_type(&mut self, file_type: std::io::Result<FileType>) -> InterpResult<'tcx, i32> {
263 let this = self.eval_context_mut();
266 if file_type.is_dir() {
267 Ok(this.eval_libc("DT_DIR")?.to_u8()?.into())
268 } else if file_type.is_file() {
269 Ok(this.eval_libc("DT_REG")?.to_u8()?.into())
270 } else if file_type.is_symlink() {
271 Ok(this.eval_libc("DT_LNK")?.to_u8()?.into())
273 // Certain file types are only supported when the host is a Unix system.
274 // (i.e. devices and sockets) If it is, check those cases, if not, fall back to
275 // DT_UNKNOWN sooner.
279 use std::os::unix::fs::FileTypeExt;
280 if file_type.is_block_device() {
281 Ok(this.eval_libc("DT_BLK")?.to_u8()?.into())
282 } else if file_type.is_char_device() {
283 Ok(this.eval_libc("DT_CHR")?.to_u8()?.into())
284 } else if file_type.is_fifo() {
285 Ok(this.eval_libc("DT_FIFO")?.to_u8()?.into())
286 } else if file_type.is_socket() {
287 Ok(this.eval_libc("DT_SOCK")?.to_u8()?.into())
289 Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
293 Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
296 Err(e) => return match e.raw_os_error() {
297 Some(error) => Ok(error),
298 None => throw_unsup_format!("the error {} couldn't be converted to a return value", e),
305 pub struct DirHandler {
306 /// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
309 /// When opendir is called, a directory iterator is created on the host for the target
310 /// directory, and an entry is stored in this hash map, indexed by an ID which represents
311 /// the directory stream. When readdir is called, the directory stream ID is used to look up
312 /// the corresponding ReadDir iterator from this map, and information from the next
313 /// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
315 streams: FxHashMap<u64, ReadDir>,
316 /// ID number to be used by the next call to opendir
321 fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
322 let id = self.next_id;
324 self.streams.insert(id, read_dir).unwrap_none();
329 impl Default for DirHandler {
330 fn default() -> DirHandler {
332 streams: FxHashMap::default(),
333 // Skip 0 as an ID, because it looks like a null pointer to libc
339 fn maybe_sync_file(file: &File, writable: bool, operation: fn(&File) -> std::io::Result<()>) -> std::io::Result<i32> {
340 if !writable && cfg!(windows) {
341 // sync_all() and sync_data() will return an error on Windows hosts if the file is not opened
342 // for writing. (FlushFileBuffers requires that the file handle have the
343 // GENERIC_WRITE right)
346 let result = operation(file);
351 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
352 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
355 path_op: OpTy<'tcx, Tag>,
356 flag_op: OpTy<'tcx, Tag>,
357 mode_op: OpTy<'tcx, Tag>,
358 ) -> InterpResult<'tcx, i32> {
359 let this = self.eval_context_mut();
361 this.check_no_isolation("open")?;
363 let flag = this.read_scalar(flag_op)?.to_i32()?;
365 // Get the mode. On macOS, the argument type `mode_t` is actually `u16`, but
366 // C integer promotion rules mean that on the ABI level, it gets passed as `u32`
367 // (see https://github.com/rust-lang/rust/issues/71915).
368 let mode = this.read_scalar(mode_op)?.to_u32()?;
370 throw_unsup_format!("non-default mode 0o{:o} is not supported", mode);
373 let mut options = OpenOptions::new();
375 let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
376 let o_wronly = this.eval_libc_i32("O_WRONLY")?;
377 let o_rdwr = this.eval_libc_i32("O_RDWR")?;
378 // The first two bits of the flag correspond to the access mode in linux, macOS and
379 // windows. We need to check that in fact the access mode flags for the current target
380 // only use these two bits, otherwise we are in an unsupported target and should error.
381 if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
382 throw_unsup_format!("access mode flags on this target are unsupported");
384 let mut writable = true;
386 // Now we check the access mode
387 let access_mode = flag & 0b11;
389 if access_mode == o_rdonly {
392 } else if access_mode == o_wronly {
394 } else if access_mode == o_rdwr {
395 options.read(true).write(true);
397 throw_unsup_format!("unsupported access mode {:#x}", access_mode);
399 // We need to check that there aren't unsupported options in `flag`. For this we try to
400 // reproduce the content of `flag` in the `mirror` variable using only the supported
402 let mut mirror = access_mode;
404 let o_append = this.eval_libc_i32("O_APPEND")?;
405 if flag & o_append != 0 {
406 options.append(true);
409 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
410 if flag & o_trunc != 0 {
411 options.truncate(true);
414 let o_creat = this.eval_libc_i32("O_CREAT")?;
415 if flag & o_creat != 0 {
418 let o_excl = this.eval_libc_i32("O_EXCL")?;
419 if flag & o_excl != 0 {
421 options.create_new(true);
423 options.create(true);
426 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
427 if flag & o_cloexec != 0 {
428 // We do not need to do anything for this flag because `std` already sets it.
429 // (Technically we do not support *not* setting this flag, but we ignore that.)
432 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
433 // then we throw an error.
435 throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
438 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
440 let fd = options.open(&path).map(|file| {
441 let fh = &mut this.machine.file_handler;
442 fh.insert_fd(FileHandle { file, writable })
445 this.try_unwrap_io_result(fd)
450 args: &[OpTy<'tcx, Tag>],
451 ) -> InterpResult<'tcx, i32> {
452 let this = self.eval_context_mut();
454 this.check_no_isolation("fcntl")?;
457 throw_ub_format!("incorrect number of arguments for fcntl: got {}, expected at least 2", args.len());
459 let fd = this.read_scalar(args[0])?.to_i32()?;
460 let cmd = this.read_scalar(args[1])?.to_i32()?;
461 // We only support getting the flags for a descriptor.
462 if cmd == this.eval_libc_i32("F_GETFD")? {
463 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
464 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
465 // always sets this flag when opening a file. However we still need to check that the
466 // file itself is open.
467 let &[_, _] = check_arg_count(args)?;
468 if this.machine.file_handler.handles.contains_key(&fd) {
469 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
471 this.handle_not_found()
473 } else if cmd == this.eval_libc_i32("F_DUPFD")?
474 || cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
476 // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
477 // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
478 // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
479 // thus they can share the same implementation here.
480 let &[_, _, start] = check_arg_count(args)?;
481 let start = this.read_scalar(start)?.to_i32()?;
482 if fd < MIN_NORMAL_FILE_FD {
483 throw_unsup_format!("duplicating file descriptors for stdin, stdout, or stderr is not supported")
485 let fh = &mut this.machine.file_handler;
486 let (file_result, writable) = match fh.handles.get(&fd) {
487 Some(file_descriptor) => {
488 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
489 (file.try_clone(), *writable)
491 None => return this.handle_not_found(),
493 let fd_result = file_result.map(|duplicated| {
494 fh.insert_fd_with_min_fd(FileHandle { file: duplicated, writable }, start)
496 this.try_unwrap_io_result(fd_result)
497 } else if this.tcx.sess.target.target.target_os == "macos"
498 && cmd == this.eval_libc_i32("F_FULLFSYNC")?
500 let &[_, _] = check_arg_count(args)?;
501 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
502 match file_descriptor.as_file_handle() {
503 Ok(FileHandle { file, writable }) => {
504 let io_result = maybe_sync_file(&file, *writable, File::sync_all);
505 this.try_unwrap_io_result(io_result)
507 Err(_) => this.handle_not_found(),
510 this.handle_not_found()
513 throw_unsup_format!("the {:#x} command is not supported for `fcntl`)", cmd);
517 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
518 let this = self.eval_context_mut();
520 this.check_no_isolation("close")?;
522 let fd = this.read_scalar(fd_op)?.to_i32()?;
524 if let Some(file_descriptor) = this.machine.file_handler.handles.remove(&fd) {
525 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
526 // We sync the file if it was opened in a mode different than read-only.
528 // `File::sync_all` does the checks that are done when closing a file. We do this to
529 // to handle possible errors correctly.
530 let result = this.try_unwrap_io_result(file.sync_all().map(|_| 0i32));
531 // Now we actually close the file.
533 // And return the result.
536 // We drop the file, this closes it but ignores any errors produced when closing
537 // it. This is done because `File::sync_all` cannot be done over files like
538 // `/dev/urandom` which are read-only. Check
539 // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439 for a deeper
545 this.handle_not_found()
554 ) -> InterpResult<'tcx, i64> {
555 let this = self.eval_context_mut();
557 this.check_no_isolation("read")?;
559 trace!("Reading from FD {}, size {}", fd, count);
561 // Check that the *entire* buffer is actually valid memory.
562 this.memory.check_ptr_access(
564 Size::from_bytes(count),
565 Align::from_bytes(1).unwrap(),
568 // We cap the number of read bytes to the largest value that we are able to fit in both the
569 // host's and target's `isize`. This saves us from having to handle overflows later.
570 let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
572 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
573 trace!("read: FD mapped to {:?}", file_descriptor);
574 // We want to read at most `count` bytes. We are sure that `count` is not negative
575 // because it was a target's `usize`. Also we are sure that its smaller than
576 // `usize::MAX` because it is a host's `isize`.
577 let mut bytes = vec![0; count as usize];
578 // `File::read` never returns a value larger than `count`,
579 // so this cannot fail.
580 let result = file_descriptor
582 .map(|c| i64::try_from(c).unwrap());
586 // If reading to `bytes` did not fail, we write those bytes to the buffer.
587 this.memory.write_bytes(buf, bytes)?;
591 this.set_last_error_from_io_error(e)?;
596 trace!("read: FD not found");
597 this.handle_not_found()
606 ) -> InterpResult<'tcx, i64> {
607 let this = self.eval_context_mut();
610 this.check_no_isolation("write")?;
613 // Check that the *entire* buffer is actually valid memory.
614 this.memory.check_ptr_access(
616 Size::from_bytes(count),
617 Align::from_bytes(1).unwrap(),
620 // We cap the number of written bytes to the largest value that we are able to fit in both the
621 // host's and target's `isize`. This saves us from having to handle overflows later.
622 let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
624 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
625 let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
626 let result = file_descriptor
628 .map(|c| i64::try_from(c).unwrap());
629 this.try_unwrap_io_result(result)
631 this.handle_not_found()
637 fd_op: OpTy<'tcx, Tag>,
638 offset_op: OpTy<'tcx, Tag>,
639 whence_op: OpTy<'tcx, Tag>,
640 ) -> InterpResult<'tcx, i64> {
641 let this = self.eval_context_mut();
643 this.check_no_isolation("lseek64")?;
645 let fd = this.read_scalar(fd_op)?.to_i32()?;
646 let offset = this.read_scalar(offset_op)?.to_i64()?;
647 let whence = this.read_scalar(whence_op)?.to_i32()?;
649 let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
650 SeekFrom::Start(u64::try_from(offset).unwrap())
651 } else if whence == this.eval_libc_i32("SEEK_CUR")? {
652 SeekFrom::Current(offset)
653 } else if whence == this.eval_libc_i32("SEEK_END")? {
654 SeekFrom::End(offset)
656 let einval = this.eval_libc("EINVAL")?;
657 this.set_last_error(einval)?;
661 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
662 let result = file_descriptor
664 .map(|offset| i64::try_from(offset).unwrap());
665 this.try_unwrap_io_result(result)
667 this.handle_not_found()
671 fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
672 let this = self.eval_context_mut();
674 this.check_no_isolation("unlink")?;
676 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
678 let result = remove_file(path).map(|_| 0);
679 this.try_unwrap_io_result(result)
684 target_op: OpTy<'tcx, Tag>,
685 linkpath_op: OpTy<'tcx, Tag>
686 ) -> InterpResult<'tcx, i32> {
688 fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
689 std::os::unix::fs::symlink(src, dst)
693 fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
694 use std::os::windows::fs;
696 fs::symlink_dir(src, dst)
698 fs::symlink_file(src, dst)
702 let this = self.eval_context_mut();
704 this.check_no_isolation("symlink")?;
706 let target = this.read_path_from_c_str(this.read_scalar(target_op)?.check_init()?)?;
707 let linkpath = this.read_path_from_c_str(this.read_scalar(linkpath_op)?.check_init()?)?;
709 let result = create_link(&target, &linkpath).map(|_| 0);
710 this.try_unwrap_io_result(result)
715 path_op: OpTy<'tcx, Tag>,
716 buf_op: OpTy<'tcx, Tag>,
717 ) -> InterpResult<'tcx, i32> {
718 let this = self.eval_context_mut();
719 this.assert_target_os("macos", "stat");
720 this.check_no_isolation("stat")?;
721 // `stat` always follows symlinks.
722 this.macos_stat_or_lstat(true, path_op, buf_op)
725 // `lstat` is used to get symlink metadata.
728 path_op: OpTy<'tcx, Tag>,
729 buf_op: OpTy<'tcx, Tag>,
730 ) -> InterpResult<'tcx, i32> {
731 let this = self.eval_context_mut();
732 this.assert_target_os("macos", "lstat");
733 this.check_no_isolation("lstat")?;
734 this.macos_stat_or_lstat(false, path_op, buf_op)
739 fd_op: OpTy<'tcx, Tag>,
740 buf_op: OpTy<'tcx, Tag>,
741 ) -> InterpResult<'tcx, i32> {
742 let this = self.eval_context_mut();
744 this.assert_target_os("macos", "fstat");
745 this.check_no_isolation("fstat")?;
747 let fd = this.read_scalar(fd_op)?.to_i32()?;
749 let metadata = match FileMetadata::from_fd(this, fd)? {
750 Some(metadata) => metadata,
751 None => return Ok(-1),
753 this.macos_stat_write_buf(metadata, buf_op)
758 dirfd_op: OpTy<'tcx, Tag>, // Should be an `int`
759 pathname_op: OpTy<'tcx, Tag>, // Should be a `const char *`
760 flags_op: OpTy<'tcx, Tag>, // Should be an `int`
761 _mask_op: OpTy<'tcx, Tag>, // Should be an `unsigned int`
762 statxbuf_op: OpTy<'tcx, Tag>, // Should be a `struct statx *`
763 ) -> InterpResult<'tcx, i32> {
764 let this = self.eval_context_mut();
766 this.assert_target_os("linux", "statx");
767 this.check_no_isolation("statx")?;
769 let statxbuf_scalar = this.read_scalar(statxbuf_op)?.check_init()?;
770 let pathname_scalar = this.read_scalar(pathname_op)?.check_init()?;
772 // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
773 if this.is_null(statxbuf_scalar)? || this.is_null(pathname_scalar)? {
774 let efault = this.eval_libc("EFAULT")?;
775 this.set_last_error(efault)?;
779 // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
780 // proper `MemPlace` and then write the results of this function to it. However, the
781 // `syscall` function is untyped. This means that all the `statx` parameters are provided
782 // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
783 // `statxbuf_op` by using the `libc::statx` struct type.
784 let statxbuf_place = {
785 // FIXME: This long path is required because `libc::statx` is an struct and also a
786 // function and `resolve_path` is returning the latter.
788 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])
789 .ty(*this.tcx, ty::ParamEnv::reveal_all());
790 let statxbuf_ty = this.tcx.mk_mut_ptr(statx_ty);
791 let statxbuf_layout = this.layout_of(statxbuf_ty)?;
792 let statxbuf_imm = ImmTy::from_scalar(statxbuf_scalar, statxbuf_layout);
793 this.ref_to_mplace(statxbuf_imm)?
796 let path = this.read_path_from_c_str(pathname_scalar)?.into_owned();
797 // `flags` should be a `c_int` but the `syscall` function provides an `isize`.
799 this.read_scalar(flags_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
800 err_unsup_format!("failed to convert pointer sized operand to integer: {}", e)
802 let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
803 // `dirfd` should be a `c_int` but the `syscall` function provides an `isize`.
805 this.read_scalar(dirfd_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
806 err_unsup_format!("failed to convert pointer sized operand to integer: {}", e)
809 // * interpreting `path` as an absolute directory,
810 // * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
811 // * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
813 // Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
814 // found this error, please open an issue reporting it.
816 path.is_absolute() ||
817 dirfd == this.eval_libc_i32("AT_FDCWD")? ||
818 (path.as_os_str().is_empty() && empty_path_flag)
821 "using statx is only supported with absolute paths, relative paths with the file \
822 descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
827 // the `_mask_op` paramter specifies the file information that the caller requested.
828 // However `statx` is allowed to return information that was not requested or to not
829 // return information that was requested. This `mask` represents the information we can
830 // actually provide for any target.
832 this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
834 // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
836 let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
838 // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
839 // represented by dirfd, whether it's a directory or otherwise.
840 let metadata = if path.as_os_str().is_empty() && empty_path_flag {
841 FileMetadata::from_fd(this, dirfd)?
843 FileMetadata::from_path(this, &path, follow_symlink)?
845 let metadata = match metadata {
846 Some(metadata) => metadata,
847 None => return Ok(-1),
850 // The `mode` field specifies the type of the file and the permissions over the file for
851 // the owner, its group and other users. Given that we can only provide the file type
852 // without using platform specific methods, we only set the bits corresponding to the file
853 // type. This should be an `__u16` but `libc` provides its values as `u32`.
854 let mode: u16 = metadata
858 .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
860 // We need to set the corresponding bits of `mask` if the access, creation and modification
861 // times were available. Otherwise we let them be zero.
862 let (access_sec, access_nsec) = metadata.accessed.map(|tup| {
863 mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
864 InterpResult::Ok(tup)
865 }).unwrap_or(Ok((0, 0)))?;
867 let (created_sec, created_nsec) = metadata.created.map(|tup| {
868 mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
869 InterpResult::Ok(tup)
870 }).unwrap_or(Ok((0, 0)))?;
872 let (modified_sec, modified_nsec) = metadata.modified.map(|tup| {
873 mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
874 InterpResult::Ok(tup)
875 }).unwrap_or(Ok((0, 0)))?;
877 let __u32_layout = this.libc_ty_layout("__u32")?;
878 let __u64_layout = this.libc_ty_layout("__u64")?;
879 let __u16_layout = this.libc_ty_layout("__u16")?;
881 // Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
882 // zero for the unavailable fields.
884 immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
885 immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
886 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
887 immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
888 immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
889 immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
890 immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
891 immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
892 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
893 immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
894 immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
895 immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
896 immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
897 immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
898 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
899 immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
900 immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
901 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
902 immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
903 immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
904 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
905 immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
906 immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
907 immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
908 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
909 immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
910 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
911 immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
914 this.write_packed_immediates(statxbuf_place, &imms)?;
921 oldpath_op: OpTy<'tcx, Tag>,
922 newpath_op: OpTy<'tcx, Tag>,
923 ) -> InterpResult<'tcx, i32> {
924 let this = self.eval_context_mut();
926 this.check_no_isolation("rename")?;
928 let oldpath_scalar = this.read_scalar(oldpath_op)?.check_init()?;
929 let newpath_scalar = this.read_scalar(newpath_op)?.check_init()?;
931 if this.is_null(oldpath_scalar)? || this.is_null(newpath_scalar)? {
932 let efault = this.eval_libc("EFAULT")?;
933 this.set_last_error(efault)?;
937 let oldpath = this.read_path_from_c_str(oldpath_scalar)?;
938 let newpath = this.read_path_from_c_str(newpath_scalar)?;
940 let result = rename(oldpath, newpath).map(|_| 0);
942 this.try_unwrap_io_result(result)
947 path_op: OpTy<'tcx, Tag>,
948 mode_op: OpTy<'tcx, Tag>,
949 ) -> InterpResult<'tcx, i32> {
950 let this = self.eval_context_mut();
952 this.check_no_isolation("mkdir")?;
954 #[cfg_attr(not(unix), allow(unused_variables))]
955 let mode = if this.tcx.sess.target.target.target_os == "macos" {
956 u32::from(this.read_scalar(mode_op)?.check_init()?.to_u16()?)
958 this.read_scalar(mode_op)?.to_u32()?
961 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
963 #[cfg_attr(not(unix), allow(unused_mut))]
964 let mut builder = DirBuilder::new();
966 // If the host supports it, forward on the mode of the directory
967 // (i.e. permission bits and the sticky bit)
970 use std::os::unix::fs::DirBuilderExt;
971 builder.mode(mode.into());
974 let result = builder.create(path).map(|_| 0i32);
976 this.try_unwrap_io_result(result)
981 path_op: OpTy<'tcx, Tag>,
982 ) -> InterpResult<'tcx, i32> {
983 let this = self.eval_context_mut();
985 this.check_no_isolation("rmdir")?;
987 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
989 let result = remove_dir(path).map(|_| 0i32);
991 this.try_unwrap_io_result(result)
994 fn opendir(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
995 let this = self.eval_context_mut();
997 this.check_no_isolation("opendir")?;
999 let name = this.read_path_from_c_str(this.read_scalar(name_op)?.check_init()?)?;
1001 let result = read_dir(name);
1005 let id = this.machine.dir_handler.insert_new(dir_iter);
1007 // The libc API for opendir says that this method returns a pointer to an opaque
1008 // structure, but we are returning an ID number. Thus, pass it as a scalar of
1010 Ok(Scalar::from_machine_usize(id, this))
1013 this.set_last_error_from_io_error(e)?;
1014 Ok(Scalar::null_ptr(this))
1019 fn linux_readdir64_r(
1021 dirp_op: OpTy<'tcx, Tag>,
1022 entry_op: OpTy<'tcx, Tag>,
1023 result_op: OpTy<'tcx, Tag>,
1024 ) -> InterpResult<'tcx, i32> {
1025 let this = self.eval_context_mut();
1027 this.assert_target_os("linux", "readdir64_r");
1028 this.check_no_isolation("readdir64_r")?;
1030 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1032 let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1033 err_unsup_format!("the DIR pointer passed to readdir64_r did not come from opendir")
1035 match dir_iter.next() {
1036 Some(Ok(dir_entry)) => {
1037 // Write into entry, write pointer to result, return 0 on success.
1038 // The name is written with write_os_str_to_c_str, while the rest of the
1039 // dirent64 struct is written using write_packed_immediates.
1042 // pub struct dirent64 {
1043 // pub d_ino: ino64_t,
1044 // pub d_off: off64_t,
1045 // pub d_reclen: c_ushort,
1046 // pub d_type: c_uchar,
1047 // pub d_name: [c_char; 256],
1050 let entry_place = this.deref_operand(entry_op)?;
1051 let name_place = this.mplace_field(entry_place, 4)?;
1053 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1054 let (name_fits, _) = this.write_os_str_to_c_str(
1057 name_place.layout.size.bytes(),
1060 throw_unsup_format!("a directory entry had a name too large to fit in libc::dirent64");
1063 let entry_place = this.deref_operand(entry_op)?;
1064 let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
1065 let off64_t_layout = this.libc_ty_layout("off64_t")?;
1066 let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
1067 let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
1069 // If the host is a Unix system, fill in the inode number with its real value.
1070 // If not, use 0 as a fallback value.
1072 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1076 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1079 immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
1080 immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
1081 immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1082 immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
1084 this.write_packed_immediates(entry_place, &imms)?;
1086 let result_place = this.deref_operand(result_op)?;
1087 this.write_scalar(this.read_scalar(entry_op)?, result_place.into())?;
1092 // end of stream: return 0, assign *result=NULL
1093 this.write_null(this.deref_operand(result_op)?.into())?;
1096 Some(Err(e)) => match e.raw_os_error() {
1097 // return positive error number on error
1098 Some(error) => Ok(error),
1100 throw_unsup_format!("the error {} couldn't be converted to a return value", e)
1108 dirp_op: OpTy<'tcx, Tag>,
1109 entry_op: OpTy<'tcx, Tag>,
1110 result_op: OpTy<'tcx, Tag>,
1111 ) -> InterpResult<'tcx, i32> {
1112 let this = self.eval_context_mut();
1114 this.assert_target_os("macos", "readdir_r");
1115 this.check_no_isolation("readdir_r")?;
1117 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1119 let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
1120 err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
1122 match dir_iter.next() {
1123 Some(Ok(dir_entry)) => {
1124 // Write into entry, write pointer to result, return 0 on success.
1125 // The name is written with write_os_str_to_c_str, while the rest of the
1126 // dirent struct is written using write_packed_Immediates.
1129 // pub struct dirent {
1131 // pub d_seekoff: u64,
1132 // pub d_reclen: u16,
1133 // pub d_namlen: u16,
1135 // pub d_name: [c_char; 1024],
1138 let entry_place = this.deref_operand(entry_op)?;
1139 let name_place = this.mplace_field(entry_place, 5)?;
1141 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1142 let (name_fits, file_name_len) = this.write_os_str_to_c_str(
1145 name_place.layout.size.bytes(),
1148 throw_unsup_format!("a directory entry had a name too large to fit in libc::dirent");
1151 let entry_place = this.deref_operand(entry_op)?;
1152 let ino_t_layout = this.libc_ty_layout("ino_t")?;
1153 let off_t_layout = this.libc_ty_layout("off_t")?;
1154 let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
1155 let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
1157 // If the host is a Unix system, fill in the inode number with its real value.
1158 // If not, use 0 as a fallback value.
1160 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1164 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1167 immty_from_uint_checked(ino, ino_t_layout)?, // d_ino
1168 immty_from_uint_checked(0u128, off_t_layout)?, // d_seekoff
1169 immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1170 immty_from_uint_checked(file_name_len, c_ushort_layout)?, // d_namlen
1171 immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
1173 this.write_packed_immediates(entry_place, &imms)?;
1175 let result_place = this.deref_operand(result_op)?;
1176 this.write_scalar(this.read_scalar(entry_op)?, result_place.into())?;
1181 // end of stream: return 0, assign *result=NULL
1182 this.write_null(this.deref_operand(result_op)?.into())?;
1185 Some(Err(e)) => match e.raw_os_error() {
1186 // return positive error number on error
1187 Some(error) => Ok(error),
1189 throw_unsup_format!("the error {} couldn't be converted to a return value", e)
1195 fn closedir(&mut self, dirp_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1196 let this = self.eval_context_mut();
1198 this.check_no_isolation("closedir")?;
1200 let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1202 if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
1206 this.handle_not_found()
1212 fd_op: OpTy<'tcx, Tag>,
1213 length_op: OpTy<'tcx, Tag>,
1214 ) -> InterpResult<'tcx, i32> {
1215 let this = self.eval_context_mut();
1217 this.check_no_isolation("ftruncate64")?;
1219 let fd = this.read_scalar(fd_op)?.to_i32()?;
1220 let length = this.read_scalar(length_op)?.to_i64()?;
1221 if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
1222 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1224 if let Ok(length) = length.try_into() {
1225 let result = file.set_len(length);
1226 this.try_unwrap_io_result(result.map(|_| 0i32))
1228 let einval = this.eval_libc("EINVAL")?;
1229 this.set_last_error(einval)?;
1233 // The file is not writable
1234 let einval = this.eval_libc("EINVAL")?;
1235 this.set_last_error(einval)?;
1239 this.handle_not_found()
1243 fn fsync(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1244 // On macOS, `fsync` (unlike `fcntl(F_FULLFSYNC)`) does not wait for the
1245 // underlying disk to finish writing. In the interest of host compatibility,
1246 // we conservatively implement this with `sync_all`, which
1247 // *does* wait for the disk.
1249 let this = self.eval_context_mut();
1251 this.check_no_isolation("fsync")?;
1253 let fd = this.read_scalar(fd_op)?.to_i32()?;
1254 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1255 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1256 let io_result = maybe_sync_file(&file, *writable, File::sync_all);
1257 this.try_unwrap_io_result(io_result)
1259 this.handle_not_found()
1263 fn fdatasync(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1264 let this = self.eval_context_mut();
1266 this.check_no_isolation("fdatasync")?;
1268 let fd = this.read_scalar(fd_op)?.to_i32()?;
1269 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1270 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1271 let io_result = maybe_sync_file(&file, *writable, File::sync_data);
1272 this.try_unwrap_io_result(io_result)
1274 this.handle_not_found()
1280 fd_op: OpTy<'tcx, Tag>,
1281 offset_op: OpTy<'tcx, Tag>,
1282 nbytes_op: OpTy<'tcx, Tag>,
1283 flags_op: OpTy<'tcx, Tag>,
1284 ) -> InterpResult<'tcx, i32> {
1285 let this = self.eval_context_mut();
1287 this.check_no_isolation("sync_file_range")?;
1289 let fd = this.read_scalar(fd_op)?.to_i32()?;
1290 let offset = this.read_scalar(offset_op)?.to_i64()?;
1291 let nbytes = this.read_scalar(nbytes_op)?.to_i64()?;
1292 let flags = this.read_scalar(flags_op)?.to_i32()?;
1294 if offset < 0 || nbytes < 0 {
1295 let einval = this.eval_libc("EINVAL")?;
1296 this.set_last_error(einval)?;
1299 let allowed_flags = this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_BEFORE")?
1300 | this.eval_libc_i32("SYNC_FILE_RANGE_WRITE")?
1301 | this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_AFTER")?;
1302 if flags & allowed_flags != flags {
1303 let einval = this.eval_libc("EINVAL")?;
1304 this.set_last_error(einval)?;
1308 if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
1309 let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
1310 let io_result = maybe_sync_file(&file, *writable, File::sync_data);
1311 this.try_unwrap_io_result(io_result)
1313 this.handle_not_found()
1318 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
1319 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
1321 fn extract_sec_and_nsec<'tcx>(
1322 time: std::io::Result<SystemTime>
1323 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
1324 time.ok().map(|time| {
1325 let duration = system_time_to_duration(&time)?;
1326 Ok((duration.as_secs(), duration.subsec_nanos()))
1330 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
1332 struct FileMetadata {
1335 created: Option<(u64, u32)>,
1336 accessed: Option<(u64, u32)>,
1337 modified: Option<(u64, u32)>,
1341 fn from_path<'tcx, 'mir>(
1342 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1344 follow_symlink: bool
1345 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1346 let metadata = if follow_symlink {
1347 std::fs::metadata(path)
1349 std::fs::symlink_metadata(path)
1352 FileMetadata::from_meta(ecx, metadata)
1355 fn from_fd<'tcx, 'mir>(
1356 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1358 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1359 let option = ecx.machine.file_handler.handles.get(&fd);
1360 let file = match option {
1361 Some(file_descriptor) => {
1362 let FileHandle { file, writable: _ } = file_descriptor.as_file_handle()?;
1365 None => return ecx.handle_not_found().map(|_: i32| None),
1367 let metadata = file.metadata();
1369 FileMetadata::from_meta(ecx, metadata)
1372 fn from_meta<'tcx, 'mir>(
1373 ecx: &mut MiriEvalContext<'mir, 'tcx>,
1374 metadata: Result<std::fs::Metadata, std::io::Error>,
1375 ) -> InterpResult<'tcx, Option<FileMetadata>> {
1376 let metadata = match metadata {
1377 Ok(metadata) => metadata,
1379 ecx.set_last_error_from_io_error(e)?;
1384 let file_type = metadata.file_type();
1386 let mode_name = if file_type.is_file() {
1388 } else if file_type.is_dir() {
1394 let mode = ecx.eval_libc(mode_name)?;
1396 let size = metadata.len();
1398 let created = extract_sec_and_nsec(metadata.created())?;
1399 let accessed = extract_sec_and_nsec(metadata.accessed())?;
1400 let modified = extract_sec_and_nsec(metadata.modified())?;
1402 // FIXME: Provide more fields using platform specific methods.
1403 Ok(Some(FileMetadata { mode, size, created, accessed, modified }))