]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/util.rs
rustc_metadata: Rename `item_children(_untracked)` to `module_children(_untracked)`
[rust.git] / src / bootstrap / util.rs
1 //! Various utility functions used throughout rustbuild.
2 //!
3 //! Simple things like testing the various filesystem operations here and there,
4 //! not a lot of interesting happenings here unfortunately.
5
6 use std::env;
7 use std::fs;
8 use std::io;
9 use std::path::{Path, PathBuf};
10 use std::process::Command;
11 use std::str;
12 use std::time::Instant;
13
14 use build_helper::t;
15
16 use crate::builder::Builder;
17 use crate::config::{Config, TargetSelection};
18
19 /// Given an executable called `name`, return the filename for the
20 /// executable for a particular target.
21 pub fn exe(name: &str, target: TargetSelection) -> String {
22     if target.contains("windows") { format!("{}.exe", name) } else { name.to_string() }
23 }
24
25 /// Returns `true` if the file name given looks like a dynamic library.
26 pub fn is_dylib(name: &str) -> bool {
27     name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
28 }
29
30 /// Returns `true` if the file name given looks like a debug info file
31 pub fn is_debug_info(name: &str) -> bool {
32     // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
33     name.ends_with(".pdb")
34 }
35
36 /// Returns the corresponding relative library directory that the compiler's
37 /// dylibs will be found in.
38 pub fn libdir(target: TargetSelection) -> &'static str {
39     if target.contains("windows") { "bin" } else { "lib" }
40 }
41
42 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
43 /// If The dylib_path_par is already set for this cmd, the old value will be overwritten!
44 pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
45     let mut list = dylib_path();
46     for path in path {
47         list.insert(0, path);
48     }
49     cmd.env(dylib_path_var(), t!(env::join_paths(list)));
50 }
51
52 include!("dylib_util.rs");
53
54 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
55 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
56     let mut list = link_lib_path();
57     for path in path {
58         list.insert(0, path);
59     }
60     cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
61 }
62
63 /// Returns the environment variable which the link library lookup path
64 /// resides in for this platform.
65 fn link_lib_path_var() -> &'static str {
66     if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
67 }
68
69 /// Parses the `link_lib_path_var()` environment variable, returning a list of
70 /// paths that are members of this lookup path.
71 fn link_lib_path() -> Vec<PathBuf> {
72     let var = match env::var_os(link_lib_path_var()) {
73         Some(v) => v,
74         None => return vec![],
75     };
76     env::split_paths(&var).collect()
77 }
78
79 pub struct TimeIt(bool, Instant);
80
81 /// Returns an RAII structure that prints out how long it took to drop.
82 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
83     TimeIt(builder.config.dry_run, Instant::now())
84 }
85
86 impl Drop for TimeIt {
87     fn drop(&mut self) {
88         let time = self.1.elapsed();
89         if !self.0 {
90             println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
91         }
92     }
93 }
94
95 /// Symlinks two directories, using junctions on Windows and normal symlinks on
96 /// Unix.
97 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
98     if config.dry_run {
99         return Ok(());
100     }
101     let _ = fs::remove_dir(dest);
102     return symlink_dir_inner(src, dest);
103
104     #[cfg(not(windows))]
105     fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
106         use std::os::unix::fs;
107         fs::symlink(src, dest)
108     }
109
110     // Creating a directory junction on windows involves dealing with reparse
111     // points and the DeviceIoControl function, and this code is a skeleton of
112     // what can be found here:
113     //
114     // http://www.flexhex.com/docs/articles/hard-links.phtml
115     #[cfg(windows)]
116     fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
117         use std::ffi::OsStr;
118         use std::os::windows::ffi::OsStrExt;
119         use std::ptr;
120
121         use winapi::shared::minwindef::{DWORD, WORD};
122         use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
123         use winapi::um::handleapi::CloseHandle;
124         use winapi::um::ioapiset::DeviceIoControl;
125         use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
126         use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
127         use winapi::um::winnt::{
128             FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
129             IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
130         };
131
132         #[allow(non_snake_case)]
133         #[repr(C)]
134         struct REPARSE_MOUNTPOINT_DATA_BUFFER {
135             ReparseTag: DWORD,
136             ReparseDataLength: DWORD,
137             Reserved: WORD,
138             ReparseTargetLength: WORD,
139             ReparseTargetMaximumLength: WORD,
140             Reserved1: WORD,
141             ReparseTarget: WCHAR,
142         }
143
144         fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
145             Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
146         }
147
148         // We're using low-level APIs to create the junction, and these are more
149         // picky about paths. For example, forward slashes cannot be used as a
150         // path separator, so we should try to canonicalize the path first.
151         let target = fs::canonicalize(target)?;
152
153         fs::create_dir(junction)?;
154
155         let path = to_u16s(junction)?;
156
157         unsafe {
158             let h = CreateFileW(
159                 path.as_ptr(),
160                 GENERIC_WRITE,
161                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
162                 ptr::null_mut(),
163                 OPEN_EXISTING,
164                 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
165                 ptr::null_mut(),
166             );
167
168             let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
169             let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
170             let buf = &mut (*db).ReparseTarget as *mut u16;
171             let mut i = 0;
172             // FIXME: this conversion is very hacky
173             let v = br"\??\";
174             let v = v.iter().map(|x| *x as u16);
175             for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
176                 *buf.offset(i) = c;
177                 i += 1;
178             }
179             *buf.offset(i) = 0;
180             i += 1;
181             (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
182             (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
183             (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
184             (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
185
186             let mut ret = 0;
187             let res = DeviceIoControl(
188                 h as *mut _,
189                 FSCTL_SET_REPARSE_POINT,
190                 data.as_ptr() as *mut _,
191                 (*db).ReparseDataLength + 8,
192                 ptr::null_mut(),
193                 0,
194                 &mut ret,
195                 ptr::null_mut(),
196             );
197
198             let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
199             CloseHandle(h);
200             out
201         }
202     }
203 }
204
205 /// The CI environment rustbuild is running in. This mainly affects how the logs
206 /// are printed.
207 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
208 pub enum CiEnv {
209     /// Not a CI environment.
210     None,
211     /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
212     AzurePipelines,
213     /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
214     GitHubActions,
215 }
216
217 impl CiEnv {
218     /// Obtains the current CI environment.
219     pub fn current() -> CiEnv {
220         if env::var("TF_BUILD").map_or(false, |e| e == "True") {
221             CiEnv::AzurePipelines
222         } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
223             CiEnv::GitHubActions
224         } else {
225             CiEnv::None
226         }
227     }
228
229     /// If in a CI environment, forces the command to run with colors.
230     pub fn force_coloring_in_ci(self, cmd: &mut Command) {
231         if self != CiEnv::None {
232             // Due to use of stamp/docker, the output stream of rustbuild is not
233             // a TTY in CI, so coloring is by-default turned off.
234             // The explicit `TERM=xterm` environment is needed for
235             // `--color always` to actually work. This env var was lost when
236             // compiling through the Makefile. Very strange.
237             cmd.env("TERM", "xterm").args(&["--color", "always"]);
238         }
239     }
240 }
241
242 pub fn forcing_clang_based_tests() -> bool {
243     if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
244         match &var.to_string_lossy().to_lowercase()[..] {
245             "1" | "yes" | "on" => true,
246             "0" | "no" | "off" => false,
247             other => {
248                 // Let's make sure typos don't go unnoticed
249                 panic!(
250                     "Unrecognized option '{}' set in \
251                         RUSTBUILD_FORCE_CLANG_BASED_TESTS",
252                     other
253                 )
254             }
255         }
256     } else {
257         false
258     }
259 }
260
261 pub fn use_host_linker(target: TargetSelection) -> bool {
262     // FIXME: this information should be gotten by checking the linker flavor
263     // of the rustc target
264     !(target.contains("emscripten")
265         || target.contains("wasm32")
266         || target.contains("nvptx")
267         || target.contains("fortanix")
268         || target.contains("fuchsia")
269         || target.contains("bpf"))
270 }
271
272 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
273     path: &'a Path,
274     suite_path: P,
275     builder: &Builder<'_>,
276 ) -> Option<&'a str> {
277     let suite_path = suite_path.as_ref();
278     let path = match path.strip_prefix(".") {
279         Ok(p) => p,
280         Err(_) => path,
281     };
282     if !path.starts_with(suite_path) {
283         return None;
284     }
285     let exists = path.is_dir() || path.is_file();
286     if !exists {
287         if let Some(p) = path.to_str() {
288             builder.info(&format!("Warning: Skipping \"{}\": not a regular file or directory", p));
289         }
290         return None;
291     }
292     // Since test suite paths are themselves directories, if we don't
293     // specify a directory or file, we'll get an empty string here
294     // (the result of the test suite directory without its suite prefix).
295     // Therefore, we need to filter these out, as only the first --test-args
296     // flag is respected, so providing an empty --test-args conflicts with
297     // any following it.
298     match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
299         Some(s) if !s.is_empty() => Some(s),
300         _ => None,
301     }
302 }