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