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