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