]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
Auto merge of #1129 - christianpoveda:stat64-shim, r=RalfJung
[rust.git] / src / shims / fs.rs
1 use std::collections::HashMap;
2 use std::convert::{TryFrom, TryInto};
3 use std::fs::{remove_file, File, OpenOptions};
4 use std::io::{Read, Write};
5 use std::path::PathBuf;
6 use std::time::SystemTime;
7
8 use rustc::ty::layout::{Align, LayoutOf, Size};
9
10 use crate::stacked_borrows::Tag;
11 use crate::*;
12 use helpers::immty_from_uint_checked;
13 use shims::time::system_time_to_duration;
14
15 #[derive(Debug)]
16 pub struct FileHandle {
17     file: File,
18 }
19
20 pub struct FileHandler {
21     handles: HashMap<i32, FileHandle>,
22     low: i32,
23 }
24
25 impl Default for FileHandler {
26     fn default() -> Self {
27         FileHandler {
28             handles: Default::default(),
29             // 0, 1 and 2 are reserved for stdin, stdout and stderr.
30             low: 3,
31         }
32     }
33 }
34
35 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
36 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
37     fn open(
38         &mut self,
39         path_op: OpTy<'tcx, Tag>,
40         flag_op: OpTy<'tcx, Tag>,
41     ) -> InterpResult<'tcx, i32> {
42         let this = self.eval_context_mut();
43
44         this.check_no_isolation("open")?;
45
46         let flag = this.read_scalar(flag_op)?.to_i32()?;
47
48         let mut options = OpenOptions::new();
49
50         let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
51         let o_wronly = this.eval_libc_i32("O_WRONLY")?;
52         let o_rdwr = this.eval_libc_i32("O_RDWR")?;
53         // The first two bits of the flag correspond to the access mode in linux, macOS and
54         // windows. We need to check that in fact the access mode flags for the current platform
55         // only use these two bits, otherwise we are in an unsupported platform and should error.
56         if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
57             throw_unsup_format!("Access mode flags on this platform are unsupported");
58         }
59         // Now we check the access mode
60         let access_mode = flag & 0b11;
61
62         if access_mode == o_rdonly {
63             options.read(true);
64         } else if access_mode == o_wronly {
65             options.write(true);
66         } else if access_mode == o_rdwr {
67             options.read(true).write(true);
68         } else {
69             throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
70         }
71         // We need to check that there aren't unsupported options in `flag`. For this we try to
72         // reproduce the content of `flag` in the `mirror` variable using only the supported
73         // options.
74         let mut mirror = access_mode;
75
76         let o_append = this.eval_libc_i32("O_APPEND")?;
77         if flag & o_append != 0 {
78             options.append(true);
79             mirror |= o_append;
80         }
81         let o_trunc = this.eval_libc_i32("O_TRUNC")?;
82         if flag & o_trunc != 0 {
83             options.truncate(true);
84             mirror |= o_trunc;
85         }
86         let o_creat = this.eval_libc_i32("O_CREAT")?;
87         if flag & o_creat != 0 {
88             options.create(true);
89             mirror |= o_creat;
90         }
91         let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
92         if flag & o_cloexec != 0 {
93             // We do not need to do anything for this flag because `std` already sets it.
94             // (Technically we do not support *not* setting this flag, but we ignore that.)
95             mirror |= o_cloexec;
96         }
97         // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
98         // then we throw an error.
99         if flag != mirror {
100             throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
101         }
102
103         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
104
105         let fd = options.open(&path).map(|file| {
106             let mut fh = &mut this.machine.file_handler;
107             fh.low += 1;
108             fh.handles.insert(fh.low, FileHandle { file }).unwrap_none();
109             fh.low
110         });
111
112         this.try_unwrap_io_result(fd)
113     }
114
115     fn fcntl(
116         &mut self,
117         fd_op: OpTy<'tcx, Tag>,
118         cmd_op: OpTy<'tcx, Tag>,
119         _arg1_op: Option<OpTy<'tcx, Tag>>,
120     ) -> InterpResult<'tcx, i32> {
121         let this = self.eval_context_mut();
122
123         this.check_no_isolation("fcntl")?;
124
125         let fd = this.read_scalar(fd_op)?.to_i32()?;
126         let cmd = this.read_scalar(cmd_op)?.to_i32()?;
127         // We only support getting the flags for a descriptor.
128         if cmd == this.eval_libc_i32("F_GETFD")? {
129             // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
130             // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
131             // always sets this flag when opening a file. However we still need to check that the
132             // file itself is open.
133             if this.machine.file_handler.handles.contains_key(&fd) {
134                 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
135             } else {
136                 this.handle_not_found()
137             }
138         } else {
139             throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
140         }
141     }
142
143     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
144         let this = self.eval_context_mut();
145
146         this.check_no_isolation("close")?;
147
148         let fd = this.read_scalar(fd_op)?.to_i32()?;
149
150         if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
151             // `File::sync_all` does the checks that are done when closing a file. We do this to
152             // to handle possible errors correctly.
153             let result = this.try_unwrap_io_result(handle.file.sync_all().map(|_| 0i32));
154             // Now we actually close the file.
155             drop(handle);
156             // And return the result.
157             result
158         } else {
159             this.handle_not_found()
160         }
161     }
162
163     fn read(
164         &mut self,
165         fd_op: OpTy<'tcx, Tag>,
166         buf_op: OpTy<'tcx, Tag>,
167         count_op: OpTy<'tcx, Tag>,
168     ) -> InterpResult<'tcx, i64> {
169         let this = self.eval_context_mut();
170
171         this.check_no_isolation("read")?;
172
173         let fd = this.read_scalar(fd_op)?.to_i32()?;
174         let buf = this.read_scalar(buf_op)?.not_undef()?;
175         let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
176
177         // Check that the *entire* buffer is actually valid memory.
178         this.memory.check_ptr_access(
179             buf,
180             Size::from_bytes(count),
181             Align::from_bytes(1).unwrap(),
182         )?;
183
184         // We cap the number of read bytes to the largest value that we are able to fit in both the
185         // host's and target's `isize`. This saves us from having to handle overflows later.
186         let count = count.min(this.isize_max() as u64).min(isize::max_value() as u64);
187
188         if let Some(handle) = this.machine.file_handler.handles.get_mut(&fd) {
189             // This can never fail because `count` was capped to be smaller than
190             // `isize::max_value()`.
191             let count = isize::try_from(count).unwrap();
192             // We want to read at most `count` bytes. We are sure that `count` is not negative
193             // because it was a target's `usize`. Also we are sure that its smaller than
194             // `usize::max_value()` because it is a host's `isize`.
195             let mut bytes = vec![0; count as usize];
196             let result = handle
197                 .file
198                 .read(&mut bytes)
199                 // `File::read` never returns a value larger than `count`, so this cannot fail.
200                 .map(|c| i64::try_from(c).unwrap());
201
202             match result {
203                 Ok(read_bytes) => {
204                     // If reading to `bytes` did not fail, we write those bytes to the buffer.
205                     this.memory.write_bytes(buf, bytes)?;
206                     Ok(read_bytes)
207                 }
208                 Err(e) => {
209                     this.set_last_error_from_io_error(e)?;
210                     Ok(-1)
211                 }
212             }
213         } else {
214             this.handle_not_found()
215         }
216     }
217
218     fn write(
219         &mut self,
220         fd_op: OpTy<'tcx, Tag>,
221         buf_op: OpTy<'tcx, Tag>,
222         count_op: OpTy<'tcx, Tag>,
223     ) -> InterpResult<'tcx, i64> {
224         let this = self.eval_context_mut();
225
226         this.check_no_isolation("write")?;
227
228         let fd = this.read_scalar(fd_op)?.to_i32()?;
229         let buf = this.read_scalar(buf_op)?.not_undef()?;
230         let count = this.read_scalar(count_op)?.to_machine_usize(&*this.tcx)?;
231
232         // Check that the *entire* buffer is actually valid memory.
233         this.memory.check_ptr_access(
234             buf,
235             Size::from_bytes(count),
236             Align::from_bytes(1).unwrap(),
237         )?;
238
239         // We cap the number of written bytes to the largest value that we are able to fit in both the
240         // host's and target's `isize`. This saves us from having to handle overflows later.
241         let count = count.min(this.isize_max() as u64).min(isize::max_value() as u64);
242
243         if let Some(handle) = this.machine.file_handler.handles.get_mut(&fd) {
244             let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
245             let result = handle.file.write(&bytes).map(|c| i64::try_from(c).unwrap());
246             this.try_unwrap_io_result(result)
247         } else {
248             this.handle_not_found()
249         }
250     }
251
252     fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
253         let this = self.eval_context_mut();
254
255         this.check_no_isolation("unlink")?;
256
257         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
258
259         let result = remove_file(path).map(|_| 0);
260
261         this.try_unwrap_io_result(result)
262     }
263
264     fn stat(
265         &mut self,
266         path_op: OpTy<'tcx, Tag>,
267         buf_op: OpTy<'tcx, Tag>,
268     ) -> InterpResult<'tcx, i32> {
269         let this = self.eval_context_mut();
270
271         if this.tcx.sess.target.target.target_os.to_lowercase() != "macos" {
272             throw_unsup_format!("The `stat` shim is only available for `macos` targets.")
273         }
274
275         let path_scalar = this.read_scalar(path_op)?.not_undef()?;
276         let path: PathBuf = this.read_os_str_from_c_str(path_scalar)?.into();
277
278         let buf = this.deref_operand(buf_op)?;
279
280         // `stat` always follows symlinks. `lstat` is used to get symlink metadata.
281         let metadata = match FileMetadata::new(this, path, true)? {
282             Some(metadata) => metadata,
283             None => return Ok(-1),
284         };
285
286         // FIXME: use Scalar::to_u16
287         let mode: u16 = metadata.mode.to_bits(Size::from_bits(16))? as u16;
288
289         let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
290         let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
291         let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
292
293         let dev_t_layout = this.libc_ty_layout("dev_t")?;
294         let mode_t_layout = this.libc_ty_layout("mode_t")?;
295         let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
296         let ino_t_layout = this.libc_ty_layout("ino_t")?;
297         let uid_t_layout = this.libc_ty_layout("uid_t")?;
298         let gid_t_layout = this.libc_ty_layout("gid_t")?;
299         let time_t_layout = this.libc_ty_layout("time_t")?;
300         let long_layout = this.libc_ty_layout("c_long")?;
301         let off_t_layout = this.libc_ty_layout("off_t")?;
302         let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
303         let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
304         let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
305
306         // We need to add 32 bits of padding after `st_rdev` if we are on a 64-bit platform.
307         let pad_layout = if this.tcx.sess.target.ptr_width == 64 {
308             uint32_t_layout
309         } else {
310             this.layout_of(this.tcx.mk_unit())?
311         };
312
313         let imms = [
314             immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
315             immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
316             immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
317             immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
318             immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
319             immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
320             immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
321             immty_from_uint_checked(0u128, pad_layout)?, // padding for 64-bit targets
322             immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
323             immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
324             immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
325             immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
326             immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
327             immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
328             immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
329             immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
330             immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
331             immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
332             immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
333             immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
334             immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
335         ];
336
337         this.write_packed_immediates(&buf, &imms)?;
338
339         Ok(0)
340     }
341
342     fn statx(
343         &mut self,
344         dirfd_op: OpTy<'tcx, Tag>,    // Should be an `int`
345         pathname_op: OpTy<'tcx, Tag>, // Should be a `const char *`
346         flags_op: OpTy<'tcx, Tag>,    // Should be an `int`
347         _mask_op: OpTy<'tcx, Tag>,    // Should be an `unsigned int`
348         statxbuf_op: OpTy<'tcx, Tag>, // Should be a `struct statx *`
349     ) -> InterpResult<'tcx, i32> {
350         let this = self.eval_context_mut();
351
352         this.check_no_isolation("statx")?;
353
354         if this.tcx.sess.target.target.target_os.to_lowercase() != "linux" {
355             throw_unsup_format!("The `statx` shim is only available for `linux` targets.")
356         }
357
358         let statxbuf_scalar = this.read_scalar(statxbuf_op)?.not_undef()?;
359         let pathname_scalar = this.read_scalar(pathname_op)?.not_undef()?;
360
361         // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
362         if this.is_null(statxbuf_scalar)? || this.is_null(pathname_scalar)? {
363             let efault = this.eval_libc("EFAULT")?;
364             this.set_last_error(efault)?;
365             return Ok(-1);
366         }
367
368         // Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
369         // proper `MemPlace` and then write the results of this function to it. However, the
370         // `syscall` function is untyped. This means that all the `statx` parameters are provided
371         // as `isize`s instead of having the proper types. Thus, we have to recover the layout of
372         // `statxbuf_op` by using the `libc::statx` struct type.
373         let statxbuf_place = {
374             // FIXME: This long path is required because `libc::statx` is an struct and also a
375             // function and `resolve_path` is returning the latter.
376             let statx_ty = this
377                 .resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])?
378                 .ty(*this.tcx);
379             let statxbuf_ty = this.tcx.mk_mut_ptr(statx_ty);
380             let statxbuf_layout = this.layout_of(statxbuf_ty)?;
381             let statxbuf_imm = ImmTy::from_scalar(statxbuf_scalar, statxbuf_layout);
382             this.ref_to_mplace(statxbuf_imm)?
383         };
384
385         let path: PathBuf = this.read_os_str_from_c_str(pathname_scalar)?.into();
386         // `flags` should be a `c_int` but the `syscall` function provides an `isize`.
387         let flags: i32 =
388             this.read_scalar(flags_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
389                 err_unsup_format!("Failed to convert pointer sized operand to integer: {}", e)
390             })?;
391         // `dirfd` should be a `c_int` but the `syscall` function provides an `isize`.
392         let dirfd: i32 =
393             this.read_scalar(dirfd_op)?.to_machine_isize(&*this.tcx)?.try_into().map_err(|e| {
394                 err_unsup_format!("Failed to convert pointer sized operand to integer: {}", e)
395             })?;
396         // we only support interpreting `path` as an absolute directory or as a directory relative
397         // to `dirfd` when the latter is `AT_FDCWD`. The behavior of `statx` with a relative path
398         // and a directory file descriptor other than `AT_FDCWD` is specified but it cannot be
399         // tested from `libstd`. If you found this error, please open an issue reporting it.
400         if !(path.is_absolute() || dirfd == this.eval_libc_i32("AT_FDCWD")?) {
401             throw_unsup_format!(
402                 "Using statx with a relative path and a file descriptor different from `AT_FDCWD` is not supported"
403             )
404         }
405
406         // the `_mask_op` paramter specifies the file information that the caller requested.
407         // However `statx` is allowed to return information that was not requested or to not
408         // return information that was requested. This `mask` represents the information we can
409         // actually provide in any host platform.
410         let mut mask =
411             this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
412
413         // If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
414         // symbolic links.
415         let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
416
417         let metadata = match FileMetadata::new(this, path, follow_symlink)? {
418             Some(metadata) => metadata,
419             None => return Ok(-1),
420         };
421
422         // The `mode` field specifies the type of the file and the permissions over the file for
423         // the owner, its group and other users. Given that we can only provide the file type
424         // without using platform specific methods, we only set the bits corresponding to the file
425         // type. This should be an `__u16` but `libc` provides its values as `u32`.
426         let mode: u16 = metadata
427             .mode
428             .to_u32()?
429             .try_into()
430             .unwrap_or_else(|_| bug!("libc contains bad value for constant"));
431
432         // We need to set the corresponding bits of `mask` if the access, creation and modification
433         // times were available. Otherwise we let them be zero.
434         let (access_sec, access_nsec) = metadata.accessed.map(|tup| {
435             mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
436             InterpResult::Ok(tup)
437         }).unwrap_or(Ok((0, 0)))?;
438
439         let (created_sec, created_nsec) = metadata.created.map(|tup| {
440             mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
441             InterpResult::Ok(tup)
442         }).unwrap_or(Ok((0, 0)))?;
443
444         let (modified_sec, modified_nsec) = metadata.modified.map(|tup| {
445             mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
446             InterpResult::Ok(tup)
447         }).unwrap_or(Ok((0, 0)))?;
448
449         let __u32_layout = this.libc_ty_layout("__u32")?;
450         let __u64_layout = this.libc_ty_layout("__u64")?;
451         let __u16_layout = this.libc_ty_layout("__u16")?;
452
453         // Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
454         // zero for the unavailable fields.
455         let imms = [
456             immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
457             immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
458             immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
459             immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
460             immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
461             immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
462             immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
463             immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
464             immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
465             immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
466             immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
467             immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
468             immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
469             immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
470             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
471             immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
472             immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
473             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
474             immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
475             immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
476             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
477             immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
478             immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
479             immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
480             immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
481             immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
482             immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
483             immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
484         ];
485
486         this.write_packed_immediates(&statxbuf_place, &imms)?;
487
488         Ok(0)
489     }
490
491     /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
492     /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
493     /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
494     /// types (like `read`, that returns an `i64`).
495     fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
496         let this = self.eval_context_mut();
497         let ebadf = this.eval_libc("EBADF")?;
498         this.set_last_error(ebadf)?;
499         Ok((-1).into())
500     }
501 }
502
503 /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
504 /// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
505 /// epoch.
506 fn extract_sec_and_nsec<'tcx>(
507     time: std::io::Result<SystemTime>
508 ) -> InterpResult<'tcx, Option<(u64, u32)>> {
509     time.ok().map(|time| {
510         let duration = system_time_to_duration(&time)?;
511         Ok((duration.as_secs(), duration.subsec_nanos()))
512     }).transpose()
513 }
514
515 /// Stores a file's metadata in order to avoid code duplication in the different metadata related
516 /// shims.
517 struct FileMetadata {
518     mode: Scalar<Tag>,
519     size: u64,
520     created: Option<(u64, u32)>,
521     accessed: Option<(u64, u32)>,
522     modified: Option<(u64, u32)>,
523 }
524
525 impl FileMetadata {
526     fn new<'tcx, 'mir>(
527         ecx: &mut MiriEvalContext<'mir, 'tcx>,
528         path: PathBuf,
529         follow_symlink: bool
530     ) -> InterpResult<'tcx, Option<FileMetadata>> {
531         let metadata = if follow_symlink {
532             std::fs::metadata(path)
533         } else {
534             // FIXME: metadata for symlinks need testing.
535             std::fs::symlink_metadata(path)
536         };
537
538         let metadata = match metadata {
539             Ok(metadata) => metadata,
540             Err(e) => {
541                 ecx.set_last_error_from_io_error(e)?;
542                 return Ok(None);
543             }
544         };
545
546         let file_type = metadata.file_type();
547
548         let mode_name = if file_type.is_file() {
549             "S_IFREG"
550         } else if file_type.is_dir() {
551             "S_IFDIR"
552         } else {
553             "S_IFLNK"
554         };
555
556         let mode = ecx.eval_libc(mode_name)?;
557
558         let size = metadata.len();
559
560         let created = extract_sec_and_nsec(metadata.created())?;
561         let accessed = extract_sec_and_nsec(metadata.accessed())?;
562         let modified = extract_sec_and_nsec(metadata.modified())?;
563
564         // FIXME: Provide more fields using platform specific methods.
565         Ok(Some(FileMetadata { mode, size, created, accessed, modified }))
566     }
567 }