-
Notifications
You must be signed in to change notification settings - Fork 358
/
Copy pathfs.rs
1751 lines (1523 loc) · 69 KB
/
fs.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! File and file system access
use std::borrow::Cow;
use std::fs::{
DirBuilder, File, FileType, Metadata, OpenOptions, ReadDir, read_dir, remove_dir, remove_file,
rename,
};
use std::io::{self, ErrorKind, IsTerminal, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use rustc_abi::Size;
use rustc_data_structures::fx::FxHashMap;
use self::shims::time::system_time_to_duration;
use crate::helpers::check_min_vararg_count;
use crate::shims::files::{EvalContextExt as _, FileDescription, FileDescriptionRef};
use crate::shims::os_str::bytes_to_os_str;
use crate::shims::unix::fd::{FlockOp, UnixFileDescription};
use crate::*;
#[derive(Debug)]
struct FileHandle {
file: File,
writable: bool,
}
impl FileDescription for FileHandle {
fn name(&self) -> &'static str {
"file"
}
fn read<'tcx>(
self: FileDescriptionRef<Self>,
communicate_allowed: bool,
ptr: Pointer,
len: usize,
ecx: &mut MiriInterpCx<'tcx>,
finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
) -> InterpResult<'tcx> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
let result = ecx.read_from_host(&self.file, len, ptr)?;
finish.call(ecx, result)
}
fn write<'tcx>(
self: FileDescriptionRef<Self>,
communicate_allowed: bool,
ptr: Pointer,
len: usize,
ecx: &mut MiriInterpCx<'tcx>,
finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
) -> InterpResult<'tcx> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
let result = ecx.write_to_host(&self.file, len, ptr)?;
finish.call(ecx, result)
}
fn seek<'tcx>(
&self,
communicate_allowed: bool,
offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
interp_ok((&mut &self.file).seek(offset))
}
fn close<'tcx>(
self,
communicate_allowed: bool,
_ecx: &mut MiriInterpCx<'tcx>,
) -> InterpResult<'tcx, io::Result<()>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
// We sync the file if it was opened in a mode different than read-only.
if self.writable {
// `File::sync_all` does the checks that are done when closing a file. We do this to
// to handle possible errors correctly.
let result = self.file.sync_all();
// Now we actually close the file and return the result.
drop(self.file);
interp_ok(result)
} else {
// We drop the file, this closes it but ignores any errors
// produced when closing it. This is done because
// `File::sync_all` cannot be done over files like
// `/dev/urandom` which are read-only. Check
// https://github.com/rust-lang/miri/issues/999#issuecomment-568920439
// for a deeper discussion.
drop(self.file);
interp_ok(Ok(()))
}
}
fn metadata<'tcx>(&self) -> InterpResult<'tcx, io::Result<Metadata>> {
interp_ok(self.file.metadata())
}
fn is_tty(&self, communicate_allowed: bool) -> bool {
communicate_allowed && self.file.is_terminal()
}
fn as_unix(&self) -> &dyn UnixFileDescription {
self
}
}
impl UnixFileDescription for FileHandle {
fn pread<'tcx>(
&self,
communicate_allowed: bool,
offset: u64,
ptr: Pointer,
len: usize,
ecx: &mut MiriInterpCx<'tcx>,
finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
) -> InterpResult<'tcx> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
let mut bytes = vec![0; len];
// Emulates pread using seek + read + seek to restore cursor position.
// Correctness of this emulation relies on sequential nature of Miri execution.
// The closure is used to emulate `try` block, since we "bubble" `io::Error` using `?`.
let file = &mut &self.file;
let mut f = || {
let cursor_pos = file.stream_position()?;
file.seek(SeekFrom::Start(offset))?;
let res = file.read(&mut bytes);
// Attempt to restore cursor position even if the read has failed
file.seek(SeekFrom::Start(cursor_pos))
.expect("failed to restore file position, this shouldn't be possible");
res
};
let result = match f() {
Ok(read_size) => {
// If reading to `bytes` did not fail, we write those bytes to the buffer.
// Crucially, if fewer than `bytes.len()` bytes were read, only write
// that much into the output buffer!
ecx.write_bytes_ptr(ptr, bytes[..read_size].iter().copied())?;
Ok(read_size)
}
Err(e) => Err(IoError::HostError(e)),
};
finish.call(ecx, result)
}
fn pwrite<'tcx>(
&self,
communicate_allowed: bool,
ptr: Pointer,
len: usize,
offset: u64,
ecx: &mut MiriInterpCx<'tcx>,
finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
) -> InterpResult<'tcx> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
// Emulates pwrite using seek + write + seek to restore cursor position.
// Correctness of this emulation relies on sequential nature of Miri execution.
// The closure is used to emulate `try` block, since we "bubble" `io::Error` using `?`.
let file = &mut &self.file;
let bytes = ecx.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
let mut f = || {
let cursor_pos = file.stream_position()?;
file.seek(SeekFrom::Start(offset))?;
let res = file.write(bytes);
// Attempt to restore cursor position even if the write has failed
file.seek(SeekFrom::Start(cursor_pos))
.expect("failed to restore file position, this shouldn't be possible");
res
};
let result = f();
finish.call(ecx, result.map_err(IoError::HostError))
}
fn flock<'tcx>(
&self,
communicate_allowed: bool,
op: FlockOp,
) -> InterpResult<'tcx, io::Result<()>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
cfg_match! {
all(target_family = "unix", not(target_os = "solaris")) => {
use std::os::fd::AsRawFd;
use FlockOp::*;
// We always use non-blocking call to prevent interpreter from being blocked
let (host_op, lock_nb) = match op {
SharedLock { nonblocking } => (libc::LOCK_SH | libc::LOCK_NB, nonblocking),
ExclusiveLock { nonblocking } => (libc::LOCK_EX | libc::LOCK_NB, nonblocking),
Unlock => (libc::LOCK_UN, false),
};
let fd = self.file.as_raw_fd();
let ret = unsafe { libc::flock(fd, host_op) };
let res = match ret {
0 => Ok(()),
-1 => {
let err = io::Error::last_os_error();
if !lock_nb && err.kind() == io::ErrorKind::WouldBlock {
throw_unsup_format!("blocking `flock` is not currently supported");
}
Err(err)
}
ret => panic!("Unexpected return value from flock: {ret}"),
};
interp_ok(res)
}
target_family = "windows" => {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::{
ERROR_IO_PENDING, ERROR_LOCK_VIOLATION, FALSE, HANDLE, TRUE,
};
use windows_sys::Win32::Storage::FileSystem::{
LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, UnlockFile,
};
let fh = self.file.as_raw_handle() as HANDLE;
use FlockOp::*;
let (ret, lock_nb) = match op {
SharedLock { nonblocking } | ExclusiveLock { nonblocking } => {
// We always use non-blocking call to prevent interpreter from being blocked
let mut flags = LOCKFILE_FAIL_IMMEDIATELY;
if matches!(op, ExclusiveLock { .. }) {
flags |= LOCKFILE_EXCLUSIVE_LOCK;
}
let ret = unsafe { LockFileEx(fh, flags, 0, !0, !0, &mut std::mem::zeroed()) };
(ret, nonblocking)
}
Unlock => {
let ret = unsafe { UnlockFile(fh, 0, 0, !0, !0) };
(ret, false)
}
};
let res = match ret {
TRUE => Ok(()),
FALSE => {
let mut err = io::Error::last_os_error();
// This only runs on Windows hosts so we can use `raw_os_error`.
// We have to be careful not to forward that error code to target code.
let code: u32 = err.raw_os_error().unwrap().try_into().unwrap();
if matches!(code, ERROR_IO_PENDING | ERROR_LOCK_VIOLATION) {
if lock_nb {
// The io error mapping does not know about these error codes,
// so we translate it to `WouldBlock` manually.
let desc = format!("LockFileEx wouldblock error: {err}");
err = io::Error::new(io::ErrorKind::WouldBlock, desc);
} else {
throw_unsup_format!("blocking `flock` is not currently supported");
}
}
Err(err)
}
_ => panic!("Unexpected return value: {ret}"),
};
interp_ok(res)
}
_ => {
let _ = op;
throw_unsup_format!(
"flock is supported only on UNIX (except Solaris) and Windows hosts"
);
}
}
}
}
impl<'tcx> EvalContextExtPrivate<'tcx> for crate::MiriInterpCx<'tcx> {}
trait EvalContextExtPrivate<'tcx>: crate::MiriInterpCxExt<'tcx> {
fn macos_fbsd_solarish_write_stat_buf(
&mut self,
metadata: FileMetadata,
buf_op: &OpTy<'tcx>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
let mode = metadata.mode.to_uint(this.libc_ty_layout("mode_t").size)?;
let buf = this.deref_pointer_as(buf_op, this.libc_ty_layout("stat"))?;
this.write_int_fields_named(
&[
("st_dev", 0),
("st_mode", mode.try_into().unwrap()),
("st_nlink", 0),
("st_ino", 0),
("st_uid", 0),
("st_gid", 0),
("st_rdev", 0),
("st_atime", access_sec.into()),
("st_mtime", modified_sec.into()),
("st_ctime", 0),
("st_size", metadata.size.into()),
("st_blocks", 0),
("st_blksize", 0),
],
&buf,
)?;
if matches!(&*this.tcx.sess.target.os, "macos" | "freebsd") {
this.write_int_fields_named(
&[
("st_atime_nsec", access_nsec.into()),
("st_mtime_nsec", modified_nsec.into()),
("st_ctime_nsec", 0),
("st_birthtime", created_sec.into()),
("st_birthtime_nsec", created_nsec.into()),
("st_flags", 0),
("st_gen", 0),
],
&buf,
)?;
}
if matches!(&*this.tcx.sess.target.os, "solaris" | "illumos") {
let st_fstype = this.project_field_named(&buf, "st_fstype")?;
// This is an array; write 0 into first element so that it encodes the empty string.
this.write_int(0, &this.project_index(&st_fstype, 0)?)?;
}
interp_ok(0)
}
fn file_type_to_d_type(
&mut self,
file_type: std::io::Result<FileType>,
) -> InterpResult<'tcx, i32> {
#[cfg(unix)]
use std::os::unix::fs::FileTypeExt;
let this = self.eval_context_mut();
match file_type {
Ok(file_type) => {
match () {
_ if file_type.is_dir() => interp_ok(this.eval_libc("DT_DIR").to_u8()?.into()),
_ if file_type.is_file() => interp_ok(this.eval_libc("DT_REG").to_u8()?.into()),
_ if file_type.is_symlink() =>
interp_ok(this.eval_libc("DT_LNK").to_u8()?.into()),
// Certain file types are only supported when the host is a Unix system.
#[cfg(unix)]
_ if file_type.is_block_device() =>
interp_ok(this.eval_libc("DT_BLK").to_u8()?.into()),
#[cfg(unix)]
_ if file_type.is_char_device() =>
interp_ok(this.eval_libc("DT_CHR").to_u8()?.into()),
#[cfg(unix)]
_ if file_type.is_fifo() =>
interp_ok(this.eval_libc("DT_FIFO").to_u8()?.into()),
#[cfg(unix)]
_ if file_type.is_socket() =>
interp_ok(this.eval_libc("DT_SOCK").to_u8()?.into()),
// Fallback
_ => interp_ok(this.eval_libc("DT_UNKNOWN").to_u8()?.into()),
}
}
Err(_) => {
// Fallback on error
interp_ok(this.eval_libc("DT_UNKNOWN").to_u8()?.into())
}
}
}
}
/// An open directory, tracked by DirHandler.
#[derive(Debug)]
struct OpenDir {
/// The directory reader on the host.
read_dir: ReadDir,
/// The most recent entry returned by readdir().
/// Will be freed by the next call.
entry: Option<Pointer>,
}
impl OpenDir {
fn new(read_dir: ReadDir) -> Self {
Self { read_dir, entry: None }
}
}
/// The table of open directories.
/// Curiously, Unix/POSIX does not unify this into the "file descriptor" concept... everything
/// is a file, except a directory is not?
#[derive(Debug)]
pub struct DirTable {
/// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
/// and closedir.
///
/// When opendir is called, a directory iterator is created on the host for the target
/// directory, and an entry is stored in this hash map, indexed by an ID which represents
/// the directory stream. When readdir is called, the directory stream ID is used to look up
/// the corresponding ReadDir iterator from this map, and information from the next
/// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
/// the map.
streams: FxHashMap<u64, OpenDir>,
/// ID number to be used by the next call to opendir
next_id: u64,
}
impl DirTable {
#[expect(clippy::arithmetic_side_effects)]
fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
let id = self.next_id;
self.next_id += 1;
self.streams.try_insert(id, OpenDir::new(read_dir)).unwrap();
id
}
}
impl Default for DirTable {
fn default() -> DirTable {
DirTable {
streams: FxHashMap::default(),
// Skip 0 as an ID, because it looks like a null pointer to libc
next_id: 1,
}
}
}
impl VisitProvenance for DirTable {
fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
let DirTable { streams, next_id: _ } = self;
for dir in streams.values() {
dir.entry.visit_provenance(visit);
}
}
}
fn maybe_sync_file(
file: &File,
writable: bool,
operation: fn(&File) -> std::io::Result<()>,
) -> std::io::Result<i32> {
if !writable && cfg!(windows) {
// sync_all() and sync_data() will return an error on Windows hosts if the file is not opened
// for writing. (FlushFileBuffers requires that the file handle have the
// GENERIC_WRITE right)
Ok(0i32)
} else {
let result = operation(file);
result.map(|_| 0i32)
}
}
impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
fn open(
&mut self,
path_raw: &OpTy<'tcx>,
flag: &OpTy<'tcx>,
varargs: &[OpTy<'tcx>],
) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
let path_raw = this.read_pointer(path_raw)?;
let path = this.read_path_from_c_str(path_raw)?;
let flag = this.read_scalar(flag)?.to_i32()?;
let mut options = OpenOptions::new();
let o_rdonly = this.eval_libc_i32("O_RDONLY");
let o_wronly = this.eval_libc_i32("O_WRONLY");
let o_rdwr = this.eval_libc_i32("O_RDWR");
// The first two bits of the flag correspond to the access mode in linux, macOS and
// windows. We need to check that in fact the access mode flags for the current target
// only use these two bits, otherwise we are in an unsupported target and should error.
if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
throw_unsup_format!("access mode flags on this target are unsupported");
}
let mut writable = true;
// Now we check the access mode
let access_mode = flag & 0b11;
if access_mode == o_rdonly {
writable = false;
options.read(true);
} else if access_mode == o_wronly {
options.write(true);
} else if access_mode == o_rdwr {
options.read(true).write(true);
} else {
throw_unsup_format!("unsupported access mode {:#x}", access_mode);
}
// We need to check that there aren't unsupported options in `flag`. For this we try to
// reproduce the content of `flag` in the `mirror` variable using only the supported
// options.
let mut mirror = access_mode;
let o_append = this.eval_libc_i32("O_APPEND");
if flag & o_append == o_append {
options.append(true);
mirror |= o_append;
}
let o_trunc = this.eval_libc_i32("O_TRUNC");
if flag & o_trunc == o_trunc {
options.truncate(true);
mirror |= o_trunc;
}
let o_creat = this.eval_libc_i32("O_CREAT");
if flag & o_creat == o_creat {
// Get the mode. On macOS, the argument type `mode_t` is actually `u16`, but
// C integer promotion rules mean that on the ABI level, it gets passed as `u32`
// (see https://github.com/rust-lang/rust/issues/71915).
let [mode] = check_min_vararg_count("open(pathname, O_CREAT, ...)", varargs)?;
let mode = this.read_scalar(mode)?.to_u32()?;
#[cfg(unix)]
{
// Support all modes on UNIX host
use std::os::unix::fs::OpenOptionsExt;
options.mode(mode);
}
#[cfg(not(unix))]
{
// Only support default mode for non-UNIX (i.e. Windows) host
if mode != 0o666 {
throw_unsup_format!(
"non-default mode 0o{:o} is not supported on non-Unix hosts",
mode
);
}
}
mirror |= o_creat;
let o_excl = this.eval_libc_i32("O_EXCL");
if flag & o_excl == o_excl {
mirror |= o_excl;
options.create_new(true);
} else {
options.create(true);
}
}
let o_cloexec = this.eval_libc_i32("O_CLOEXEC");
if flag & o_cloexec == o_cloexec {
// We do not need to do anything for this flag because `std` already sets it.
// (Technically we do not support *not* setting this flag, but we ignore that.)
mirror |= o_cloexec;
}
if this.tcx.sess.target.os == "linux" {
let o_tmpfile = this.eval_libc_i32("O_TMPFILE");
if flag & o_tmpfile == o_tmpfile {
// if the flag contains `O_TMPFILE` then we return a graceful error
return this.set_last_error_and_return_i32(LibcError("EOPNOTSUPP"));
}
}
let o_nofollow = this.eval_libc_i32("O_NOFOLLOW");
if flag & o_nofollow == o_nofollow {
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW);
}
// Strictly speaking, this emulation is not equivalent to the O_NOFOLLOW flag behavior:
// the path could change between us checking it here and the later call to `open`.
// But it's good enough for Miri purposes.
#[cfg(not(unix))]
{
// O_NOFOLLOW only fails when the trailing component is a symlink;
// the entire rest of the path can still contain symlinks.
if path.is_symlink() {
return this.set_last_error_and_return_i32(LibcError("ELOOP"));
}
}
mirror |= o_nofollow;
}
// If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
// then we throw an error.
if flag != mirror {
throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
}
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`open`", reject_with)?;
return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
}
let fd = options
.open(path)
.map(|file| this.machine.fds.insert_new(FileHandle { file, writable }));
interp_ok(Scalar::from_i32(this.try_unwrap_io_result(fd)?))
}
fn lseek64(&mut self, fd_num: i32, offset: i128, whence: i32) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
// Isolation check is done via `FileDescription` trait.
let seek_from = if whence == this.eval_libc_i32("SEEK_SET") {
if offset < 0 {
// Negative offsets return `EINVAL`.
return this.set_last_error_and_return_i64(LibcError("EINVAL"));
} else {
SeekFrom::Start(u64::try_from(offset).unwrap())
}
} else if whence == this.eval_libc_i32("SEEK_CUR") {
SeekFrom::Current(i64::try_from(offset).unwrap())
} else if whence == this.eval_libc_i32("SEEK_END") {
SeekFrom::End(i64::try_from(offset).unwrap())
} else {
return this.set_last_error_and_return_i64(LibcError("EINVAL"));
};
let communicate = this.machine.communicate();
let Some(fd) = this.machine.fds.get(fd_num) else {
return this.set_last_error_and_return_i64(LibcError("EBADF"));
};
let result = fd.seek(communicate, seek_from)?.map(|offset| i64::try_from(offset).unwrap());
drop(fd);
let result = this.try_unwrap_io_result(result)?;
interp_ok(Scalar::from_i64(result))
}
fn unlink(&mut self, path_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`unlink`", reject_with)?;
return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
}
let result = remove_file(path).map(|_| 0);
interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
}
fn symlink(
&mut self,
target_op: &OpTy<'tcx>,
linkpath_op: &OpTy<'tcx>,
) -> InterpResult<'tcx, Scalar> {
#[cfg(unix)]
fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
#[cfg(windows)]
fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
use std::os::windows::fs;
if src.is_dir() { fs::symlink_dir(src, dst) } else { fs::symlink_file(src, dst) }
}
let this = self.eval_context_mut();
let target = this.read_path_from_c_str(this.read_pointer(target_op)?)?;
let linkpath = this.read_path_from_c_str(this.read_pointer(linkpath_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`symlink`", reject_with)?;
return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
}
let result = create_link(&target, &linkpath).map(|_| 0);
interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
}
fn macos_fbsd_solarish_stat(
&mut self,
path_op: &OpTy<'tcx>,
buf_op: &OpTy<'tcx>,
) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
if !matches!(&*this.tcx.sess.target.os, "macos" | "freebsd" | "solaris" | "illumos") {
panic!("`macos_fbsd_solaris_stat` should not be called on {}", this.tcx.sess.target.os);
}
let path_scalar = this.read_pointer(path_op)?;
let path = this.read_path_from_c_str(path_scalar)?.into_owned();
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`stat`", reject_with)?;
return this.set_last_error_and_return_i32(LibcError("EACCES"));
}
// `stat` always follows symlinks.
let metadata = match FileMetadata::from_path(this, &path, true)? {
Ok(metadata) => metadata,
Err(err) => return this.set_last_error_and_return_i32(err),
};
interp_ok(Scalar::from_i32(this.macos_fbsd_solarish_write_stat_buf(metadata, buf_op)?))
}
// `lstat` is used to get symlink metadata.
fn macos_fbsd_solarish_lstat(
&mut self,
path_op: &OpTy<'tcx>,
buf_op: &OpTy<'tcx>,
) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
if !matches!(&*this.tcx.sess.target.os, "macos" | "freebsd" | "solaris" | "illumos") {
panic!(
"`macos_fbsd_solaris_lstat` should not be called on {}",
this.tcx.sess.target.os
);
}
let path_scalar = this.read_pointer(path_op)?;
let path = this.read_path_from_c_str(path_scalar)?.into_owned();
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`lstat`", reject_with)?;
return this.set_last_error_and_return_i32(LibcError("EACCES"));
}
let metadata = match FileMetadata::from_path(this, &path, false)? {
Ok(metadata) => metadata,
Err(err) => return this.set_last_error_and_return_i32(err),
};
interp_ok(Scalar::from_i32(this.macos_fbsd_solarish_write_stat_buf(metadata, buf_op)?))
}
fn macos_fbsd_solarish_fstat(
&mut self,
fd_op: &OpTy<'tcx>,
buf_op: &OpTy<'tcx>,
) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
if !matches!(&*this.tcx.sess.target.os, "macos" | "freebsd" | "solaris" | "illumos") {
panic!(
"`macos_fbsd_solaris_fstat` should not be called on {}",
this.tcx.sess.target.os
);
}
let fd = this.read_scalar(fd_op)?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fstat`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.set_last_error_and_return_i32(LibcError("EBADF"));
}
let metadata = match FileMetadata::from_fd_num(this, fd)? {
Ok(metadata) => metadata,
Err(err) => return this.set_last_error_and_return_i32(err),
};
interp_ok(Scalar::from_i32(this.macos_fbsd_solarish_write_stat_buf(metadata, buf_op)?))
}
fn linux_statx(
&mut self,
dirfd_op: &OpTy<'tcx>, // Should be an `int`
pathname_op: &OpTy<'tcx>, // Should be a `const char *`
flags_op: &OpTy<'tcx>, // Should be an `int`
mask_op: &OpTy<'tcx>, // Should be an `unsigned int`
statxbuf_op: &OpTy<'tcx>, // Should be a `struct statx *`
) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
this.assert_target_os("linux", "statx");
let dirfd = this.read_scalar(dirfd_op)?.to_i32()?;
let pathname_ptr = this.read_pointer(pathname_op)?;
let flags = this.read_scalar(flags_op)?.to_i32()?;
let _mask = this.read_scalar(mask_op)?.to_u32()?;
let statxbuf_ptr = this.read_pointer(statxbuf_op)?;
// If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
if this.ptr_is_null(statxbuf_ptr)? || this.ptr_is_null(pathname_ptr)? {
return this.set_last_error_and_return_i32(LibcError("EFAULT"));
}
let statxbuf = this.deref_pointer_as(statxbuf_op, this.libc_ty_layout("statx"))?;
let path = this.read_path_from_c_str(pathname_ptr)?.into_owned();
// See <https://github.com/rust-lang/rust/pull/79196> for a discussion of argument sizes.
let at_empty_path = this.eval_libc_i32("AT_EMPTY_PATH");
let empty_path_flag = flags & at_empty_path == at_empty_path;
// We only support:
// * interpreting `path` as an absolute directory,
// * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
// * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
// set.
// Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
// found this error, please open an issue reporting it.
if !(path.is_absolute()
|| dirfd == this.eval_libc_i32("AT_FDCWD")
|| (path.as_os_str().is_empty() && empty_path_flag))
{
throw_unsup_format!(
"using statx is only supported with absolute paths, relative paths with the file \
descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
file descriptor"
)
}
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`statx`", reject_with)?;
let ecode = if path.is_absolute() || dirfd == this.eval_libc_i32("AT_FDCWD") {
// since `path` is provided, either absolute or
// relative to CWD, `EACCES` is the most relevant.
LibcError("EACCES")
} else {
// `dirfd` is set to target file, and `path` is empty
// (or we would have hit the `throw_unsup_format`
// above). `EACCES` would violate the spec.
assert!(empty_path_flag);
LibcError("EBADF")
};
return this.set_last_error_and_return_i32(ecode);
}
// the `_mask_op` parameter specifies the file information that the caller requested.
// However `statx` is allowed to return information that was not requested or to not
// return information that was requested. This `mask` represents the information we can
// actually provide for any target.
let mut mask = this.eval_libc_u32("STATX_TYPE") | this.eval_libc_u32("STATX_SIZE");
// If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
// symbolic links.
let follow_symlink = flags & this.eval_libc_i32("AT_SYMLINK_NOFOLLOW") == 0;
// If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
// represented by dirfd, whether it's a directory or otherwise.
let metadata = if path.as_os_str().is_empty() && empty_path_flag {
FileMetadata::from_fd_num(this, dirfd)?
} else {
FileMetadata::from_path(this, &path, follow_symlink)?
};
let metadata = match metadata {
Ok(metadata) => metadata,
Err(err) => return this.set_last_error_and_return_i32(err),
};
// The `mode` field specifies the type of the file and the permissions over the file for
// the owner, its group and other users. Given that we can only provide the file type
// without using platform specific methods, we only set the bits corresponding to the file
// type. This should be an `__u16` but `libc` provides its values as `u32`.
let mode: u16 = metadata
.mode
.to_u32()?
.try_into()
.unwrap_or_else(|_| bug!("libc contains bad value for constant"));
// We need to set the corresponding bits of `mask` if the access, creation and modification
// times were available. Otherwise we let them be zero.
let (access_sec, access_nsec) = metadata
.accessed
.map(|tup| {
mask |= this.eval_libc_u32("STATX_ATIME");
interp_ok(tup)
})
.unwrap_or_else(|| interp_ok((0, 0)))?;
let (created_sec, created_nsec) = metadata
.created
.map(|tup| {
mask |= this.eval_libc_u32("STATX_BTIME");
interp_ok(tup)
})
.unwrap_or_else(|| interp_ok((0, 0)))?;
let (modified_sec, modified_nsec) = metadata
.modified
.map(|tup| {
mask |= this.eval_libc_u32("STATX_MTIME");
interp_ok(tup)
})
.unwrap_or_else(|| interp_ok((0, 0)))?;
// Now we write everything to `statxbuf`. We write a zero for the unavailable fields.
this.write_int_fields_named(
&[
("stx_mask", mask.into()),
("stx_blksize", 0),
("stx_attributes", 0),
("stx_nlink", 0),
("stx_uid", 0),
("stx_gid", 0),
("stx_mode", mode.into()),
("stx_ino", 0),
("stx_size", metadata.size.into()),
("stx_blocks", 0),
("stx_attributes_mask", 0),
("stx_rdev_major", 0),
("stx_rdev_minor", 0),
("stx_dev_major", 0),
("stx_dev_minor", 0),
],
&statxbuf,
)?;
#[rustfmt::skip]
this.write_int_fields_named(
&[
("tv_sec", access_sec.into()),
("tv_nsec", access_nsec.into()),
],
&this.project_field_named(&statxbuf, "stx_atime")?,
)?;
#[rustfmt::skip]
this.write_int_fields_named(
&[
("tv_sec", created_sec.into()),
("tv_nsec", created_nsec.into()),
],
&this.project_field_named(&statxbuf, "stx_btime")?,
)?;
#[rustfmt::skip]
this.write_int_fields_named(
&[
("tv_sec", 0.into()),
("tv_nsec", 0.into()),
],
&this.project_field_named(&statxbuf, "stx_ctime")?,
)?;
#[rustfmt::skip]
this.write_int_fields_named(
&[
("tv_sec", modified_sec.into()),
("tv_nsec", modified_nsec.into()),
],
&this.project_field_named(&statxbuf, "stx_mtime")?,
)?;
interp_ok(Scalar::from_i32(0))
}
fn rename(
&mut self,
oldpath_op: &OpTy<'tcx>,
newpath_op: &OpTy<'tcx>,
) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
let oldpath_ptr = this.read_pointer(oldpath_op)?;
let newpath_ptr = this.read_pointer(newpath_op)?;
if this.ptr_is_null(oldpath_ptr)? || this.ptr_is_null(newpath_ptr)? {
return this.set_last_error_and_return_i32(LibcError("EFAULT"));
}
let oldpath = this.read_path_from_c_str(oldpath_ptr)?;
let newpath = this.read_path_from_c_str(newpath_ptr)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`rename`", reject_with)?;
return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
}
let result = rename(oldpath, newpath).map(|_| 0);
interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
}
fn mkdir(&mut self, path_op: &OpTy<'tcx>, mode_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
let this = self.eval_context_mut();
#[cfg_attr(not(unix), allow(unused_variables))]
let mode = if matches!(&*this.tcx.sess.target.os, "macos" | "freebsd") {
u32::from(this.read_scalar(mode_op)?.to_u16()?)
} else {
this.read_scalar(mode_op)?.to_u32()?
};
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`mkdir`", reject_with)?;
return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
}
#[cfg_attr(not(unix), allow(unused_mut))]
let mut builder = DirBuilder::new();
// If the host supports it, forward on the mode of the directory
// (i.e. permission bits and the sticky bit)
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(mode);
}
let result = builder.create(path).map(|_| 0i32);
interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
}