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