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