]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
Add shims for mkdir and rmdir
[rust.git] / src / shims / fs.rs
1 use std::collections::BTreeMap;
2 use std::convert::{TryFrom, TryInto};
3 use std::fs::{remove_dir, remove_file, rename, DirBuilder, File, OpenOptions};
4 use std::io::{Read, Seek, SeekFrom, Write};
5 use std::path::PathBuf;
6 use std::time::SystemTime;
7
8 use rustc::ty::layout::{Align, LayoutOf, Size};
9
10 use crate::stacked_borrows::Tag;
11 use crate::*;
12 use helpers::immty_from_uint_checked;
13 use shims::time::system_time_to_duration;
14
15 #[derive(Debug)]
16 pub struct FileHandle {
17     file: File,
18     writable: bool,
19 }
20
21 #[derive(Debug, Default)]
22 pub struct FileHandler {
23     handles: BTreeMap<i32, FileHandle>,
24 }
25
26 // fd numbers 0, 1, and 2 are reserved for stdin, stdout, and stderr
27 const MIN_NORMAL_FILE_FD: i32 = 3;
28
29 impl FileHandler {
30     fn insert_fd(&mut self, file_handle: FileHandle) -> i32 {
31         self.insert_fd_with_min_fd(file_handle, 0)
32     }
33
34     fn insert_fd_with_min_fd(&mut self, file_handle: FileHandle, min_fd: i32) -> i32 {
35         let min_fd = std::cmp::max(min_fd, MIN_NORMAL_FILE_FD);
36
37         // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
38         // between used FDs, the find_map combinator will return it. If the first such unused FD
39         // is after all other used FDs, the find_map combinator will return None, and we will use
40         // the FD following the greatest FD thus far.
41         let candidate_new_fd = self
42             .handles
43             .range(min_fd..)
44             .zip(min_fd..)
45             .find_map(|((fd, _fh), counter)| {
46                 if *fd != counter {
47                     // There was a gap in the fds stored, return the first unused one
48                     // (note that this relies on BTreeMap iterating in key order)
49                     Some(counter)
50                 } else {
51                     // This fd is used, keep going
52                     None
53                 }
54             });
55         let new_fd = candidate_new_fd.unwrap_or_else(|| {
56             // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
57             // maximum fd in the map
58             self.handles.last_entry().map(|entry| entry.key() + 1).unwrap_or(min_fd)
59         });
60
61         self.handles.insert(new_fd, file_handle).unwrap_none();
62         new_fd
63     }
64 }
65
66 impl<'mir, 'tcx> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
67 trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
68     /// Emulate `stat` or `lstat` on the `macos` platform. This function is not intended to be
69     /// called directly from `emulate_foreign_item_by_name`, so it does not check if isolation is
70     /// disabled or if the target platform is the correct one. Please use `macos_stat` or
71     /// `macos_lstat` instead.
72     fn macos_stat_or_lstat(
73         &mut self,
74         follow_symlink: bool,
75         path_op: OpTy<'tcx, Tag>,
76         buf_op: OpTy<'tcx, Tag>,
77     ) -> InterpResult<'tcx, i32> {
78         let this = self.eval_context_mut();
79
80         let path_scalar = this.read_scalar(path_op)?.not_undef()?;
81         let path: PathBuf = this.read_os_str_from_c_str(path_scalar)?.into();
82
83         let metadata = match FileMetadata::from_path(this, path, follow_symlink)? {
84             Some(metadata) => metadata,
85             None => return Ok(-1),
86         };
87         this.macos_stat_write_buf(metadata, buf_op)
88     }
89
90     fn macos_stat_write_buf(
91         &mut self,
92         metadata: FileMetadata,
93         buf_op: OpTy<'tcx, Tag>,
94     ) -> InterpResult<'tcx, i32> {
95         let this = self.eval_context_mut();
96
97         let mode: u16 = metadata.mode.to_u16()?;
98
99         let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
100         let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
101         let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
102
103         let dev_t_layout = this.libc_ty_layout("dev_t")?;
104         let mode_t_layout = this.libc_ty_layout("mode_t")?;
105         let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
106         let ino_t_layout = this.libc_ty_layout("ino_t")?;
107         let uid_t_layout = this.libc_ty_layout("uid_t")?;
108         let gid_t_layout = this.libc_ty_layout("gid_t")?;
109         let time_t_layout = this.libc_ty_layout("time_t")?;
110         let long_layout = this.libc_ty_layout("c_long")?;
111         let off_t_layout = this.libc_ty_layout("off_t")?;
112         let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
113         let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
114         let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
115
116         // We need to add 32 bits of padding after `st_rdev` if we are on a 64-bit platform.
117         let pad_layout = if this.tcx.sess.target.ptr_width == 64 {
118             uint32_t_layout
119         } else {
120             this.layout_of(this.tcx.mk_unit())?
121         };
122
123         let imms = [
124             immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
125             immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
126             immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
127             immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
128             immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
129             immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
130             immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
131             immty_from_uint_checked(0u128, pad_layout)?, // padding for 64-bit targets
132             immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
133             immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
134             immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
135             immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
136             immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
137             immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
138             immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
139             immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
140             immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
141             immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
142             immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
143             immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
144             immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
145         ];
146
147         let buf = this.deref_operand(buf_op)?;
148         this.write_packed_immediates(buf, &imms)?;
149
150         Ok(0)
151     }
152
153     /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
154     /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
155     /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
156     /// types (like `read`, that returns an `i64`).
157     fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
158         let this = self.eval_context_mut();
159         let ebadf = this.eval_libc("EBADF")?;
160         this.set_last_error(ebadf)?;
161         Ok((-1).into())
162     }
163 }
164
165 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
166 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
167     fn open(
168         &mut self,
169         path_op: OpTy<'tcx, Tag>,
170         flag_op: OpTy<'tcx, Tag>,
171     ) -> InterpResult<'tcx, i32> {
172         let this = self.eval_context_mut();
173
174         this.check_no_isolation("open")?;
175
176         let flag = this.read_scalar(flag_op)?.to_i32()?;
177
178         let mut options = OpenOptions::new();
179
180         let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
181         let o_wronly = this.eval_libc_i32("O_WRONLY")?;
182         let o_rdwr = this.eval_libc_i32("O_RDWR")?;
183         // The first two bits of the flag correspond to the access mode in linux, macOS and
184         // windows. We need to check that in fact the access mode flags for the current platform
185         // only use these two bits, otherwise we are in an unsupported platform and should error.
186         if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
187             throw_unsup_format!("Access mode flags on this platform are unsupported");
188         }
189         let mut writable = true;
190
191         // Now we check the access mode
192         let access_mode = flag & 0b11;
193
194         if access_mode == o_rdonly {
195             writable = false;
196             options.read(true);
197         } else if access_mode == o_wronly {
198             options.write(true);
199         } else if access_mode == o_rdwr {
200             options.read(true).write(true);
201         } else {
202             throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
203         }
204         // We need to check that there aren't unsupported options in `flag`. For this we try to
205         // reproduce the content of `flag` in the `mirror` variable using only the supported
206         // options.
207         let mut mirror = access_mode;
208
209         let o_append = this.eval_libc_i32("O_APPEND")?;
210         if flag & o_append != 0 {
211             options.append(true);
212             mirror |= o_append;
213         }
214         let o_trunc = this.eval_libc_i32("O_TRUNC")?;
215         if flag & o_trunc != 0 {
216             options.truncate(true);
217             mirror |= o_trunc;
218         }
219         let o_creat = this.eval_libc_i32("O_CREAT")?;
220         if flag & o_creat != 0 {
221             options.create(true);
222             mirror |= o_creat;
223         }
224         let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
225         if flag & o_cloexec != 0 {
226             // We do not need to do anything for this flag because `std` already sets it.
227             // (Technically we do not support *not* setting this flag, but we ignore that.)
228             mirror |= o_cloexec;
229         }
230         // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
231         // then we throw an error.
232         if flag != mirror {
233             throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
234         }
235
236         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
237
238         let fd = options.open(&path).map(|file| {
239             let fh = &mut this.machine.file_handler;
240             fh.insert_fd(FileHandle { file, writable })
241         });
242
243         this.try_unwrap_io_result(fd)
244     }
245
246     fn fcntl(
247         &mut self,
248         fd_op: OpTy<'tcx, Tag>,
249         cmd_op: OpTy<'tcx, Tag>,
250         start_op: Option<OpTy<'tcx, Tag>>,
251     ) -> InterpResult<'tcx, i32> {
252         let this = self.eval_context_mut();
253
254         this.check_no_isolation("fcntl")?;
255
256         let fd = this.read_scalar(fd_op)?.to_i32()?;
257         let cmd = this.read_scalar(cmd_op)?.to_i32()?;
258         // We only support getting the flags for a descriptor.
259         if cmd == this.eval_libc_i32("F_GETFD")? {
260             // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
261             // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
262             // always sets this flag when opening a file. However we still need to check that the
263             // file itself is open.
264             if this.machine.file_handler.handles.contains_key(&fd) {
265                 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
266             } else {
267                 this.handle_not_found()
268             }
269         } else if cmd == this.eval_libc_i32("F_DUPFD")?
270             || cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
271         {
272             // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
273             // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
274             // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
275             // thus they can share the same implementation here.
276             if fd < MIN_NORMAL_FILE_FD {
277                 throw_unsup_format!("Duplicating file descriptors for stdin, stdout, or stderr is not supported")
278             }
279             let start_op = start_op.ok_or_else(|| {
280                 err_unsup_format!(
281                     "fcntl with command F_DUPFD or F_DUPFD_CLOEXEC requires a third argument"
282                 )
283             })?;
284             let start = this.read_scalar(start_op)?.to_i32()?;
285             let fh = &mut this.machine.file_handler;
286             let (file_result, writable) = match fh.handles.get(&fd) {
287                 Some(FileHandle { file, writable }) => (file.try_clone(), *writable),
288                 None => return this.handle_not_found(),
289             };
290             let fd_result = file_result.map(|duplicated| {
291                 fh.insert_fd_with_min_fd(FileHandle { file: duplicated, writable }, start)
292             });
293             this.try_unwrap_io_result(fd_result)
294         } else {
295             throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
296         }
297     }
298
299     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
300         let this = self.eval_context_mut();
301
302         this.check_no_isolation("close")?;
303
304         let fd = this.read_scalar(fd_op)?.to_i32()?;
305
306         if let Some(FileHandle { file, writable }) = this.machine.file_handler.handles.remove(&fd) {
307             // We sync the file if it was opened in a mode different than read-only.
308             if writable {
309                 // `File::sync_all` does the checks that are done when closing a file. We do this to
310                 // to handle possible errors correctly.
311                 let result = this.try_unwrap_io_result(file.sync_all().map(|_| 0i32));
312                 // Now we actually close the file.
313                 drop(file);
314                 // And return the result.
315                 result
316             } else {
317                 // We drop the file, this closes it but ignores any errors produced when closing
318                 // it. This is done because `File::sync_all` cannot be done over files like
319                 // `/dev/urandom` which are read-only. Check
320                 // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439 for a deeper
321                 // discussion.
322                 drop(file);
323                 Ok(0)
324             }
325         } else {
326             this.handle_not_found()
327         }
328     }
329
330     fn read(
331         &mut self,
332         fd_op: OpTy<'tcx, Tag>,
333         buf_op: OpTy<'tcx, Tag>,
334         count_op: OpTy<'tcx, Tag>,
335     ) -> InterpResult<'tcx, i64> {
336         let this = self.eval_context_mut();
337
338         this.check_no_isolation("read")?;
339
340         let fd = this.read_scalar(fd_op)?.to_i32()?;
341         let buf = this.read_scalar(buf_op)?.not_undef()?;
342         let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
343
344         // Check that the *entire* buffer is actually valid memory.
345         this.memory.check_ptr_access(
346             buf,
347             Size::from_bytes(count),
348             Align::from_bytes(1).unwrap(),
349         )?;
350
351         // We cap the number of read bytes to the largest value that we are able to fit in both the
352         // host's and target's `isize`. This saves us from having to handle overflows later.
353         let count = count.min(this.isize_max() as u64).min(isize::max_value() as u64);
354
355         if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
356             // This can never fail because `count` was capped to be smaller than
357             // `isize::max_value()`.
358             let count = isize::try_from(count).unwrap();
359             // We want to read at most `count` bytes. We are sure that `count` is not negative
360             // because it was a target's `usize`. Also we are sure that its smaller than
361             // `usize::max_value()` because it is a host's `isize`.
362             let mut bytes = vec![0; count as usize];
363             let result = file
364                 .read(&mut bytes)
365                 // `File::read` never returns a value larger than `count`, so this cannot fail.
366                 .map(|c| i64::try_from(c).unwrap());
367
368             match result {
369                 Ok(read_bytes) => {
370                     // If reading to `bytes` did not fail, we write those bytes to the buffer.
371                     this.memory.write_bytes(buf, bytes)?;
372                     Ok(read_bytes)
373                 }
374                 Err(e) => {
375                     this.set_last_error_from_io_error(e)?;
376                     Ok(-1)
377                 }
378             }
379         } else {
380             this.handle_not_found()
381         }
382     }
383
384     fn write(
385         &mut self,
386         fd_op: OpTy<'tcx, Tag>,
387         buf_op: OpTy<'tcx, Tag>,
388         count_op: OpTy<'tcx, Tag>,
389     ) -> InterpResult<'tcx, i64> {
390         let this = self.eval_context_mut();
391
392         this.check_no_isolation("write")?;
393
394         let fd = this.read_scalar(fd_op)?.to_i32()?;
395         let buf = this.read_scalar(buf_op)?.not_undef()?;
396         let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
397
398         // Check that the *entire* buffer is actually valid memory.
399         this.memory.check_ptr_access(
400             buf,
401             Size::from_bytes(count),
402             Align::from_bytes(1).unwrap(),
403         )?;
404
405         // We cap the number of written bytes to the largest value that we are able to fit in both the
406         // host's and target's `isize`. This saves us from having to handle overflows later.
407         let count = count.min(this.isize_max() as u64).min(isize::max_value() as u64);
408
409         if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
410             let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
411             let result = file.write(&bytes).map(|c| i64::try_from(c).unwrap());
412             this.try_unwrap_io_result(result)
413         } else {
414             this.handle_not_found()
415         }
416     }
417
418     fn lseek64(
419         &mut self,
420         fd_op: OpTy<'tcx, Tag>,
421         offset_op: OpTy<'tcx, Tag>,
422         whence_op: OpTy<'tcx, Tag>,
423     ) -> InterpResult<'tcx, i64> {
424         let this = self.eval_context_mut();
425
426         this.check_no_isolation("lseek64")?;
427
428         let fd = this.read_scalar(fd_op)?.to_i32()?;
429         let offset = this.read_scalar(offset_op)?.to_i64()?;
430         let whence = this.read_scalar(whence_op)?.to_i32()?;
431
432         let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
433             SeekFrom::Start(offset as u64)
434         } else if whence == this.eval_libc_i32("SEEK_CUR")? {
435             SeekFrom::Current(offset)
436         } else if whence == this.eval_libc_i32("SEEK_END")? {
437             SeekFrom::End(offset)
438         } else {
439             let einval = this.eval_libc("EINVAL")?;
440             this.set_last_error(einval)?;
441             return Ok(-1);
442         };
443
444         if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
445             let result = file.seek(seek_from).map(|offset| offset as i64);
446             this.try_unwrap_io_result(result)
447         } else {
448             this.handle_not_found()
449         }
450     }
451
452     fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
453         let this = self.eval_context_mut();
454
455         this.check_no_isolation("unlink")?;
456
457         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
458
459         let result = remove_file(path).map(|_| 0);
460
461         this.try_unwrap_io_result(result)
462     }
463
464     fn symlink(
465         &mut self,
466         target_op: OpTy<'tcx, Tag>,
467         linkpath_op: OpTy<'tcx, Tag>
468     ) -> InterpResult<'tcx, i32> {
469         #[cfg(target_family = "unix")]
470         fn create_link(src: PathBuf, dst: PathBuf) -> std::io::Result<()> {
471             std::os::unix::fs::symlink(src, dst)
472         }
473
474         #[cfg(target_family = "windows")]
475         fn create_link(src: PathBuf, dst: PathBuf) -> std::io::Result<()> {
476             use std::os::windows::fs;
477             if src.is_dir() {
478                 fs::symlink_dir(src, dst)
479             } else {
480                 fs::symlink_file(src, dst)
481             }
482         }
483
484         let this = self.eval_context_mut();
485
486         this.check_no_isolation("symlink")?;
487
488         let target = this.read_os_str_from_c_str(this.read_scalar(target_op)?.not_undef()?)?.into();
489         let linkpath = this.read_os_str_from_c_str(this.read_scalar(linkpath_op)?.not_undef()?)?.into();
490
491         this.try_unwrap_io_result(create_link(target, linkpath).map(|_| 0))
492     }
493
494     fn macos_stat(
495         &mut self,
496         path_op: OpTy<'tcx, Tag>,
497         buf_op: OpTy<'tcx, Tag>,
498     ) -> InterpResult<'tcx, i32> {
499         let this = self.eval_context_mut();
500         this.check_no_isolation("stat")?;
501         this.assert_platform("macos", "stat");
502         // `stat` always follows symlinks.
503         this.macos_stat_or_lstat(true, path_op, buf_op)
504     }
505
506     // `lstat` is used to get symlink metadata.
507     fn macos_lstat(
508         &mut self,
509         path_op: OpTy<'tcx, Tag>,
510         buf_op: OpTy<'tcx, Tag>,
511     ) -> InterpResult<'tcx, i32> {
512         let this = self.eval_context_mut();
513         this.check_no_isolation("lstat")?;
514         this.assert_platform("macos", "lstat");
515         this.macos_stat_or_lstat(false, path_op, buf_op)
516     }
517
518     fn macos_fstat(
519         &mut self,
520         fd_op: OpTy<'tcx, Tag>,
521         buf_op: OpTy<'tcx, Tag>,
522     ) -> InterpResult<'tcx, i32> {
523         let this = self.eval_context_mut();
524
525         this.check_no_isolation("fstat")?;
526         this.assert_platform("macos", "fstat");
527
528         let fd = this.read_scalar(fd_op)?.to_i32()?;
529
530         let metadata = match FileMetadata::from_fd(this, fd)? {
531             Some(metadata) => metadata,
532             None => return Ok(-1),
533         };
534         this.macos_stat_write_buf(metadata, buf_op)
535     }
536
537     fn linux_statx(
538         &mut self,
539         dirfd_op: OpTy<'tcx, Tag>,    // Should be an `int`
540         pathname_op: OpTy<'tcx, Tag>, // Should be a `const char *`
541         flags_op: OpTy<'tcx, Tag>,    // Should be an `int`
542         _mask_op: OpTy<'tcx, Tag>,    // Should be an `unsigned int`
543         statxbuf_op: OpTy<'tcx, Tag>, // Should be a `struct statx *`
544     ) -> InterpResult<'tcx, i32> {
545         let this = self.eval_context_mut();
546
547         this.check_no_isolation("statx")?;
548         this.assert_platform("linux", "statx");
549
550         let statxbuf_scalar = this.read_scalar(statxbuf_op)?.not_undef()?;
551         let pathname_scalar = this.read_scalar(pathname_op)?.not_undef()?;
552
553         // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
554         if this.is_null(statxbuf_scalar)? || this.is_null(pathname_scalar)? {
555             let efault = this.eval_libc("EFAULT")?;
556             this.set_last_error(efault)?;
557             return Ok(-1);
558         }
559
560         // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
561         // proper `MemPlace` and then write the results of this function to it. However, the
562         // `syscall` function is untyped. This means that all the `statx` parameters are provided
563         // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
564         // `statxbuf_op` by using the `libc::statx` struct type.
565         let statxbuf_place = {
566             // FIXME: This long path is required because `libc::statx` is an struct and also a
567             // function and `resolve_path` is returning the latter.
568             let statx_ty = this
569                 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])?
570                 .monomorphic_ty(*this.tcx);
571             let statxbuf_ty = this.tcx.mk_mut_ptr(statx_ty);
572             let statxbuf_layout = this.layout_of(statxbuf_ty)?;
573             let statxbuf_imm = ImmTy::from_scalar(statxbuf_scalar, statxbuf_layout);
574             this.ref_to_mplace(statxbuf_imm)?
575         };
576
577         let path: PathBuf = this.read_os_str_from_c_str(pathname_scalar)?.into();
578         // `flags` should be a `c_int` but the `syscall` function provides an `isize`.
579         let flags: i32 =
580             this.read_scalar(flags_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
581                 err_unsup_format!("Failed to convert pointer sized operand to integer: {}", e)
582             })?;
583         let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
584         // `dirfd` should be a `c_int` but the `syscall` function provides an `isize`.
585         let dirfd: i32 =
586             this.read_scalar(dirfd_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
587                 err_unsup_format!("Failed to convert pointer sized operand to integer: {}", e)
588             })?;
589         // We only support:
590         // * interpreting `path` as an absolute directory,
591         // * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
592         // * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
593         // set.
594         // Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
595         // found this error, please open an issue reporting it.
596         if !(
597             path.is_absolute() ||
598             dirfd == this.eval_libc_i32("AT_FDCWD")? ||
599             (path.as_os_str().is_empty() && empty_path_flag)
600         ) {
601             throw_unsup_format!(
602                 "Using statx is only supported with absolute paths, relative paths with the file \
603                 descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
604                 file descriptor"
605             )
606         }
607
608         // the `_mask_op` paramter specifies the file information that the caller requested.
609         // However `statx` is allowed to return information that was not requested or to not
610         // return information that was requested. This `mask` represents the information we can
611         // actually provide in any host platform.
612         let mut mask =
613             this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
614
615         // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
616         // symbolic links.
617         let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
618
619         // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
620         // represented by dirfd, whether it's a directory or otherwise.
621         let metadata = if path.as_os_str().is_empty() && empty_path_flag {
622             FileMetadata::from_fd(this, dirfd)?
623         } else {
624             FileMetadata::from_path(this, path, follow_symlink)?
625         };
626         let metadata = match metadata {
627             Some(metadata) => metadata,
628             None => return Ok(-1),
629         };
630
631         // The `mode` field specifies the type of the file and the permissions over the file for
632         // the owner, its group and other users. Given that we can only provide the file type
633         // without using platform specific methods, we only set the bits corresponding to the file
634         // type. This should be an `__u16` but `libc` provides its values as `u32`.
635         let mode: u16 = metadata
636             .mode
637             .to_u32()?
638             .try_into()
639             .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
640
641         // We need to set the corresponding bits of `mask` if the access, creation and modification
642         // times were available. Otherwise we let them be zero.
643         let (access_sec, access_nsec) = metadata.accessed.map(|tup| {
644             mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
645             InterpResult::Ok(tup)
646         }).unwrap_or(Ok((0, 0)))?;
647
648         let (created_sec, created_nsec) = metadata.created.map(|tup| {
649             mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
650             InterpResult::Ok(tup)
651         }).unwrap_or(Ok((0, 0)))?;
652
653         let (modified_sec, modified_nsec) = metadata.modified.map(|tup| {
654             mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
655             InterpResult::Ok(tup)
656         }).unwrap_or(Ok((0, 0)))?;
657
658         let __u32_layout = this.libc_ty_layout("__u32")?;
659         let __u64_layout = this.libc_ty_layout("__u64")?;
660         let __u16_layout = this.libc_ty_layout("__u16")?;
661
662         // Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
663         // zero for the unavailable fields.
664         let imms = [
665             immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
666             immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
667             immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
668             immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
669             immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
670             immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
671             immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
672             immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
673             immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
674             immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
675             immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
676             immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
677             immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
678             immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
679             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
680             immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
681             immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
682             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
683             immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
684             immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
685             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
686             immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
687             immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
688             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
689             immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
690             immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
691             immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
692             immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
693         ];
694
695         this.write_packed_immediates(statxbuf_place, &imms)?;
696
697         Ok(0)
698     }
699
700     fn rename(
701         &mut self,
702         oldpath_op: OpTy<'tcx, Tag>,
703         newpath_op: OpTy<'tcx, Tag>,
704     ) -> InterpResult<'tcx, i32> {
705         let this = self.eval_context_mut();
706
707         this.check_no_isolation("rename")?;
708
709         let oldpath_scalar = this.read_scalar(oldpath_op)?.not_undef()?;
710         let newpath_scalar = this.read_scalar(newpath_op)?.not_undef()?;
711
712         if this.is_null(oldpath_scalar)? || this.is_null(newpath_scalar)? {
713             let efault = this.eval_libc("EFAULT")?;
714             this.set_last_error(efault)?;
715             return Ok(-1);
716         }
717
718         let oldpath = this.read_os_str_from_c_str(oldpath_scalar)?;
719         let newpath = this.read_os_str_from_c_str(newpath_scalar)?;
720
721         let result = rename(oldpath, newpath).map(|_| 0);
722
723         this.try_unwrap_io_result(result)
724     }
725
726     fn mkdir(
727         &mut self,
728         path_op: OpTy<'tcx, Tag>,
729         mode_op: OpTy<'tcx, Tag>,
730     ) -> InterpResult<'tcx, i32> {
731         let this = self.eval_context_mut();
732
733         this.check_no_isolation("mkdir")?;
734
735         let mode = this.read_scalar(mode_op)?.to_u32()?;
736
737         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
738
739         let mut builder = DirBuilder::new();
740         #[cfg(target_family = "unix")]
741         {
742             use std::os::unix::fs::DirBuilderExt;
743             builder.mode(mode);
744         }
745         let result = builder.create(path).map(|_| 0i32);
746
747         this.try_unwrap_io_result(result)
748     }
749
750     fn rmdir(
751         &mut self,
752         path_op: OpTy<'tcx, Tag>,
753     ) -> InterpResult<'tcx, i32> {
754         let this = self.eval_context_mut();
755
756         this.check_no_isolation("rmdir")?;
757
758         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
759
760         let result = remove_dir(path).map(|_| 0i32);
761
762         this.try_unwrap_io_result(result)
763     }
764 }
765
766 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
767 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
768 /// epoch.
769 fn extract_sec_and_nsec<'tcx>(
770     time: std::io::Result<SystemTime>
771 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
772     time.ok().map(|time| {
773         let duration = system_time_to_duration(&time)?;
774         Ok((duration.as_secs(), duration.subsec_nanos()))
775     }).transpose()
776 }
777
778 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
779 /// shims.
780 struct FileMetadata {
781     mode: Scalar<Tag>,
782     size: u64,
783     created: Option<(u64, u32)>,
784     accessed: Option<(u64, u32)>,
785     modified: Option<(u64, u32)>,
786 }
787
788 impl FileMetadata {
789     fn from_path<'tcx, 'mir>(
790         ecx: &mut MiriEvalContext<'mir, 'tcx>,
791         path: PathBuf,
792         follow_symlink: bool
793     ) -> InterpResult<'tcx, Option<FileMetadata>> {
794         let metadata = if follow_symlink {
795             std::fs::metadata(path)
796         } else {
797             std::fs::symlink_metadata(path)
798         };
799
800         FileMetadata::from_meta(ecx, metadata)
801     }
802
803     fn from_fd<'tcx, 'mir>(
804         ecx: &mut MiriEvalContext<'mir, 'tcx>,
805         fd: i32,
806     ) -> InterpResult<'tcx, Option<FileMetadata>> {
807         let option = ecx.machine.file_handler.handles.get(&fd);
808         let file = match option {
809             Some(FileHandle { file, writable: _ }) => file,
810             None => return ecx.handle_not_found().map(|_: i32| None),
811         };
812         let metadata = file.metadata();
813
814         FileMetadata::from_meta(ecx, metadata)
815     }
816
817     fn from_meta<'tcx, 'mir>(
818         ecx: &mut MiriEvalContext<'mir, 'tcx>,
819         metadata: Result<std::fs::Metadata, std::io::Error>,
820     ) -> InterpResult<'tcx, Option<FileMetadata>> {
821         let metadata = match metadata {
822             Ok(metadata) => metadata,
823             Err(e) => {
824                 ecx.set_last_error_from_io_error(e)?;
825                 return Ok(None);
826             }
827         };
828
829         let file_type = metadata.file_type();
830
831         let mode_name = if file_type.is_file() {
832             "S_IFREG"
833         } else if file_type.is_dir() {
834             "S_IFDIR"
835         } else {
836             "S_IFLNK"
837         };
838
839         let mode = ecx.eval_libc(mode_name)?;
840
841         let size = metadata.len();
842
843         let created = extract_sec_and_nsec(metadata.created())?;
844         let accessed = extract_sec_and_nsec(metadata.accessed())?;
845         let modified = extract_sec_and_nsec(metadata.modified())?;
846
847         // FIXME: Provide more fields using platform specific methods.
848         Ok(Some(FileMetadata { mode, size, created, accessed, modified }))
849     }
850 }