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