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