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