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