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