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