]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
Fix fsync shim for Windows hosts with RO files
[rust.git] / src / shims / fs.rs
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::{Read, Seek, SeekFrom, Write};
5 use std::path::Path;
6 use std::time::SystemTime;
7
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_target::abi::{Align, LayoutOf, Size};
10
11 use crate::stacked_borrows::Tag;
12 use crate::*;
13 use helpers::{check_arg_count, immty_from_int_checked, immty_from_uint_checked};
14 use shims::time::system_time_to_duration;
15
16 #[derive(Debug)]
17 pub struct FileHandle {
18     file: File,
19     writable: bool,
20 }
21
22 #[derive(Debug, Default)]
23 pub struct FileHandler {
24     handles: BTreeMap<i32, FileHandle>,
25 }
26
27 // fd numbers 0, 1, and 2 are reserved for stdin, stdout, and stderr
28 const MIN_NORMAL_FILE_FD: i32 = 3;
29
30 impl FileHandler {
31     fn insert_fd(&mut self, file_handle: FileHandle) -> i32 {
32         self.insert_fd_with_min_fd(file_handle, 0)
33     }
34
35     fn insert_fd_with_min_fd(&mut self, file_handle: FileHandle, min_fd: i32) -> i32 {
36         let min_fd = std::cmp::max(min_fd, MIN_NORMAL_FILE_FD);
37
38         // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
39         // between used FDs, the find_map combinator will return it. If the first such unused FD
40         // is after all other used FDs, the find_map combinator will return None, and we will use
41         // the FD following the greatest FD thus far.
42         let candidate_new_fd = self
43             .handles
44             .range(min_fd..)
45             .zip(min_fd..)
46             .find_map(|((fd, _fh), counter)| {
47                 if *fd != counter {
48                     // There was a gap in the fds stored, return the first unused one
49                     // (note that this relies on BTreeMap iterating in key order)
50                     Some(counter)
51                 } else {
52                     // This fd is used, keep going
53                     None
54                 }
55             });
56         let new_fd = candidate_new_fd.unwrap_or_else(|| {
57             // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
58             // maximum fd in the map
59             self.handles.last_key_value().map(|(fd, _)| fd.checked_add(1).unwrap()).unwrap_or(min_fd)
60         });
61
62         self.handles.insert(new_fd, file_handle).unwrap_none();
63         new_fd
64     }
65 }
66
67 impl<'mir, 'tcx: 'mir> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
68 trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
69     /// Emulate `stat` or `lstat` on `macos`. This function is not intended to be
70     /// called directly from `emulate_foreign_item_by_name`, so it does not check if isolation is
71     /// disabled or if the target OS is the correct one. Please use `macos_stat` or
72     /// `macos_lstat` instead.
73     fn macos_stat_or_lstat(
74         &mut self,
75         follow_symlink: bool,
76         path_op: OpTy<'tcx, Tag>,
77         buf_op: OpTy<'tcx, Tag>,
78     ) -> InterpResult<'tcx, i32> {
79         let this = self.eval_context_mut();
80
81         let path_scalar = this.read_scalar(path_op)?.not_undef()?;
82         let path = this.read_path_from_c_str(path_scalar)?.into_owned();
83
84         let metadata = match FileMetadata::from_path(this, &path, follow_symlink)? {
85             Some(metadata) => metadata,
86             None => return Ok(-1),
87         };
88         this.macos_stat_write_buf(metadata, buf_op)
89     }
90
91     fn macos_stat_write_buf(
92         &mut self,
93         metadata: FileMetadata,
94         buf_op: OpTy<'tcx, Tag>,
95     ) -> InterpResult<'tcx, i32> {
96         let this = self.eval_context_mut();
97
98         let mode: u16 = metadata.mode.to_u16()?;
99
100         let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
101         let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
102         let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
103
104         let dev_t_layout = this.libc_ty_layout("dev_t")?;
105         let mode_t_layout = this.libc_ty_layout("mode_t")?;
106         let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
107         let ino_t_layout = this.libc_ty_layout("ino_t")?;
108         let uid_t_layout = this.libc_ty_layout("uid_t")?;
109         let gid_t_layout = this.libc_ty_layout("gid_t")?;
110         let time_t_layout = this.libc_ty_layout("time_t")?;
111         let long_layout = this.libc_ty_layout("c_long")?;
112         let off_t_layout = this.libc_ty_layout("off_t")?;
113         let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
114         let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
115         let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
116
117         let imms = [
118             immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
119             immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
120             immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
121             immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
122             immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
123             immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
124             immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
125             immty_from_uint_checked(0u128, uint32_t_layout)?, // padding
126             immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
127             immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
128             immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
129             immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
130             immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
131             immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
132             immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
133             immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
134             immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
135             immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
136             immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
137             immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
138             immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
139         ];
140
141         let buf = this.deref_operand(buf_op)?;
142         this.write_packed_immediates(buf, &imms)?;
143
144         Ok(0)
145     }
146
147     /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
148     /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
149     /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
150     /// types (like `read`, that returns an `i64`).
151     fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
152         let this = self.eval_context_mut();
153         let ebadf = this.eval_libc("EBADF")?;
154         this.set_last_error(ebadf)?;
155         Ok((-1).into())
156     }
157
158     fn file_type_to_d_type(&mut self, file_type: std::io::Result<FileType>) -> InterpResult<'tcx, i32> {
159         let this = self.eval_context_mut();
160         match file_type {
161             Ok(file_type) => {
162                 if file_type.is_dir() {
163                     Ok(this.eval_libc("DT_DIR")?.to_u8()?.into())
164                 } else if file_type.is_file() {
165                     Ok(this.eval_libc("DT_REG")?.to_u8()?.into())
166                 } else if file_type.is_symlink() {
167                     Ok(this.eval_libc("DT_LNK")?.to_u8()?.into())
168                 } else {
169                     // Certain file types are only supported when the host is a Unix system.
170                     // (i.e. devices and sockets) If it is, check those cases, if not, fall back to
171                     // DT_UNKNOWN sooner.
172
173                     #[cfg(unix)]
174                     {
175                         use std::os::unix::fs::FileTypeExt;
176                         if file_type.is_block_device() {
177                             Ok(this.eval_libc("DT_BLK")?.to_u8()?.into())
178                         } else if file_type.is_char_device() {
179                             Ok(this.eval_libc("DT_CHR")?.to_u8()?.into())
180                         } else if file_type.is_fifo() {
181                             Ok(this.eval_libc("DT_FIFO")?.to_u8()?.into())
182                         } else if file_type.is_socket() {
183                             Ok(this.eval_libc("DT_SOCK")?.to_u8()?.into())
184                         } else {
185                             Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
186                         }
187                     }
188                     #[cfg(not(unix))]
189                     Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
190                 }
191             }
192             Err(e) => return match e.raw_os_error() {
193                 Some(error) => Ok(error),
194                 None => throw_unsup_format!("the error {} couldn't be converted to a return value", e),
195             }
196         }
197     }
198 }
199
200 #[derive(Debug)]
201 pub struct DirHandler {
202     /// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
203     /// and closedir.
204     ///
205     /// When opendir is called, a directory iterator is created on the host for the target
206     /// directory, and an entry is stored in this hash map, indexed by an ID which represents
207     /// the directory stream. When readdir is called, the directory stream ID is used to look up
208     /// the corresponding ReadDir iterator from this map, and information from the next
209     /// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
210     /// the map.
211     streams: FxHashMap<u64, ReadDir>,
212     /// ID number to be used by the next call to opendir
213     next_id: u64,
214 }
215
216 impl DirHandler {
217     fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
218         let id = self.next_id;
219         self.next_id += 1;
220         self.streams.insert(id, read_dir).unwrap_none();
221         id
222     }
223 }
224
225 impl Default for DirHandler {
226     fn default() -> DirHandler {
227         DirHandler {
228             streams: FxHashMap::default(),
229             // Skip 0 as an ID, because it looks like a null pointer to libc
230             next_id: 1,
231         }
232     }
233 }
234
235 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
236 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
237     fn open(
238         &mut self,
239         path_op: OpTy<'tcx, Tag>,
240         flag_op: OpTy<'tcx, Tag>,
241         mode_op: OpTy<'tcx, Tag>,
242     ) -> InterpResult<'tcx, i32> {
243         let this = self.eval_context_mut();
244
245         this.check_no_isolation("open")?;
246
247         let flag = this.read_scalar(flag_op)?.to_i32()?;
248
249         // Get the mode.  On macOS, the argument type `mode_t` is actually `u16`, but
250         // C integer promotion rules mean that on the ABI level, it gets passed as `u32`
251         // (see https://github.com/rust-lang/rust/issues/71915).
252         let mode = this.read_scalar(mode_op)?.to_u32()?;
253         if mode != 0o666 {
254             throw_unsup_format!("non-default mode 0o{:o} is not supported", mode);
255         }
256
257         let mut options = OpenOptions::new();
258
259         let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
260         let o_wronly = this.eval_libc_i32("O_WRONLY")?;
261         let o_rdwr = this.eval_libc_i32("O_RDWR")?;
262         // The first two bits of the flag correspond to the access mode in linux, macOS and
263         // windows. We need to check that in fact the access mode flags for the current target
264         // only use these two bits, otherwise we are in an unsupported target and should error.
265         if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
266             throw_unsup_format!("access mode flags on this target are unsupported");
267         }
268         let mut writable = true;
269
270         // Now we check the access mode
271         let access_mode = flag & 0b11;
272
273         if access_mode == o_rdonly {
274             writable = false;
275             options.read(true);
276         } else if access_mode == o_wronly {
277             options.write(true);
278         } else if access_mode == o_rdwr {
279             options.read(true).write(true);
280         } else {
281             throw_unsup_format!("unsupported access mode {:#x}", access_mode);
282         }
283         // We need to check that there aren't unsupported options in `flag`. For this we try to
284         // reproduce the content of `flag` in the `mirror` variable using only the supported
285         // options.
286         let mut mirror = access_mode;
287
288         let o_append = this.eval_libc_i32("O_APPEND")?;
289         if flag & o_append != 0 {
290             options.append(true);
291             mirror |= o_append;
292         }
293         let o_trunc = this.eval_libc_i32("O_TRUNC")?;
294         if flag & o_trunc != 0 {
295             options.truncate(true);
296             mirror |= o_trunc;
297         }
298         let o_creat = this.eval_libc_i32("O_CREAT")?;
299         if flag & o_creat != 0 {
300             mirror |= o_creat;
301
302             let o_excl = this.eval_libc_i32("O_EXCL")?;
303             if flag & o_excl != 0 {
304                 mirror |= o_excl;
305                 options.create_new(true);
306             } else {
307                 options.create(true);
308             }
309         }
310         let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
311         if flag & o_cloexec != 0 {
312             // We do not need to do anything for this flag because `std` already sets it.
313             // (Technically we do not support *not* setting this flag, but we ignore that.)
314             mirror |= o_cloexec;
315         }
316         // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
317         // then we throw an error.
318         if flag != mirror {
319             throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
320         }
321
322         let path = this.read_path_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
323
324         let fd = options.open(&path).map(|file| {
325             let fh = &mut this.machine.file_handler;
326             fh.insert_fd(FileHandle { file, writable })
327         });
328
329         this.try_unwrap_io_result(fd)
330     }
331
332     fn fcntl(
333         &mut self,
334         args: &[OpTy<'tcx, Tag>],
335     ) -> InterpResult<'tcx, i32> {
336         let this = self.eval_context_mut();
337
338         this.check_no_isolation("fcntl")?;
339
340         if args.len() < 2 {
341             throw_ub_format!("incorrect number of arguments for fcntl: got {}, expected at least 2", args.len());
342         }
343         let fd = this.read_scalar(args[0])?.to_i32()?;
344         let cmd = this.read_scalar(args[1])?.to_i32()?;
345         // We only support getting the flags for a descriptor.
346         if cmd == this.eval_libc_i32("F_GETFD")? {
347             // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
348             // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
349             // always sets this flag when opening a file. However we still need to check that the
350             // file itself is open.
351             let &[_, _] = check_arg_count(args)?;
352             if this.machine.file_handler.handles.contains_key(&fd) {
353                 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
354             } else {
355                 this.handle_not_found()
356             }
357         } else if cmd == this.eval_libc_i32("F_DUPFD")?
358             || cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
359         {
360             // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
361             // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
362             // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
363             // thus they can share the same implementation here.
364             let &[_, _, start] = check_arg_count(args)?;
365             let start = this.read_scalar(start)?.to_i32()?;
366             if fd < MIN_NORMAL_FILE_FD {
367                 throw_unsup_format!("duplicating file descriptors for stdin, stdout, or stderr is not supported")
368             }
369             let fh = &mut this.machine.file_handler;
370             let (file_result, writable) = match fh.handles.get(&fd) {
371                 Some(FileHandle { file, writable }) => (file.try_clone(), *writable),
372                 None => return this.handle_not_found(),
373             };
374             let fd_result = file_result.map(|duplicated| {
375                 fh.insert_fd_with_min_fd(FileHandle { file: duplicated, writable }, start)
376             });
377             this.try_unwrap_io_result(fd_result)
378         } else if this.tcx.sess.target.target.target_os == "macos"
379             && cmd == this.eval_libc_i32("F_FULLFSYNC")?
380         {
381             let &[_, _] = check_arg_count(args)?;
382             if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
383                 let result = file.sync_all();
384                 this.try_unwrap_io_result(result.map(|_| 0i32))
385             } else {
386                 this.handle_not_found()
387             }
388         } else {
389             throw_unsup_format!("the {:#x} command is not supported for `fcntl`)", cmd);
390         }
391     }
392
393     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
394         let this = self.eval_context_mut();
395
396         this.check_no_isolation("close")?;
397
398         let fd = this.read_scalar(fd_op)?.to_i32()?;
399
400         if let Some(FileHandle { file, writable }) = this.machine.file_handler.handles.remove(&fd) {
401             // We sync the file if it was opened in a mode different than read-only.
402             if writable {
403                 // `File::sync_all` does the checks that are done when closing a file. We do this to
404                 // to handle possible errors correctly.
405                 let result = this.try_unwrap_io_result(file.sync_all().map(|_| 0i32));
406                 // Now we actually close the file.
407                 drop(file);
408                 // And return the result.
409                 result
410             } else {
411                 // We drop the file, this closes it but ignores any errors produced when closing
412                 // it. This is done because `File::sync_all` cannot be done over files like
413                 // `/dev/urandom` which are read-only. Check
414                 // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439 for a deeper
415                 // discussion.
416                 drop(file);
417                 Ok(0)
418             }
419         } else {
420             this.handle_not_found()
421         }
422     }
423
424     fn read(
425         &mut self,
426         fd_op: OpTy<'tcx, Tag>,
427         buf_op: OpTy<'tcx, Tag>,
428         count_op: OpTy<'tcx, Tag>,
429     ) -> InterpResult<'tcx, i64> {
430         let this = self.eval_context_mut();
431
432         this.check_no_isolation("read")?;
433
434         let fd = this.read_scalar(fd_op)?.to_i32()?;
435         let buf = this.read_scalar(buf_op)?.not_undef()?;
436         let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
437
438         // Check that the *entire* buffer is actually valid memory.
439         this.memory.check_ptr_access(
440             buf,
441             Size::from_bytes(count),
442             Align::from_bytes(1).unwrap(),
443         )?;
444
445         // We cap the number of read bytes to the largest value that we are able to fit in both the
446         // host's and target's `isize`. This saves us from having to handle overflows later.
447         let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
448
449         if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
450             // This can never fail because `count` was capped to be smaller than
451             // `isize::MAX`.
452             let count = isize::try_from(count).unwrap();
453             // We want to read at most `count` bytes. We are sure that `count` is not negative
454             // because it was a target's `usize`. Also we are sure that its smaller than
455             // `usize::MAX` because it is a host's `isize`.
456             let mut bytes = vec![0; count as usize];
457             let result = file
458                 .read(&mut bytes)
459                 // `File::read` never returns a value larger than `count`, so this cannot fail.
460                 .map(|c| i64::try_from(c).unwrap());
461
462             match result {
463                 Ok(read_bytes) => {
464                     // If reading to `bytes` did not fail, we write those bytes to the buffer.
465                     this.memory.write_bytes(buf, bytes)?;
466                     Ok(read_bytes)
467                 }
468                 Err(e) => {
469                     this.set_last_error_from_io_error(e)?;
470                     Ok(-1)
471                 }
472             }
473         } else {
474             this.handle_not_found()
475         }
476     }
477
478     fn write(
479         &mut self,
480         fd_op: OpTy<'tcx, Tag>,
481         buf_op: OpTy<'tcx, Tag>,
482         count_op: OpTy<'tcx, Tag>,
483     ) -> InterpResult<'tcx, i64> {
484         let this = self.eval_context_mut();
485
486         this.check_no_isolation("write")?;
487
488         let fd = this.read_scalar(fd_op)?.to_i32()?;
489         let buf = this.read_scalar(buf_op)?.not_undef()?;
490         let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
491
492         // Check that the *entire* buffer is actually valid memory.
493         this.memory.check_ptr_access(
494             buf,
495             Size::from_bytes(count),
496             Align::from_bytes(1).unwrap(),
497         )?;
498
499         // We cap the number of written bytes to the largest value that we are able to fit in both the
500         // host's and target's `isize`. This saves us from having to handle overflows later.
501         let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
502
503         if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
504             let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
505             let result = file.write(&bytes).map(|c| i64::try_from(c).unwrap());
506             this.try_unwrap_io_result(result)
507         } else {
508             this.handle_not_found()
509         }
510     }
511
512     fn lseek64(
513         &mut self,
514         fd_op: OpTy<'tcx, Tag>,
515         offset_op: OpTy<'tcx, Tag>,
516         whence_op: OpTy<'tcx, Tag>,
517     ) -> InterpResult<'tcx, i64> {
518         let this = self.eval_context_mut();
519
520         this.check_no_isolation("lseek64")?;
521
522         let fd = this.read_scalar(fd_op)?.to_i32()?;
523         let offset = this.read_scalar(offset_op)?.to_i64()?;
524         let whence = this.read_scalar(whence_op)?.to_i32()?;
525
526         let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
527             SeekFrom::Start(u64::try_from(offset).unwrap())
528         } else if whence == this.eval_libc_i32("SEEK_CUR")? {
529             SeekFrom::Current(offset)
530         } else if whence == this.eval_libc_i32("SEEK_END")? {
531             SeekFrom::End(offset)
532         } else {
533             let einval = this.eval_libc("EINVAL")?;
534             this.set_last_error(einval)?;
535             return Ok(-1);
536         };
537
538         if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
539             let result = file.seek(seek_from).map(|offset| i64::try_from(offset).unwrap());
540             this.try_unwrap_io_result(result)
541         } else {
542             this.handle_not_found()
543         }
544     }
545
546     fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
547         let this = self.eval_context_mut();
548
549         this.check_no_isolation("unlink")?;
550
551         let path = this.read_path_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
552
553         let result = remove_file(path).map(|_| 0);
554         this.try_unwrap_io_result(result)
555     }
556
557     fn symlink(
558         &mut self,
559         target_op: OpTy<'tcx, Tag>,
560         linkpath_op: OpTy<'tcx, Tag>
561     ) -> InterpResult<'tcx, i32> {
562         #[cfg(unix)]
563         fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
564             std::os::unix::fs::symlink(src, dst)
565         }
566
567         #[cfg(windows)]
568         fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
569             use std::os::windows::fs;
570             if src.is_dir() {
571                 fs::symlink_dir(src, dst)
572             } else {
573                 fs::symlink_file(src, dst)
574             }
575         }
576
577         let this = self.eval_context_mut();
578
579         this.check_no_isolation("symlink")?;
580
581         let target = this.read_path_from_c_str(this.read_scalar(target_op)?.not_undef()?)?;
582         let linkpath = this.read_path_from_c_str(this.read_scalar(linkpath_op)?.not_undef()?)?;
583
584         let result = create_link(&target, &linkpath).map(|_| 0);
585         this.try_unwrap_io_result(result)
586     }
587
588     fn macos_stat(
589         &mut self,
590         path_op: OpTy<'tcx, Tag>,
591         buf_op: OpTy<'tcx, Tag>,
592     ) -> InterpResult<'tcx, i32> {
593         let this = self.eval_context_mut();
594         this.assert_target_os("macos", "stat");
595         this.check_no_isolation("stat")?;
596         // `stat` always follows symlinks.
597         this.macos_stat_or_lstat(true, path_op, buf_op)
598     }
599
600     // `lstat` is used to get symlink metadata.
601     fn macos_lstat(
602         &mut self,
603         path_op: OpTy<'tcx, Tag>,
604         buf_op: OpTy<'tcx, Tag>,
605     ) -> InterpResult<'tcx, i32> {
606         let this = self.eval_context_mut();
607         this.assert_target_os("macos", "lstat");
608         this.check_no_isolation("lstat")?;
609         this.macos_stat_or_lstat(false, path_op, buf_op)
610     }
611
612     fn macos_fstat(
613         &mut self,
614         fd_op: OpTy<'tcx, Tag>,
615         buf_op: OpTy<'tcx, Tag>,
616     ) -> InterpResult<'tcx, i32> {
617         let this = self.eval_context_mut();
618
619         this.assert_target_os("macos", "fstat");
620         this.check_no_isolation("fstat")?;
621
622         let fd = this.read_scalar(fd_op)?.to_i32()?;
623
624         let metadata = match FileMetadata::from_fd(this, fd)? {
625             Some(metadata) => metadata,
626             None => return Ok(-1),
627         };
628         this.macos_stat_write_buf(metadata, buf_op)
629     }
630
631     fn linux_statx(
632         &mut self,
633         dirfd_op: OpTy<'tcx, Tag>,    // Should be an `int`
634         pathname_op: OpTy<'tcx, Tag>, // Should be a `const char *`
635         flags_op: OpTy<'tcx, Tag>,    // Should be an `int`
636         _mask_op: OpTy<'tcx, Tag>,    // Should be an `unsigned int`
637         statxbuf_op: OpTy<'tcx, Tag>, // Should be a `struct statx *`
638     ) -> InterpResult<'tcx, i32> {
639         let this = self.eval_context_mut();
640
641         this.assert_target_os("linux", "statx");
642         this.check_no_isolation("statx")?;
643
644         let statxbuf_scalar = this.read_scalar(statxbuf_op)?.not_undef()?;
645         let pathname_scalar = this.read_scalar(pathname_op)?.not_undef()?;
646
647         // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
648         if this.is_null(statxbuf_scalar)? || this.is_null(pathname_scalar)? {
649             let efault = this.eval_libc("EFAULT")?;
650             this.set_last_error(efault)?;
651             return Ok(-1);
652         }
653
654         // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
655         // proper `MemPlace` and then write the results of this function to it. However, the
656         // `syscall` function is untyped. This means that all the `statx` parameters are provided
657         // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
658         // `statxbuf_op` by using the `libc::statx` struct type.
659         let statxbuf_place = {
660             // FIXME: This long path is required because `libc::statx` is an struct and also a
661             // function and `resolve_path` is returning the latter.
662             let statx_ty = this
663                 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])
664                 .monomorphic_ty(*this.tcx);
665             let statxbuf_ty = this.tcx.mk_mut_ptr(statx_ty);
666             let statxbuf_layout = this.layout_of(statxbuf_ty)?;
667             let statxbuf_imm = ImmTy::from_scalar(statxbuf_scalar, statxbuf_layout);
668             this.ref_to_mplace(statxbuf_imm)?
669         };
670
671         let path = this.read_path_from_c_str(pathname_scalar)?.into_owned();
672         // `flags` should be a `c_int` but the `syscall` function provides an `isize`.
673         let flags: i32 =
674             this.read_scalar(flags_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
675                 err_unsup_format!("failed to convert pointer sized operand to integer: {}", e)
676             })?;
677         let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
678         // `dirfd` should be a `c_int` but the `syscall` function provides an `isize`.
679         let dirfd: i32 =
680             this.read_scalar(dirfd_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
681                 err_unsup_format!("failed to convert pointer sized operand to integer: {}", e)
682             })?;
683         // We only support:
684         // * interpreting `path` as an absolute directory,
685         // * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
686         // * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
687         // set.
688         // Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
689         // found this error, please open an issue reporting it.
690         if !(
691             path.is_absolute() ||
692             dirfd == this.eval_libc_i32("AT_FDCWD")? ||
693             (path.as_os_str().is_empty() && empty_path_flag)
694         ) {
695             throw_unsup_format!(
696                 "using statx is only supported with absolute paths, relative paths with the file \
697                 descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
698                 file descriptor"
699             )
700         }
701
702         // the `_mask_op` paramter specifies the file information that the caller requested.
703         // However `statx` is allowed to return information that was not requested or to not
704         // return information that was requested. This `mask` represents the information we can
705         // actually provide for any target.
706         let mut mask =
707             this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
708
709         // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
710         // symbolic links.
711         let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
712
713         // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
714         // represented by dirfd, whether it's a directory or otherwise.
715         let metadata = if path.as_os_str().is_empty() && empty_path_flag {
716             FileMetadata::from_fd(this, dirfd)?
717         } else {
718             FileMetadata::from_path(this, &path, follow_symlink)?
719         };
720         let metadata = match metadata {
721             Some(metadata) => metadata,
722             None => return Ok(-1),
723         };
724
725         // The `mode` field specifies the type of the file and the permissions over the file for
726         // the owner, its group and other users. Given that we can only provide the file type
727         // without using platform specific methods, we only set the bits corresponding to the file
728         // type. This should be an `__u16` but `libc` provides its values as `u32`.
729         let mode: u16 = metadata
730             .mode
731             .to_u32()?
732             .try_into()
733             .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
734
735         // We need to set the corresponding bits of `mask` if the access, creation and modification
736         // times were available. Otherwise we let them be zero.
737         let (access_sec, access_nsec) = metadata.accessed.map(|tup| {
738             mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
739             InterpResult::Ok(tup)
740         }).unwrap_or(Ok((0, 0)))?;
741
742         let (created_sec, created_nsec) = metadata.created.map(|tup| {
743             mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
744             InterpResult::Ok(tup)
745         }).unwrap_or(Ok((0, 0)))?;
746
747         let (modified_sec, modified_nsec) = metadata.modified.map(|tup| {
748             mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
749             InterpResult::Ok(tup)
750         }).unwrap_or(Ok((0, 0)))?;
751
752         let __u32_layout = this.libc_ty_layout("__u32")?;
753         let __u64_layout = this.libc_ty_layout("__u64")?;
754         let __u16_layout = this.libc_ty_layout("__u16")?;
755
756         // Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
757         // zero for the unavailable fields.
758         let imms = [
759             immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
760             immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
761             immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
762             immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
763             immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
764             immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
765             immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
766             immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
767             immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
768             immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
769             immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
770             immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
771             immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
772             immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
773             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
774             immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
775             immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
776             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
777             immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
778             immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
779             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
780             immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
781             immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
782             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
783             immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
784             immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
785             immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
786             immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
787         ];
788
789         this.write_packed_immediates(statxbuf_place, &imms)?;
790
791         Ok(0)
792     }
793
794     fn rename(
795         &mut self,
796         oldpath_op: OpTy<'tcx, Tag>,
797         newpath_op: OpTy<'tcx, Tag>,
798     ) -> InterpResult<'tcx, i32> {
799         let this = self.eval_context_mut();
800
801         this.check_no_isolation("rename")?;
802
803         let oldpath_scalar = this.read_scalar(oldpath_op)?.not_undef()?;
804         let newpath_scalar = this.read_scalar(newpath_op)?.not_undef()?;
805
806         if this.is_null(oldpath_scalar)? || this.is_null(newpath_scalar)? {
807             let efault = this.eval_libc("EFAULT")?;
808             this.set_last_error(efault)?;
809             return Ok(-1);
810         }
811
812         let oldpath = this.read_path_from_c_str(oldpath_scalar)?;
813         let newpath = this.read_path_from_c_str(newpath_scalar)?;
814
815         let result = rename(oldpath, newpath).map(|_| 0);
816
817         this.try_unwrap_io_result(result)
818     }
819
820     fn mkdir(
821         &mut self,
822         path_op: OpTy<'tcx, Tag>,
823         mode_op: OpTy<'tcx, Tag>,
824     ) -> InterpResult<'tcx, i32> {
825         let this = self.eval_context_mut();
826
827         this.check_no_isolation("mkdir")?;
828
829         #[cfg_attr(not(unix), allow(unused_variables))]
830         let mode = if this.tcx.sess.target.target.target_os == "macos" {
831             u32::from(this.read_scalar(mode_op)?.not_undef()?.to_u16()?)
832         } else {
833             this.read_scalar(mode_op)?.to_u32()?
834         };
835
836         let path = this.read_path_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
837
838         #[cfg_attr(not(unix), allow(unused_mut))]
839         let mut builder = DirBuilder::new();
840
841         // If the host supports it, forward on the mode of the directory
842         // (i.e. permission bits and the sticky bit)
843         #[cfg(unix)]
844         {
845             use std::os::unix::fs::DirBuilderExt;
846             builder.mode(mode.into());
847         }
848
849         let result = builder.create(path).map(|_| 0i32);
850
851         this.try_unwrap_io_result(result)
852     }
853
854     fn rmdir(
855         &mut self,
856         path_op: OpTy<'tcx, Tag>,
857     ) -> InterpResult<'tcx, i32> {
858         let this = self.eval_context_mut();
859
860         this.check_no_isolation("rmdir")?;
861
862         let path = this.read_path_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
863
864         let result = remove_dir(path).map(|_| 0i32);
865
866         this.try_unwrap_io_result(result)
867     }
868
869     fn opendir(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
870         let this = self.eval_context_mut();
871
872         this.check_no_isolation("opendir")?;
873
874         let name = this.read_path_from_c_str(this.read_scalar(name_op)?.not_undef()?)?;
875
876         let result = read_dir(name);
877
878         match result {
879             Ok(dir_iter) => {
880                 let id = this.machine.dir_handler.insert_new(dir_iter);
881
882                 // The libc API for opendir says that this method returns a pointer to an opaque
883                 // structure, but we are returning an ID number. Thus, pass it as a scalar of
884                 // pointer width.
885                 Ok(Scalar::from_machine_usize(id, this))
886             }
887             Err(e) => {
888                 this.set_last_error_from_io_error(e)?;
889                 Ok(Scalar::null_ptr(this))
890             }
891         }
892     }
893
894     fn linux_readdir64_r(
895         &mut self,
896         dirp_op: OpTy<'tcx, Tag>,
897         entry_op: OpTy<'tcx, Tag>,
898         result_op: OpTy<'tcx, Tag>,
899     ) -> InterpResult<'tcx, i32> {
900         let this = self.eval_context_mut();
901
902         this.assert_target_os("linux", "readdir64_r");
903         this.check_no_isolation("readdir64_r")?;
904
905         let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
906
907         let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
908             err_unsup_format!("the DIR pointer passed to readdir64_r did not come from opendir")
909         })?;
910         match dir_iter.next() {
911             Some(Ok(dir_entry)) => {
912                 // Write into entry, write pointer to result, return 0 on success.
913                 // The name is written with write_os_str_to_c_str, while the rest of the
914                 // dirent64 struct is written using write_packed_immediates.
915
916                 // For reference:
917                 // pub struct dirent64 {
918                 //     pub d_ino: ino64_t,
919                 //     pub d_off: off64_t,
920                 //     pub d_reclen: c_ushort,
921                 //     pub d_type: c_uchar,
922                 //     pub d_name: [c_char; 256],
923                 // }
924
925                 let entry_place = this.deref_operand(entry_op)?;
926                 let name_place = this.mplace_field(entry_place, 4)?;
927
928                 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
929                 let (name_fits, _) = this.write_os_str_to_c_str(
930                     &file_name,
931                     name_place.ptr,
932                     name_place.layout.size.bytes(),
933                 )?;
934                 if !name_fits {
935                     throw_unsup_format!("a directory entry had a name too large to fit in libc::dirent64");
936                 }
937
938                 let entry_place = this.deref_operand(entry_op)?;
939                 let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
940                 let off64_t_layout = this.libc_ty_layout("off64_t")?;
941                 let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
942                 let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
943
944                 // If the host is a Unix system, fill in the inode number with its real value.
945                 // If not, use 0 as a fallback value.
946                 #[cfg(unix)]
947                 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
948                 #[cfg(not(unix))]
949                 let ino = 0u64;
950
951                 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
952
953                 let imms = [
954                     immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
955                     immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
956                     immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
957                     immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
958                 ];
959                 this.write_packed_immediates(entry_place, &imms)?;
960
961                 let result_place = this.deref_operand(result_op)?;
962                 this.write_scalar(this.read_scalar(entry_op)?, result_place.into())?;
963
964                 Ok(0)
965             }
966             None => {
967                 // end of stream: return 0, assign *result=NULL
968                 this.write_null(this.deref_operand(result_op)?.into())?;
969                 Ok(0)
970             }
971             Some(Err(e)) => match e.raw_os_error() {
972                 // return positive error number on error
973                 Some(error) => Ok(error),
974                 None => {
975                     throw_unsup_format!("the error {} couldn't be converted to a return value", e)
976                 }
977             },
978         }
979     }
980
981     fn macos_readdir_r(
982         &mut self,
983         dirp_op: OpTy<'tcx, Tag>,
984         entry_op: OpTy<'tcx, Tag>,
985         result_op: OpTy<'tcx, Tag>,
986     ) -> InterpResult<'tcx, i32> {
987         let this = self.eval_context_mut();
988
989         this.assert_target_os("macos", "readdir_r");
990         this.check_no_isolation("readdir_r")?;
991
992         let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
993
994         let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
995             err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
996         })?;
997         match dir_iter.next() {
998             Some(Ok(dir_entry)) => {
999                 // Write into entry, write pointer to result, return 0 on success.
1000                 // The name is written with write_os_str_to_c_str, while the rest of the
1001                 // dirent struct is written using write_packed_Immediates.
1002
1003                 // For reference:
1004                 // pub struct dirent {
1005                 //     pub d_ino: u64,
1006                 //     pub d_seekoff: u64,
1007                 //     pub d_reclen: u16,
1008                 //     pub d_namlen: u16,
1009                 //     pub d_type: u8,
1010                 //     pub d_name: [c_char; 1024],
1011                 // }
1012
1013                 let entry_place = this.deref_operand(entry_op)?;
1014                 let name_place = this.mplace_field(entry_place, 5)?;
1015
1016                 let file_name = dir_entry.file_name(); // not a Path as there are no separators!
1017                 let (name_fits, file_name_len) = this.write_os_str_to_c_str(
1018                     &file_name,
1019                     name_place.ptr,
1020                     name_place.layout.size.bytes(),
1021                 )?;
1022                 if !name_fits {
1023                     throw_unsup_format!("a directory entry had a name too large to fit in libc::dirent");
1024                 }
1025
1026                 let entry_place = this.deref_operand(entry_op)?;
1027                 let ino_t_layout = this.libc_ty_layout("ino_t")?;
1028                 let off_t_layout = this.libc_ty_layout("off_t")?;
1029                 let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
1030                 let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
1031
1032                 // If the host is a Unix system, fill in the inode number with its real value.
1033                 // If not, use 0 as a fallback value.
1034                 #[cfg(unix)]
1035                 let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
1036                 #[cfg(not(unix))]
1037                 let ino = 0u64;
1038
1039                 let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
1040
1041                 let imms = [
1042                     immty_from_uint_checked(ino, ino_t_layout)?, // d_ino
1043                     immty_from_uint_checked(0u128, off_t_layout)?, // d_seekoff
1044                     immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
1045                     immty_from_uint_checked(file_name_len, c_ushort_layout)?, // d_namlen
1046                     immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
1047                 ];
1048                 this.write_packed_immediates(entry_place, &imms)?;
1049
1050                 let result_place = this.deref_operand(result_op)?;
1051                 this.write_scalar(this.read_scalar(entry_op)?, result_place.into())?;
1052
1053                 Ok(0)
1054             }
1055             None => {
1056                 // end of stream: return 0, assign *result=NULL
1057                 this.write_null(this.deref_operand(result_op)?.into())?;
1058                 Ok(0)
1059             }
1060             Some(Err(e)) => match e.raw_os_error() {
1061                 // return positive error number on error
1062                 Some(error) => Ok(error),
1063                 None => {
1064                     throw_unsup_format!("the error {} couldn't be converted to a return value", e)
1065                 }
1066             },
1067         }
1068     }
1069
1070     fn closedir(&mut self, dirp_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1071         let this = self.eval_context_mut();
1072
1073         this.check_no_isolation("closedir")?;
1074
1075         let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
1076
1077         if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
1078             drop(dir_iter);
1079             Ok(0)
1080         } else {
1081             this.handle_not_found()
1082         }
1083     }
1084
1085     fn ftruncate64(
1086         &mut self,
1087         fd_op: OpTy<'tcx, Tag>,
1088         length_op: OpTy<'tcx, Tag>,
1089     ) -> InterpResult<'tcx, i32> {
1090         let this = self.eval_context_mut();
1091
1092         this.check_no_isolation("ftruncate64")?;
1093
1094         let fd = this.read_scalar(fd_op)?.to_i32()?;
1095         let length = this.read_scalar(length_op)?.to_i64()?;
1096         if let Some(FileHandle { file, writable }) = this.machine.file_handler.handles.get_mut(&fd) {
1097             if *writable {
1098                 if let Ok(length) = length.try_into() {
1099                     let result = file.set_len(length);
1100                     this.try_unwrap_io_result(result.map(|_| 0i32))
1101                 } else {
1102                     let einval = this.eval_libc("EINVAL")?;
1103                     this.set_last_error(einval)?;
1104                     Ok(-1)
1105                 }
1106             } else {
1107                 // The file is not writable
1108                 let einval = this.eval_libc("EINVAL")?;
1109                 this.set_last_error(einval)?;
1110                 Ok(-1)
1111             }
1112         } else {
1113             this.handle_not_found()
1114         }
1115     }
1116
1117     fn fsync(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1118         // On macOS, `fsync` (unlike `fcntl(F_FULLFSYNC)`) does not wait for the
1119         // underlying disk to finish writing. In the interest of host compatibility,
1120         // we conservatively implement this with `sync_all`, which
1121         // *does* wait for the disk.
1122
1123         let this = self.eval_context_mut();
1124
1125         this.check_no_isolation("fsync")?;
1126
1127         let fd = this.read_scalar(fd_op)?.to_i32()?;
1128         if let Some(FileHandle { file, writable }) = this.machine.file_handler.handles.get_mut(&fd) {
1129             if !*writable && cfg!(windows) {
1130                 // sync_all() will return an error on Windows hosts if the file is not opened for writing.
1131                 Ok(0i32)
1132             } else {
1133                 let result = file.sync_all();
1134                 this.try_unwrap_io_result(result.map(|_| 0i32))
1135             }
1136         } else {
1137             this.handle_not_found()
1138         }
1139     }
1140
1141     fn fdatasync(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
1142         let this = self.eval_context_mut();
1143
1144         this.check_no_isolation("fdatasync")?;
1145
1146         let fd = this.read_scalar(fd_op)?.to_i32()?;
1147         if let Some(FileHandle { file, writable }) = this.machine.file_handler.handles.get_mut(&fd) {
1148             if !*writable && cfg!(windows) {
1149                 // sync_data() will return an error on Windows hosts if the file is not opened for writing.
1150                 Ok(0i32)
1151             } else {
1152                 let result = file.sync_data();
1153                 this.try_unwrap_io_result(result.map(|_| 0i32))
1154             }
1155         } else {
1156             this.handle_not_found()
1157         }
1158     }
1159
1160     fn sync_file_range(
1161         &mut self,
1162         fd_op: OpTy<'tcx, Tag>,
1163         offset_op: OpTy<'tcx, Tag>,
1164         nbytes_op: OpTy<'tcx, Tag>,
1165         flags_op: OpTy<'tcx, Tag>,
1166     ) -> InterpResult<'tcx, i32> {
1167         let this = self.eval_context_mut();
1168
1169         this.check_no_isolation("sync_file_range")?;
1170
1171         let fd = this.read_scalar(fd_op)?.to_i32()?;
1172         let offset = this.read_scalar(offset_op)?.to_i64()?;
1173         let nbytes = this.read_scalar(nbytes_op)?.to_i64()?;
1174         let flags = this.read_scalar(flags_op)?.to_i32()?;
1175
1176         if offset < 0 || nbytes < 0 {
1177             let einval = this.eval_libc("EINVAL")?;
1178             this.set_last_error(einval)?;
1179             return Ok(-1);
1180         }
1181         let allowed_flags = this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_BEFORE")?
1182             | this.eval_libc_i32("SYNC_FILE_RANGE_WRITE")?
1183             | this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_AFTER")?;
1184         if flags & allowed_flags != flags {
1185             let einval = this.eval_libc("EINVAL")?;
1186             this.set_last_error(einval)?;
1187             return Ok(-1);
1188         }
1189
1190         if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
1191             // In the interest of host compatibility, we conservatively ignore
1192             // offset, nbytes, and flags, and sync the entire file.
1193             let result = file.sync_data();
1194             this.try_unwrap_io_result(result.map(|_| 0i32))
1195         } else {
1196             this.handle_not_found()
1197         }
1198     }
1199 }
1200
1201 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
1202 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
1203 /// epoch.
1204 fn extract_sec_and_nsec<'tcx>(
1205     time: std::io::Result<SystemTime>
1206 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
1207     time.ok().map(|time| {
1208         let duration = system_time_to_duration(&time)?;
1209         Ok((duration.as_secs(), duration.subsec_nanos()))
1210     }).transpose()
1211 }
1212
1213 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
1214 /// shims.
1215 struct FileMetadata {
1216     mode: Scalar<Tag>,
1217     size: u64,
1218     created: Option<(u64, u32)>,
1219     accessed: Option<(u64, u32)>,
1220     modified: Option<(u64, u32)>,
1221 }
1222
1223 impl FileMetadata {
1224     fn from_path<'tcx, 'mir>(
1225         ecx: &mut MiriEvalContext<'mir, 'tcx>,
1226         path: &Path,
1227         follow_symlink: bool
1228     ) -> InterpResult<'tcx, Option<FileMetadata>> {
1229         let metadata = if follow_symlink {
1230             std::fs::metadata(path)
1231         } else {
1232             std::fs::symlink_metadata(path)
1233         };
1234
1235         FileMetadata::from_meta(ecx, metadata)
1236     }
1237
1238     fn from_fd<'tcx, 'mir>(
1239         ecx: &mut MiriEvalContext<'mir, 'tcx>,
1240         fd: i32,
1241     ) -> InterpResult<'tcx, Option<FileMetadata>> {
1242         let option = ecx.machine.file_handler.handles.get(&fd);
1243         let file = match option {
1244             Some(FileHandle { file, writable: _ }) => file,
1245             None => return ecx.handle_not_found().map(|_: i32| None),
1246         };
1247         let metadata = file.metadata();
1248
1249         FileMetadata::from_meta(ecx, metadata)
1250     }
1251
1252     fn from_meta<'tcx, 'mir>(
1253         ecx: &mut MiriEvalContext<'mir, 'tcx>,
1254         metadata: Result<std::fs::Metadata, std::io::Error>,
1255     ) -> InterpResult<'tcx, Option<FileMetadata>> {
1256         let metadata = match metadata {
1257             Ok(metadata) => metadata,
1258             Err(e) => {
1259                 ecx.set_last_error_from_io_error(e)?;
1260                 return Ok(None);
1261             }
1262         };
1263
1264         let file_type = metadata.file_type();
1265
1266         let mode_name = if file_type.is_file() {
1267             "S_IFREG"
1268         } else if file_type.is_dir() {
1269             "S_IFDIR"
1270         } else {
1271             "S_IFLNK"
1272         };
1273
1274         let mode = ecx.eval_libc(mode_name)?;
1275
1276         let size = metadata.len();
1277
1278         let created = extract_sec_and_nsec(metadata.created())?;
1279         let accessed = extract_sec_and_nsec(metadata.accessed())?;
1280         let modified = extract_sec_and_nsec(metadata.modified())?;
1281
1282         // FIXME: Provide more fields using platform specific methods.
1283         Ok(Some(FileMetadata { mode, size, created, accessed, modified }))
1284     }
1285 }