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