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