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