1 //@ignore-target-windows: File handling is not implemented yet
2 //@compile-flags: -Zmiri-disable-isolation
4 #![feature(rustc_private)]
5 #![feature(io_error_more)]
6 #![feature(io_error_uncategorized)]
10 create_dir, read_dir, read_link, remove_dir, remove_dir_all, remove_file, rename, File,
13 use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write};
14 use std::path::{Path, PathBuf};
19 test_file_create_new();
29 test_dup_stdout_stderr();
30 test_from_raw_os_error();
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();
39 std::env::var("MIRI_TEMP")
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`
47 return PathBuf::from(tmp.replace("/", "\\"));
50 return PathBuf::from(tmp.replace("\\", "/"));
52 .unwrap_or_else(|_| std::env::temp_dir())
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();
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();
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();
80 let bytes = b"Hello, World!\n";
81 let path = prepare("miri_test_fs_file.txt");
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);
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());
100 // Removing file should succeed.
101 remove_file(&path).unwrap();
104 fn test_file_open_unix_allow_two_args() {
105 use std::os::unix::ffi::OsStrExt;
107 let path = prepare_with_content("test_file_open_unix_allow_two_args.txt", &[]);
109 let mut name = path.into_os_string();
111 let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
112 let _fd = unsafe { libc::open(name_ptr, libc::O_RDONLY) };
115 fn test_file_open_unix_needs_three_args() {
116 use std::os::unix::ffi::OsStrExt;
118 let path = prepare_with_content("test_file_open_unix_needs_three_args.txt", &[]);
120 let mut name = path.into_os_string();
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) };
126 fn test_file_open_unix_extra_third_arg() {
127 use std::os::unix::ffi::OsStrExt;
129 let path = prepare_with_content("test_file_open_unix_extra_third_arg.txt", &[]);
131 let mut name = path.into_os_string();
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) };
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);
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());
149 // Removing file should succeed.
150 remove_file(&path).unwrap();
153 fn test_file_create_new() {
154 let path = prepare("miri_test_fs_file_create_new.txt");
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.
160 ErrorKind::AlreadyExists,
161 OpenOptions::new().write(true).create_new(true).open(&path).unwrap_err().kind()
163 // Optionally creating a new file that already exists should succeed.
164 OpenOptions::new().write(true).create(true).open(&path).unwrap();
167 remove_file(&path).unwrap();
171 let bytes = b"Hello, entire World!\n";
172 let path = prepare_with_content("miri_test_fs_seek.txt", bytes);
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());
195 // Removing file should succeed.
196 remove_file(&path).unwrap();
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());
210 let bytes = b"Hello, meta-World!\n";
211 let path = prepare_with_content("miri_test_fs_metadata.txt", bytes);
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();
219 // Removing file should succeed.
220 remove_file(&path).unwrap();
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);
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());
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());
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());
246 remove_file(&path).unwrap();
249 fn test_file_sync() {
250 let bytes = b"Hello, World!\n";
251 let path = prepare_with_content("miri_test_fs_sync.txt", bytes);
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();
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();
263 remove_file(&path).unwrap();
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");
271 // Creating a symbolic link should succeed.
273 std::os::unix::fs::symlink(&path, &symlink_path).unwrap();
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());
284 use std::os::unix::ffi::OsStrExt;
286 let expected_path = path.as_os_str().as_bytes();
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();
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];
297 libc::readlink(symlink_c_ptr, large_buf.as_mut_ptr().cast(), large_buf.len())
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);
304 // Test that the resolved path is truncated if the provided buffer
306 let mut small_buf = [0u8; 2];
308 libc::readlink(symlink_c_ptr, small_buf.as_mut_ptr().cast(), small_buf.len())
310 assert_eq!(small_buf, &expected_path[..small_buf.len()]);
311 assert_eq!(res, small_buf.len() as isize);
313 // Test that we report a proper error for a missing path.
314 let bad_path = CString::new("MIRI_MISSING_FILE_NAME").unwrap();
316 libc::readlink(bad_path.as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len())
319 assert_eq!(Error::last_os_error().kind(), ErrorKind::NotFound);
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();
331 // Removing file should succeed.
332 remove_file(&path).unwrap();
336 let bytes = b"Hello, World!\n";
337 let path = prepare("miri_test_fs_errors.txt");
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());
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");
355 let file = File::create(&path1).unwrap();
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());
365 // Renaming a nonexistent file should fail
366 assert_eq!(ErrorKind::NotFound, rename(&path1, &path2).unwrap_err().kind());
368 remove_file(&path2).unwrap();
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());
378 let p = canonicalize(format!("{}/./test_file", dir_path.to_string_lossy())).unwrap();
379 assert_eq!(p.to_string_lossy().find('.'), None);
381 remove_dir_all(&dir_path).unwrap();
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());
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());
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());
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());
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();
430 fn test_dup_stdout_stderr() {
431 let bytes = b"hello dup fd\n";
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());
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:?}");