]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/tests/pass-dep/shims/fs.rs
Rollup merge of #102109 - petrochenkov:addids, r=oli-obk
[rust.git] / src / tools / miri / tests / pass-dep / shims / fs.rs
1 //@ignore-target-windows: File handling is not implemented yet
2 //@compile-flags: -Zmiri-disable-isolation
3
4 #![feature(io_error_more)]
5 #![feature(io_error_uncategorized)]
6
7 use std::ffi::CString;
8 use std::fs::{
9     create_dir, read_dir, read_link, remove_dir, remove_dir_all, remove_file, rename, File,
10     OpenOptions,
11 };
12 use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write};
13 use std::path::{Path, PathBuf};
14
15 fn main() {
16     test_file();
17     test_file_clone();
18     test_file_create_new();
19     test_seek();
20     test_metadata();
21     test_file_set_len();
22     test_file_sync();
23     test_symlink();
24     test_errors();
25     test_rename();
26     test_directory();
27     test_canonicalize();
28     test_dup_stdout_stderr();
29     test_from_raw_os_error();
30
31     // These all require unix, if the test is changed to no longer `ignore-windows`, move these to a unix test
32     test_file_open_unix_allow_two_args();
33     test_file_open_unix_needs_three_args();
34     test_file_open_unix_extra_third_arg();
35 }
36
37 fn tmp() -> PathBuf {
38     std::env::var("MIRI_TEMP")
39         .map(|tmp| {
40             // MIRI_TEMP is set outside of our emulated
41             // program, so it may have path separators that don't
42             // correspond to our target platform. We normalize them here
43             // before constructing a `PathBuf`
44
45             #[cfg(windows)]
46             return PathBuf::from(tmp.replace("/", "\\"));
47
48             #[cfg(not(windows))]
49             return PathBuf::from(tmp.replace("\\", "/"));
50         })
51         .unwrap_or_else(|_| std::env::temp_dir())
52 }
53
54 /// Prepare: compute filename and make sure the file does not exist.
55 fn prepare(filename: &str) -> PathBuf {
56     let path = tmp().join(filename);
57     // Clean the paths for robustness.
58     remove_file(&path).ok();
59     path
60 }
61
62 /// Prepare directory: compute directory name and make sure it does not exist.
63 fn prepare_dir(dirname: &str) -> PathBuf {
64     let path = tmp().join(&dirname);
65     // Clean the directory for robustness.
66     remove_dir_all(&path).ok();
67     path
68 }
69
70 /// Prepare like above, and also write some initial content to the file.
71 fn prepare_with_content(filename: &str, content: &[u8]) -> PathBuf {
72     let path = prepare(filename);
73     let mut file = File::create(&path).unwrap();
74     file.write(content).unwrap();
75     path
76 }
77
78 fn test_file() {
79     let bytes = b"Hello, World!\n";
80     let path = prepare("miri_test_fs_file.txt");
81
82     // Test creating, writing and closing a file (closing is tested when `file` is dropped).
83     let mut file = File::create(&path).unwrap();
84     // Writing 0 bytes should not change the file contents.
85     file.write(&mut []).unwrap();
86     assert_eq!(file.metadata().unwrap().len(), 0);
87
88     file.write(bytes).unwrap();
89     assert_eq!(file.metadata().unwrap().len(), bytes.len() as u64);
90     // Test opening, reading and closing a file.
91     let mut file = File::open(&path).unwrap();
92     let mut contents = Vec::new();
93     // Reading 0 bytes should not move the file pointer.
94     file.read(&mut []).unwrap();
95     // Reading until EOF should get the whole text.
96     file.read_to_end(&mut contents).unwrap();
97     assert_eq!(bytes, contents.as_slice());
98
99     // Removing file should succeed.
100     remove_file(&path).unwrap();
101 }
102
103 fn test_file_open_unix_allow_two_args() {
104     use std::os::unix::ffi::OsStrExt;
105
106     let path = prepare_with_content("test_file_open_unix_allow_two_args.txt", &[]);
107
108     let mut name = path.into_os_string();
109     name.push("\0");
110     let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
111     let _fd = unsafe { libc::open(name_ptr, libc::O_RDONLY) };
112 }
113
114 fn test_file_open_unix_needs_three_args() {
115     use std::os::unix::ffi::OsStrExt;
116
117     let path = prepare_with_content("test_file_open_unix_needs_three_args.txt", &[]);
118
119     let mut name = path.into_os_string();
120     name.push("\0");
121     let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
122     let _fd = unsafe { libc::open(name_ptr, libc::O_CREAT, 0o666) };
123 }
124
125 fn test_file_open_unix_extra_third_arg() {
126     use std::os::unix::ffi::OsStrExt;
127
128     let path = prepare_with_content("test_file_open_unix_extra_third_arg.txt", &[]);
129
130     let mut name = path.into_os_string();
131     name.push("\0");
132     let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
133     let _fd = unsafe { libc::open(name_ptr, libc::O_RDONLY, 42) };
134 }
135
136 fn test_file_clone() {
137     let bytes = b"Hello, World!\n";
138     let path = prepare_with_content("miri_test_fs_file_clone.txt", bytes);
139
140     // Cloning a file should be successful.
141     let file = File::open(&path).unwrap();
142     let mut cloned = file.try_clone().unwrap();
143     // Reading from a cloned file should get the same text.
144     let mut contents = Vec::new();
145     cloned.read_to_end(&mut contents).unwrap();
146     assert_eq!(bytes, contents.as_slice());
147
148     // Removing file should succeed.
149     remove_file(&path).unwrap();
150 }
151
152 fn test_file_create_new() {
153     let path = prepare("miri_test_fs_file_create_new.txt");
154
155     // Creating a new file that doesn't yet exist should succeed.
156     OpenOptions::new().write(true).create_new(true).open(&path).unwrap();
157     // Creating a new file that already exists should fail.
158     assert_eq!(
159         ErrorKind::AlreadyExists,
160         OpenOptions::new().write(true).create_new(true).open(&path).unwrap_err().kind()
161     );
162     // Optionally creating a new file that already exists should succeed.
163     OpenOptions::new().write(true).create(true).open(&path).unwrap();
164
165     // Clean up
166     remove_file(&path).unwrap();
167 }
168
169 fn test_seek() {
170     let bytes = b"Hello, entire World!\n";
171     let path = prepare_with_content("miri_test_fs_seek.txt", bytes);
172
173     let mut file = File::open(&path).unwrap();
174     let mut contents = Vec::new();
175     file.read_to_end(&mut contents).unwrap();
176     assert_eq!(bytes, contents.as_slice());
177     // Test that seeking to the beginning and reading until EOF gets the text again.
178     file.seek(SeekFrom::Start(0)).unwrap();
179     let mut contents = Vec::new();
180     file.read_to_end(&mut contents).unwrap();
181     assert_eq!(bytes, contents.as_slice());
182     // Test seeking relative to the end of the file.
183     file.seek(SeekFrom::End(-1)).unwrap();
184     let mut contents = Vec::new();
185     file.read_to_end(&mut contents).unwrap();
186     assert_eq!(&bytes[bytes.len() - 1..], contents.as_slice());
187     // Test seeking relative to the current position.
188     file.seek(SeekFrom::Start(5)).unwrap();
189     file.seek(SeekFrom::Current(-3)).unwrap();
190     let mut contents = Vec::new();
191     file.read_to_end(&mut contents).unwrap();
192     assert_eq!(&bytes[2..], contents.as_slice());
193
194     // Removing file should succeed.
195     remove_file(&path).unwrap();
196 }
197
198 fn check_metadata(bytes: &[u8], path: &Path) -> Result<()> {
199     // Test that the file metadata is correct.
200     let metadata = path.metadata()?;
201     // `path` should point to a file.
202     assert!(metadata.is_file());
203     // The size of the file must be equal to the number of written bytes.
204     assert_eq!(bytes.len() as u64, metadata.len());
205     Ok(())
206 }
207
208 fn test_metadata() {
209     let bytes = b"Hello, meta-World!\n";
210     let path = prepare_with_content("miri_test_fs_metadata.txt", bytes);
211
212     // Test that metadata of an absolute path is correct.
213     check_metadata(bytes, &path).unwrap();
214     // Test that metadata of a relative path is correct.
215     std::env::set_current_dir(path.parent().unwrap()).unwrap();
216     check_metadata(bytes, Path::new(path.file_name().unwrap())).unwrap();
217
218     // Removing file should succeed.
219     remove_file(&path).unwrap();
220 }
221
222 fn test_file_set_len() {
223     let bytes = b"Hello, World!\n";
224     let path = prepare_with_content("miri_test_fs_set_len.txt", bytes);
225
226     // Test extending the file
227     let mut file = OpenOptions::new().read(true).write(true).open(&path).unwrap();
228     let bytes_extended = b"Hello, World!\n\x00\x00\x00\x00\x00\x00";
229     file.set_len(20).unwrap();
230     let mut contents = Vec::new();
231     file.read_to_end(&mut contents).unwrap();
232     assert_eq!(bytes_extended, contents.as_slice());
233
234     // Test truncating the file
235     file.seek(SeekFrom::Start(0)).unwrap();
236     file.set_len(10).unwrap();
237     let mut contents = Vec::new();
238     file.read_to_end(&mut contents).unwrap();
239     assert_eq!(&bytes[..10], contents.as_slice());
240
241     // Can't use set_len on a file not opened for writing
242     let file = OpenOptions::new().read(true).open(&path).unwrap();
243     assert_eq!(ErrorKind::InvalidInput, file.set_len(14).unwrap_err().kind());
244
245     remove_file(&path).unwrap();
246 }
247
248 fn test_file_sync() {
249     let bytes = b"Hello, World!\n";
250     let path = prepare_with_content("miri_test_fs_sync.txt", bytes);
251
252     // Test that we can call sync_data and sync_all (can't readily test effects of this operation)
253     let file = OpenOptions::new().write(true).open(&path).unwrap();
254     file.sync_data().unwrap();
255     file.sync_all().unwrap();
256
257     // Test that we can call sync_data and sync_all on a file opened for reading.
258     let file = File::open(&path).unwrap();
259     file.sync_data().unwrap();
260     file.sync_all().unwrap();
261
262     remove_file(&path).unwrap();
263 }
264
265 fn test_symlink() {
266     let bytes = b"Hello, World!\n";
267     let path = prepare_with_content("miri_test_fs_link_target.txt", bytes);
268     let symlink_path = prepare("miri_test_fs_symlink.txt");
269
270     // Creating a symbolic link should succeed.
271     #[cfg(unix)]
272     std::os::unix::fs::symlink(&path, &symlink_path).unwrap();
273     #[cfg(windows)]
274     std::os::windows::fs::symlink_file(&path, &symlink_path).unwrap();
275     // Test that the symbolic link has the same contents as the file.
276     let mut symlink_file = File::open(&symlink_path).unwrap();
277     let mut contents = Vec::new();
278     symlink_file.read_to_end(&mut contents).unwrap();
279     assert_eq!(bytes, contents.as_slice());
280
281     #[cfg(unix)]
282     {
283         use std::os::unix::ffi::OsStrExt;
284
285         let expected_path = path.as_os_str().as_bytes();
286
287         // Test that the expected string gets written to a buffer of proper
288         // length, and that a trailing null byte is not written.
289         let symlink_c_str = CString::new(symlink_path.as_os_str().as_bytes()).unwrap();
290         let symlink_c_ptr = symlink_c_str.as_ptr();
291
292         // Make the buf one byte larger than it needs to be,
293         // and check that the last byte is not overwritten.
294         let mut large_buf = vec![0xFF; expected_path.len() + 1];
295         let res = unsafe {
296             libc::readlink(symlink_c_ptr, large_buf.as_mut_ptr().cast(), large_buf.len())
297         };
298         // Check that the resovled path was properly written into the buf.
299         assert_eq!(&large_buf[..(large_buf.len() - 1)], expected_path);
300         assert_eq!(large_buf.last(), Some(&0xFF));
301         assert_eq!(res, large_buf.len() as isize - 1);
302
303         // Test that the resolved path is truncated if the provided buffer
304         // is too small.
305         let mut small_buf = [0u8; 2];
306         let res = unsafe {
307             libc::readlink(symlink_c_ptr, small_buf.as_mut_ptr().cast(), small_buf.len())
308         };
309         assert_eq!(small_buf, &expected_path[..small_buf.len()]);
310         assert_eq!(res, small_buf.len() as isize);
311
312         // Test that we report a proper error for a missing path.
313         let bad_path = CString::new("MIRI_MISSING_FILE_NAME").unwrap();
314         let res = unsafe {
315             libc::readlink(bad_path.as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len())
316         };
317         assert_eq!(res, -1);
318         assert_eq!(Error::last_os_error().kind(), ErrorKind::NotFound);
319     }
320
321     // Test that metadata of a symbolic link (i.e., the file it points to) is correct.
322     check_metadata(bytes, &symlink_path).unwrap();
323     // Test that the metadata of a symbolic link is correct when not following it.
324     assert!(symlink_path.symlink_metadata().unwrap().file_type().is_symlink());
325     // Check that we can follow the link.
326     assert_eq!(read_link(&symlink_path).unwrap(), path);
327     // Removing symbolic link should succeed.
328     remove_file(&symlink_path).unwrap();
329
330     // Removing file should succeed.
331     remove_file(&path).unwrap();
332 }
333
334 fn test_errors() {
335     let bytes = b"Hello, World!\n";
336     let path = prepare("miri_test_fs_errors.txt");
337
338     // The following tests also check that the `__errno_location()` shim is working properly.
339     // Opening a non-existing file should fail with a "not found" error.
340     assert_eq!(ErrorKind::NotFound, File::open(&path).unwrap_err().kind());
341     // Make sure we can also format this.
342     format!("{0:?}: {0}", File::open(&path).unwrap_err());
343     // Removing a non-existing file should fail with a "not found" error.
344     assert_eq!(ErrorKind::NotFound, remove_file(&path).unwrap_err().kind());
345     // Reading the metadata of a non-existing file should fail with a "not found" error.
346     assert_eq!(ErrorKind::NotFound, check_metadata(bytes, &path).unwrap_err().kind());
347 }
348
349 fn test_rename() {
350     // Renaming a file should succeed.
351     let path1 = prepare("miri_test_fs_rename_source.txt");
352     let path2 = prepare("miri_test_fs_rename_destination.txt");
353
354     let file = File::create(&path1).unwrap();
355     drop(file);
356
357     // Renaming should succeed
358     rename(&path1, &path2).unwrap();
359     // Check that the old file path isn't present
360     assert_eq!(ErrorKind::NotFound, path1.metadata().unwrap_err().kind());
361     // Check that the file has moved successfully
362     assert!(path2.metadata().unwrap().is_file());
363
364     // Renaming a nonexistent file should fail
365     assert_eq!(ErrorKind::NotFound, rename(&path1, &path2).unwrap_err().kind());
366
367     remove_file(&path2).unwrap();
368 }
369
370 fn test_canonicalize() {
371     use std::fs::canonicalize;
372     let dir_path = prepare_dir("miri_test_fs_dir");
373     create_dir(&dir_path).unwrap();
374     let path = dir_path.join("test_file");
375     drop(File::create(&path).unwrap());
376
377     let p = canonicalize(format!("{}/./test_file", dir_path.to_string_lossy())).unwrap();
378     assert_eq!(p.to_string_lossy().find('.'), None);
379
380     remove_dir_all(&dir_path).unwrap();
381
382     // Make sure we get an error for long paths.
383     use std::convert::TryInto;
384     let too_long = "x/".repeat(libc::PATH_MAX.try_into().unwrap());
385     assert!(canonicalize(too_long).is_err());
386 }
387
388 fn test_directory() {
389     let dir_path = prepare_dir("miri_test_fs_dir");
390     // Creating a directory should succeed.
391     create_dir(&dir_path).unwrap();
392     // Test that the metadata of a directory is correct.
393     assert!(dir_path.metadata().unwrap().is_dir());
394     // Creating a directory when it already exists should fail.
395     assert_eq!(ErrorKind::AlreadyExists, create_dir(&dir_path).unwrap_err().kind());
396
397     // Create some files inside the directory
398     let path_1 = dir_path.join("test_file_1");
399     drop(File::create(&path_1).unwrap());
400     let path_2 = dir_path.join("test_file_2");
401     drop(File::create(&path_2).unwrap());
402     // Test that the files are present inside the directory
403     let dir_iter = read_dir(&dir_path).unwrap();
404     let mut file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
405     file_names.sort_unstable();
406     assert_eq!(file_names, vec!["test_file_1", "test_file_2"]);
407     // Deleting the directory should fail, since it is not empty.
408     assert_eq!(ErrorKind::DirectoryNotEmpty, remove_dir(&dir_path).unwrap_err().kind());
409     // Clean up the files in the directory
410     remove_file(&path_1).unwrap();
411     remove_file(&path_2).unwrap();
412     // Now there should be nothing left in the directory.
413     let dir_iter = read_dir(&dir_path).unwrap();
414     let file_names = dir_iter.map(|e| e.unwrap().file_name()).collect::<Vec<_>>();
415     assert!(file_names.is_empty());
416
417     // Deleting the directory should succeed.
418     remove_dir(&dir_path).unwrap();
419     // Reading the metadata of a non-existent directory should fail with a "not found" error.
420     assert_eq!(ErrorKind::NotFound, check_metadata(&[], &dir_path).unwrap_err().kind());
421
422     // To test remove_dir_all, re-create the directory with a file and a directory in it.
423     create_dir(&dir_path).unwrap();
424     drop(File::create(&path_1).unwrap());
425     create_dir(&path_2).unwrap();
426     remove_dir_all(&dir_path).unwrap();
427 }
428
429 fn test_dup_stdout_stderr() {
430     let bytes = b"hello dup fd\n";
431     unsafe {
432         let new_stdout = libc::fcntl(1, libc::F_DUPFD, 0);
433         let new_stderr = libc::fcntl(2, libc::F_DUPFD, 0);
434         libc::write(new_stdout, bytes.as_ptr() as *const libc::c_void, bytes.len());
435         libc::write(new_stderr, bytes.as_ptr() as *const libc::c_void, bytes.len());
436     }
437 }
438
439 fn test_from_raw_os_error() {
440     let code = 6; // not a code that std or Miri know
441     let error = Error::from_raw_os_error(code);
442     assert!(matches!(error.kind(), ErrorKind::Uncategorized));
443     // Make sure we can also format this.
444     format!("{error:?}");
445 }