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