]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/tests/pass-dep/shims/libc-fs.rs
Rollup merge of #106625 - Swatinem:ref/cov6, r=nagisa
[rust.git] / src / tools / miri / tests / pass-dep / shims / libc-fs.rs
1 //@ignore-target-windows: no libc on Windows
2 //@compile-flags: -Zmiri-disable-isolation
3
4 #![feature(io_error_more)]
5 #![feature(io_error_uncategorized)]
6
7 use std::convert::TryInto;
8 use std::ffi::{CStr, CString};
9 use std::fs::{canonicalize, remove_dir_all, remove_file, File};
10 use std::io::{Error, ErrorKind, Write};
11 use std::os::unix::ffi::OsStrExt;
12 use std::path::PathBuf;
13
14 fn main() {
15     test_dup_stdout_stderr();
16     test_canonicalize_too_long();
17     test_readlink();
18     test_file_open_unix_allow_two_args();
19     test_file_open_unix_needs_three_args();
20     test_file_open_unix_extra_third_arg();
21     #[cfg(target_os = "linux")]
22     test_o_tmpfile_flag();
23 }
24
25 fn tmp() -> PathBuf {
26     let path = std::env::var("MIRI_TEMP")
27         .unwrap_or_else(|_| std::env::temp_dir().into_os_string().into_string().unwrap());
28     // These are host paths. We need to convert them to the target.
29     let path = CString::new(path).unwrap();
30     let mut out = Vec::with_capacity(1024);
31
32     unsafe {
33         extern "Rust" {
34             fn miri_host_to_target_path(path: *const i8, out: *mut i8, out_size: usize) -> usize;
35         }
36         let ret = miri_host_to_target_path(path.as_ptr(), out.as_mut_ptr(), out.capacity());
37         assert_eq!(ret, 0);
38         let out = CStr::from_ptr(out.as_ptr()).to_str().unwrap();
39         PathBuf::from(out)
40     }
41 }
42
43 /// Prepare: compute filename and make sure the file does not exist.
44 fn prepare(filename: &str) -> PathBuf {
45     let path = tmp().join(filename);
46     // Clean the paths for robustness.
47     remove_file(&path).ok();
48     path
49 }
50
51 /// Prepare directory: compute directory name and make sure it does not exist.
52 #[allow(unused)]
53 fn prepare_dir(dirname: &str) -> PathBuf {
54     let path = tmp().join(&dirname);
55     // Clean the directory for robustness.
56     remove_dir_all(&path).ok();
57     path
58 }
59
60 /// Prepare like above, and also write some initial content to the file.
61 fn prepare_with_content(filename: &str, content: &[u8]) -> PathBuf {
62     let path = prepare(filename);
63     let mut file = File::create(&path).unwrap();
64     file.write(content).unwrap();
65     path
66 }
67
68 fn test_file_open_unix_allow_two_args() {
69     let path = prepare_with_content("test_file_open_unix_allow_two_args.txt", &[]);
70
71     let mut name = path.into_os_string();
72     name.push("\0");
73     let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
74     let _fd = unsafe { libc::open(name_ptr, libc::O_RDONLY) };
75 }
76
77 fn test_file_open_unix_needs_three_args() {
78     let path = prepare_with_content("test_file_open_unix_needs_three_args.txt", &[]);
79
80     let mut name = path.into_os_string();
81     name.push("\0");
82     let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
83     let _fd = unsafe { libc::open(name_ptr, libc::O_CREAT, 0o666) };
84 }
85
86 fn test_file_open_unix_extra_third_arg() {
87     let path = prepare_with_content("test_file_open_unix_extra_third_arg.txt", &[]);
88
89     let mut name = path.into_os_string();
90     name.push("\0");
91     let name_ptr = name.as_bytes().as_ptr().cast::<libc::c_char>();
92     let _fd = unsafe { libc::open(name_ptr, libc::O_RDONLY, 42) };
93 }
94
95 fn test_dup_stdout_stderr() {
96     let bytes = b"hello dup fd\n";
97     unsafe {
98         let new_stdout = libc::fcntl(1, libc::F_DUPFD, 0);
99         let new_stderr = libc::fcntl(2, libc::F_DUPFD, 0);
100         libc::write(new_stdout, bytes.as_ptr() as *const libc::c_void, bytes.len());
101         libc::write(new_stderr, bytes.as_ptr() as *const libc::c_void, bytes.len());
102     }
103 }
104
105 fn test_canonicalize_too_long() {
106     // Make sure we get an error for long paths.
107     let too_long = "x/".repeat(libc::PATH_MAX.try_into().unwrap());
108     assert!(canonicalize(too_long).is_err());
109 }
110
111 fn test_readlink() {
112     let bytes = b"Hello, World!\n";
113     let path = prepare_with_content("miri_test_fs_link_target.txt", bytes);
114     let expected_path = path.as_os_str().as_bytes();
115
116     let symlink_path = prepare("miri_test_fs_symlink.txt");
117     std::os::unix::fs::symlink(&path, &symlink_path).unwrap();
118
119     // Test that the expected string gets written to a buffer of proper
120     // length, and that a trailing null byte is not written.
121     let symlink_c_str = CString::new(symlink_path.as_os_str().as_bytes()).unwrap();
122     let symlink_c_ptr = symlink_c_str.as_ptr();
123
124     // Make the buf one byte larger than it needs to be,
125     // and check that the last byte is not overwritten.
126     let mut large_buf = vec![0xFF; expected_path.len() + 1];
127     let res =
128         unsafe { libc::readlink(symlink_c_ptr, large_buf.as_mut_ptr().cast(), large_buf.len()) };
129     // Check that the resovled path was properly written into the buf.
130     assert_eq!(&large_buf[..(large_buf.len() - 1)], expected_path);
131     assert_eq!(large_buf.last(), Some(&0xFF));
132     assert_eq!(res, large_buf.len() as isize - 1);
133
134     // Test that the resolved path is truncated if the provided buffer
135     // is too small.
136     let mut small_buf = [0u8; 2];
137     let res =
138         unsafe { libc::readlink(symlink_c_ptr, small_buf.as_mut_ptr().cast(), small_buf.len()) };
139     assert_eq!(small_buf, &expected_path[..small_buf.len()]);
140     assert_eq!(res, small_buf.len() as isize);
141
142     // Test that we report a proper error for a missing path.
143     let bad_path = CString::new("MIRI_MISSING_FILE_NAME").unwrap();
144     let res = unsafe {
145         libc::readlink(bad_path.as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len())
146     };
147     assert_eq!(res, -1);
148     assert_eq!(Error::last_os_error().kind(), ErrorKind::NotFound);
149 }
150
151 #[cfg(target_os = "linux")]
152 fn test_o_tmpfile_flag() {
153     use std::fs::{create_dir, OpenOptions};
154     use std::os::unix::fs::OpenOptionsExt;
155     let dir_path = prepare_dir("miri_test_fs_dir");
156     create_dir(&dir_path).unwrap();
157     // test that the `O_TMPFILE` custom flag gracefully errors instead of stopping execution
158     assert_eq!(
159         Some(libc::EOPNOTSUPP),
160         OpenOptions::new()
161             .read(true)
162             .write(true)
163             .custom_flags(libc::O_TMPFILE)
164             .open(dir_path)
165             .unwrap_err()
166             .raw_os_error(),
167     );
168 }