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