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