1 //@ignore-target-windows: File handling is not implemented yet
2 //@compile-flags: -Zmiri-disable-isolation
4 #![feature(io_error_more)]
5 #![feature(io_error_uncategorized)]
9 create_dir, read_dir, read_link, remove_dir, remove_dir_all, remove_file, rename, File,
12 use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write};
13 use std::path::{Path, PathBuf};
18 test_file_create_new();
28 test_dup_stdout_stderr();
29 test_from_raw_os_error();
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();
38 std::env::var("MIRI_TEMP")
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`
46 return PathBuf::from(tmp.replace("/", "\\"));
49 return PathBuf::from(tmp.replace("\\", "/"));
51 .unwrap_or_else(|_| std::env::temp_dir())
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();
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();
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();
79 let bytes = b"Hello, World!\n";
80 let path = prepare("miri_test_fs_file.txt");
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);
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());
99 // Removing file should succeed.
100 remove_file(&path).unwrap();
103 fn test_file_open_unix_allow_two_args() {
104 use std::os::unix::ffi::OsStrExt;
106 let path = prepare_with_content("test_file_open_unix_allow_two_args.txt", &[]);
108 let mut name = path.into_os_string();
110 let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
111 let _fd = unsafe { libc::open(name_ptr, libc::O_RDONLY) };
114 fn test_file_open_unix_needs_three_args() {
115 use std::os::unix::ffi::OsStrExt;
117 let path = prepare_with_content("test_file_open_unix_needs_three_args.txt", &[]);
119 let mut name = path.into_os_string();
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) };
125 fn test_file_open_unix_extra_third_arg() {
126 use std::os::unix::ffi::OsStrExt;
128 let path = prepare_with_content("test_file_open_unix_extra_third_arg.txt", &[]);
130 let mut name = path.into_os_string();
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) };
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);
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());
148 // Removing file should succeed.
149 remove_file(&path).unwrap();
152 fn test_file_create_new() {
153 let path = prepare("miri_test_fs_file_create_new.txt");
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.
159 ErrorKind::AlreadyExists,
160 OpenOptions::new().write(true).create_new(true).open(&path).unwrap_err().kind()
162 // Optionally creating a new file that already exists should succeed.
163 OpenOptions::new().write(true).create(true).open(&path).unwrap();
166 remove_file(&path).unwrap();
170 let bytes = b"Hello, entire World!\n";
171 let path = prepare_with_content("miri_test_fs_seek.txt", bytes);
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());
194 // Removing file should succeed.
195 remove_file(&path).unwrap();
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());
209 let bytes = b"Hello, meta-World!\n";
210 let path = prepare_with_content("miri_test_fs_metadata.txt", bytes);
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();
218 // Removing file should succeed.
219 remove_file(&path).unwrap();
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);
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());
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());
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());
245 remove_file(&path).unwrap();
248 fn test_file_sync() {
249 let bytes = b"Hello, World!\n";
250 let path = prepare_with_content("miri_test_fs_sync.txt", bytes);
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();
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();
262 remove_file(&path).unwrap();
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");
270 // Creating a symbolic link should succeed.
272 std::os::unix::fs::symlink(&path, &symlink_path).unwrap();
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());
283 use std::os::unix::ffi::OsStrExt;
285 let expected_path = path.as_os_str().as_bytes();
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();
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];
296 libc::readlink(symlink_c_ptr, large_buf.as_mut_ptr().cast(), large_buf.len())
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);
303 // Test that the resolved path is truncated if the provided buffer
305 let mut small_buf = [0u8; 2];
307 libc::readlink(symlink_c_ptr, small_buf.as_mut_ptr().cast(), small_buf.len())
309 assert_eq!(small_buf, &expected_path[..small_buf.len()]);
310 assert_eq!(res, small_buf.len() as isize);
312 // Test that we report a proper error for a missing path.
313 let bad_path = CString::new("MIRI_MISSING_FILE_NAME").unwrap();
315 libc::readlink(bad_path.as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len())
318 assert_eq!(Error::last_os_error().kind(), ErrorKind::NotFound);
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();
330 // Removing file should succeed.
331 remove_file(&path).unwrap();
335 let bytes = b"Hello, World!\n";
336 let path = prepare("miri_test_fs_errors.txt");
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());
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");
354 let file = File::create(&path1).unwrap();
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());
364 // Renaming a nonexistent file should fail
365 assert_eq!(ErrorKind::NotFound, rename(&path1, &path2).unwrap_err().kind());
367 remove_file(&path2).unwrap();
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());
377 let p = canonicalize(format!("{}/./test_file", dir_path.to_string_lossy())).unwrap();
378 assert_eq!(p.to_string_lossy().find('.'), None);
380 remove_dir_all(&dir_path).unwrap();
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());
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());
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());
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());
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();
429 fn test_dup_stdout_stderr() {
430 let bytes = b"hello dup fd\n";
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());
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:?}");