]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/util.rs
Tweak assertion note in fmt
[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     //
127     // Copied from std
128     #[cfg(windows)]
129     #[allow(nonstandard_style)]
130     fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
131         use std::ffi::OsStr;
132         use std::os::windows::ffi::OsStrExt;
133         use std::ptr;
134
135         const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;
136         const GENERIC_WRITE: DWORD = 0x40000000;
137         const OPEN_EXISTING: DWORD = 3;
138         const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000;
139         const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000;
140         const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4;
141         const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003;
142         const FILE_SHARE_DELETE: DWORD = 0x4;
143         const FILE_SHARE_READ: DWORD = 0x1;
144         const FILE_SHARE_WRITE: DWORD = 0x2;
145
146         type BOOL = i32;
147         type DWORD = u32;
148         type HANDLE = *mut u8;
149         type LPCWSTR = *const u16;
150         type LPDWORD = *mut DWORD;
151         type LPOVERLAPPED = *mut u8;
152         type LPSECURITY_ATTRIBUTES = *mut u8;
153         type LPVOID = *mut u8;
154         type WCHAR = u16;
155         type WORD = u16;
156
157         #[repr(C)]
158         struct REPARSE_MOUNTPOINT_DATA_BUFFER {
159             ReparseTag: DWORD,
160             ReparseDataLength: DWORD,
161             Reserved: WORD,
162             ReparseTargetLength: WORD,
163             ReparseTargetMaximumLength: WORD,
164             Reserved1: WORD,
165             ReparseTarget: WCHAR,
166         }
167
168         extern "system" {
169             fn CreateFileW(
170                 lpFileName: LPCWSTR,
171                 dwDesiredAccess: DWORD,
172                 dwShareMode: DWORD,
173                 lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
174                 dwCreationDisposition: DWORD,
175                 dwFlagsAndAttributes: DWORD,
176                 hTemplateFile: HANDLE,
177             ) -> HANDLE;
178             fn DeviceIoControl(
179                 hDevice: HANDLE,
180                 dwIoControlCode: DWORD,
181                 lpInBuffer: LPVOID,
182                 nInBufferSize: DWORD,
183                 lpOutBuffer: LPVOID,
184                 nOutBufferSize: DWORD,
185                 lpBytesReturned: LPDWORD,
186                 lpOverlapped: LPOVERLAPPED,
187             ) -> BOOL;
188             fn CloseHandle(hObject: HANDLE) -> BOOL;
189         }
190
191         fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
192             Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
193         }
194
195         // We're using low-level APIs to create the junction, and these are more
196         // picky about paths. For example, forward slashes cannot be used as a
197         // path separator, so we should try to canonicalize the path first.
198         let target = fs::canonicalize(target)?;
199
200         fs::create_dir(junction)?;
201
202         let path = to_u16s(junction)?;
203
204         unsafe {
205             let h = CreateFileW(
206                 path.as_ptr(),
207                 GENERIC_WRITE,
208                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
209                 ptr::null_mut(),
210                 OPEN_EXISTING,
211                 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
212                 ptr::null_mut(),
213             );
214
215             let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
216             let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
217             let buf = &mut (*db).ReparseTarget as *mut u16;
218             let mut i = 0;
219             // FIXME: this conversion is very hacky
220             let v = br"\??\";
221             let v = v.iter().map(|x| *x as u16);
222             for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
223                 *buf.offset(i) = c;
224                 i += 1;
225             }
226             *buf.offset(i) = 0;
227             i += 1;
228             (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
229             (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
230             (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
231             (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
232
233             let mut ret = 0;
234             let res = DeviceIoControl(
235                 h as *mut _,
236                 FSCTL_SET_REPARSE_POINT,
237                 data.as_ptr() as *mut _,
238                 (*db).ReparseDataLength + 8,
239                 ptr::null_mut(),
240                 0,
241                 &mut ret,
242                 ptr::null_mut(),
243             );
244
245             let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
246             CloseHandle(h);
247             out
248         }
249     }
250 }
251
252 /// The CI environment rustbuild is running in. This mainly affects how the logs
253 /// are printed.
254 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
255 pub enum CiEnv {
256     /// Not a CI environment.
257     None,
258     /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
259     AzurePipelines,
260     /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
261     GitHubActions,
262 }
263
264 impl CiEnv {
265     /// Obtains the current CI environment.
266     pub fn current() -> CiEnv {
267         if env::var("TF_BUILD").map_or(false, |e| e == "True") {
268             CiEnv::AzurePipelines
269         } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
270             CiEnv::GitHubActions
271         } else {
272             CiEnv::None
273         }
274     }
275
276     /// If in a CI environment, forces the command to run with colors.
277     pub fn force_coloring_in_ci(self, cmd: &mut Command) {
278         if self != CiEnv::None {
279             // Due to use of stamp/docker, the output stream of rustbuild is not
280             // a TTY in CI, so coloring is by-default turned off.
281             // The explicit `TERM=xterm` environment is needed for
282             // `--color always` to actually work. This env var was lost when
283             // compiling through the Makefile. Very strange.
284             cmd.env("TERM", "xterm").args(&["--color", "always"]);
285         }
286     }
287 }
288
289 pub fn forcing_clang_based_tests() -> bool {
290     if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
291         match &var.to_string_lossy().to_lowercase()[..] {
292             "1" | "yes" | "on" => true,
293             "0" | "no" | "off" => false,
294             other => {
295                 // Let's make sure typos don't go unnoticed
296                 panic!(
297                     "Unrecognized option '{}' set in \
298                         RUSTBUILD_FORCE_CLANG_BASED_TESTS",
299                     other
300                 )
301             }
302         }
303     } else {
304         false
305     }
306 }
307
308 pub fn use_host_linker(target: &Interned<String>) -> bool {
309     // FIXME: this information should be gotten by checking the linker flavor
310     // of the rustc target
311     !(target.contains("emscripten")
312         || target.contains("wasm32")
313         || target.contains("nvptx")
314         || target.contains("fortanix")
315         || target.contains("fuchsia"))
316 }