1 // ignore-windows: File handling is not implemented yet
2 // compile-flags: -Zmiri-disable-isolation
4 #![feature(rustc_private)]
5 #![feature(io_error_more)]
11 create_dir, read_dir, remove_dir, remove_dir_all, remove_file, rename, File, OpenOptions,
13 use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write};
14 use std::path::{Path, PathBuf};
19 test_file_create_new();
28 test_dup_stdout_stderr();
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();
37 std::env::var("MIRI_TEMP")
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`
45 return PathBuf::from(tmp.replace("/", "\\"));
48 return PathBuf::from(tmp.replace("\\", "/"));
50 .unwrap_or_else(|_| std::env::temp_dir())
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();
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();
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();
78 let bytes = b"Hello, World!\n";
79 let path = prepare("miri_test_fs_file.txt");
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);
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());
98 // Removing file should succeed.
99 remove_file(&path).unwrap();
102 fn test_file_open_unix_allow_two_args() {
103 use std::os::unix::ffi::OsStrExt;
105 let path = prepare_with_content("test_file_open_unix_allow_two_args.txt", &[]);
107 let mut name = path.into_os_string();
109 let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
110 let _fd = unsafe { libc::open(name_ptr, libc::O_RDONLY) };
113 fn test_file_open_unix_needs_three_args() {
114 use std::os::unix::ffi::OsStrExt;
116 let path = prepare_with_content("test_file_open_unix_needs_three_args.txt", &[]);
118 let mut name = path.into_os_string();
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) };
124 fn test_file_open_unix_extra_third_arg() {
125 use std::os::unix::ffi::OsStrExt;
127 let path = prepare_with_content("test_file_open_unix_extra_third_arg.txt", &[]);
129 let mut name = path.into_os_string();
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) };
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);
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());
147 // Removing file should succeed.
148 remove_file(&path).unwrap();
151 fn test_file_create_new() {
152 let path = prepare("miri_test_fs_file_create_new.txt");
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.
158 ErrorKind::AlreadyExists,
159 OpenOptions::new().write(true).create_new(true).open(&path).unwrap_err().kind()
161 // Optionally creating a new file that already exists should succeed.
162 OpenOptions::new().write(true).create(true).open(&path).unwrap();
165 remove_file(&path).unwrap();
169 let bytes = b"Hello, entire World!\n";
170 let path = prepare_with_content("miri_test_fs_seek.txt", bytes);
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());
193 // Removing file should succeed.
194 remove_file(&path).unwrap();
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());
208 let bytes = b"Hello, meta-World!\n";
209 let path = prepare_with_content("miri_test_fs_metadata.txt", bytes);
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();
217 // Removing file should succeed.
218 remove_file(&path).unwrap();
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);
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());
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());
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());
244 remove_file(&path).unwrap();
247 fn test_file_sync() {
248 let bytes = b"Hello, World!\n";
249 let path = prepare_with_content("miri_test_fs_sync.txt", bytes);
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();
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();
261 remove_file(&path).unwrap();
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");
269 // Creating a symbolic link should succeed.
271 std::os::unix::fs::symlink(&path, &symlink_path).unwrap();
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());
282 use std::os::unix::ffi::OsStrExt;
284 let expected_path = path.as_os_str().as_bytes();
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();
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];
295 libc::readlink(symlink_c_ptr, large_buf.as_mut_ptr().cast(), large_buf.len())
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);
302 // Test that the resolved path is truncated if the provided buffer
304 let mut small_buf = [0u8; 2];
306 libc::readlink(symlink_c_ptr, small_buf.as_mut_ptr().cast(), small_buf.len())
308 assert_eq!(small_buf, &expected_path[..small_buf.len()]);
309 assert_eq!(res, small_buf.len() as isize);
311 // Test that we report a proper error for a missing path.
312 let bad_path = CString::new("MIRI_MISSING_FILE_NAME").unwrap();
314 libc::readlink(bad_path.as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len())
317 assert_eq!(Error::last_os_error().kind(), ErrorKind::NotFound);
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();
327 // Removing file should succeed.
328 remove_file(&path).unwrap();
332 let bytes = b"Hello, World!\n";
333 let path = prepare("miri_test_fs_errors.txt");
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());
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");
349 let file = File::create(&path1).unwrap();
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());
359 // Renaming a nonexistent file should fail
360 assert_eq!(ErrorKind::NotFound, rename(&path1, &path2).unwrap_err().kind());
362 remove_file(&path2).unwrap();
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());
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());
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());
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();
406 fn test_dup_stdout_stderr() {
407 let bytes = b"hello dup fd\n";
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());