]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/util.rs
Rollup merge of #60766 - vorner:weak-into-raw, r=sfackler
[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::str;
8 use std::fs;
9 use std::io::{self, Write};
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{SystemTime, Instant};
13
14 use build_helper::t;
15
16 use crate::config::Config;
17 use crate::builder::Builder;
18
19 /// Returns the `name` as the filename of a static library for `target`.
20 pub fn staticlib(name: &str, target: &str) -> String {
21     if target.contains("windows") {
22         format!("{}.lib", name)
23     } else {
24         format!("lib{}.a", name)
25     }
26 }
27
28 /// Given an executable called `name`, return the filename for the
29 /// executable for a particular target.
30 pub fn exe(name: &str, target: &str) -> String {
31     if target.contains("windows") {
32         format!("{}.exe", name)
33     } else {
34         name.to_string()
35     }
36 }
37
38 /// Returns `true` if the file name given looks like a dynamic library.
39 pub fn is_dylib(name: &str) -> bool {
40     name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
41 }
42
43 /// Returns the corresponding relative library directory that the compiler's
44 /// dylibs will be found in.
45 pub fn libdir(target: &str) -> &'static str {
46     if target.contains("windows") {"bin"} else {"lib"}
47 }
48
49 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
50 pub fn add_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
51     let mut list = dylib_path();
52     for path in path {
53         list.insert(0, path);
54     }
55     cmd.env(dylib_path_var(), t!(env::join_paths(list)));
56 }
57
58 /// Returns the environment variable which the dynamic library lookup path
59 /// resides in for this platform.
60 pub fn dylib_path_var() -> &'static str {
61     if cfg!(target_os = "windows") {
62         "PATH"
63     } else if cfg!(target_os = "macos") {
64         "DYLD_LIBRARY_PATH"
65     } else if cfg!(target_os = "haiku") {
66         "LIBRARY_PATH"
67     } else {
68         "LD_LIBRARY_PATH"
69     }
70 }
71
72 /// Parses the `dylib_path_var()` environment variable, returning a list of
73 /// paths that are members of this lookup path.
74 pub fn dylib_path() -> Vec<PathBuf> {
75     let var = match env::var_os(dylib_path_var()) {
76         Some(v) => v,
77         None => return vec![],
78     };
79     env::split_paths(&var).collect()
80 }
81
82 /// `push` all components to `buf`. On windows, append `.exe` to the last component.
83 pub fn push_exe_path(mut buf: PathBuf, components: &[&str]) -> PathBuf {
84     let (&file, components) = components.split_last().expect("at least one component required");
85     let mut file = file.to_owned();
86
87     if cfg!(windows) {
88         file.push_str(".exe");
89     }
90
91     buf.extend(components);
92     buf.push(file);
93
94     buf
95 }
96
97 pub struct TimeIt(bool, Instant);
98
99 /// Returns an RAII structure that prints out how long it took to drop.
100 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
101     TimeIt(builder.config.dry_run, Instant::now())
102 }
103
104 impl Drop for TimeIt {
105     fn drop(&mut self) {
106         let time = self.1.elapsed();
107         if !self.0 {
108             println!("\tfinished in {}.{:03}",
109                     time.as_secs(),
110                     time.subsec_nanos() / 1_000_000);
111         }
112     }
113 }
114
115 /// Symlinks two directories, using junctions on Windows and normal symlinks on
116 /// Unix.
117 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
118     if config.dry_run { return Ok(()); }
119     let _ = fs::remove_dir(dest);
120     return symlink_dir_inner(src, dest);
121
122     #[cfg(not(windows))]
123     fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
124         use std::os::unix::fs;
125         fs::symlink(src, dest)
126     }
127
128     // Creating a directory junction on windows involves dealing with reparse
129     // points and the DeviceIoControl function, and this code is a skeleton of
130     // what can be found here:
131     //
132     // http://www.flexhex.com/docs/articles/hard-links.phtml
133     //
134     // Copied from std
135     #[cfg(windows)]
136     #[allow(nonstandard_style)]
137     fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
138         use std::ptr;
139         use std::ffi::OsStr;
140         use std::os::windows::ffi::OsStrExt;
141
142         const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;
143         const GENERIC_WRITE: DWORD = 0x40000000;
144         const OPEN_EXISTING: DWORD = 3;
145         const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000;
146         const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000;
147         const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4;
148         const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003;
149         const FILE_SHARE_DELETE: DWORD = 0x4;
150         const FILE_SHARE_READ: DWORD = 0x1;
151         const FILE_SHARE_WRITE: DWORD = 0x2;
152
153         type BOOL = i32;
154         type DWORD = u32;
155         type HANDLE = *mut u8;
156         type LPCWSTR = *const u16;
157         type LPDWORD = *mut DWORD;
158         type LPOVERLAPPED = *mut u8;
159         type LPSECURITY_ATTRIBUTES = *mut u8;
160         type LPVOID = *mut u8;
161         type WCHAR = u16;
162         type WORD = u16;
163
164         #[repr(C)]
165         struct REPARSE_MOUNTPOINT_DATA_BUFFER {
166             ReparseTag: DWORD,
167             ReparseDataLength: DWORD,
168             Reserved: WORD,
169             ReparseTargetLength: WORD,
170             ReparseTargetMaximumLength: WORD,
171             Reserved1: WORD,
172             ReparseTarget: WCHAR,
173         }
174
175         extern "system" {
176             fn CreateFileW(lpFileName: LPCWSTR,
177                            dwDesiredAccess: DWORD,
178                            dwShareMode: DWORD,
179                            lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
180                            dwCreationDisposition: DWORD,
181                            dwFlagsAndAttributes: DWORD,
182                            hTemplateFile: HANDLE)
183                            -> HANDLE;
184             fn DeviceIoControl(hDevice: HANDLE,
185                                dwIoControlCode: DWORD,
186                                lpInBuffer: LPVOID,
187                                nInBufferSize: DWORD,
188                                lpOutBuffer: LPVOID,
189                                nOutBufferSize: DWORD,
190                                lpBytesReturned: LPDWORD,
191                                lpOverlapped: LPOVERLAPPED) -> BOOL;
192             fn CloseHandle(hObject: HANDLE) -> BOOL;
193         }
194
195         fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
196             Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
197         }
198
199         // We're using low-level APIs to create the junction, and these are more
200         // picky about paths. For example, forward slashes cannot be used as a
201         // path separator, so we should try to canonicalize the path first.
202         let target = fs::canonicalize(target)?;
203
204         fs::create_dir(junction)?;
205
206         let path = to_u16s(junction)?;
207
208         unsafe {
209             let h = CreateFileW(path.as_ptr(),
210                                 GENERIC_WRITE,
211                                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
212                                 0 as *mut _,
213                                 OPEN_EXISTING,
214                                 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
215                                 ptr::null_mut());
216
217             let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
218             let db = data.as_mut_ptr()
219                             as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
220             let buf = &mut (*db).ReparseTarget as *mut u16;
221             let mut i = 0;
222             // FIXME: this conversion is very hacky
223             let v = br"\??\";
224             let v = v.iter().map(|x| *x as u16);
225             for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
226                 *buf.offset(i) = c;
227                 i += 1;
228             }
229             *buf.offset(i) = 0;
230             i += 1;
231             (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
232             (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
233             (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
234             (*db).ReparseDataLength =
235                     (*db).ReparseTargetLength as DWORD + 12;
236
237             let mut ret = 0;
238             let res = DeviceIoControl(h as *mut _,
239                                       FSCTL_SET_REPARSE_POINT,
240                                       data.as_ptr() as *mut _,
241                                       (*db).ReparseDataLength + 8,
242                                       ptr::null_mut(), 0,
243                                       &mut ret,
244                                       ptr::null_mut());
245
246             let out = if res == 0 {
247                 Err(io::Error::last_os_error())
248             } else {
249                 Ok(())
250             };
251             CloseHandle(h);
252             out
253         }
254     }
255 }
256
257 /// An RAII structure that indicates all output until this instance is dropped
258 /// is part of the same group.
259 ///
260 /// On Travis CI, these output will be folded by default, together with the
261 /// elapsed time in this block. This reduces noise from unnecessary logs,
262 /// allowing developers to quickly identify the error.
263 ///
264 /// Travis CI supports folding by printing `travis_fold:start:<name>` and
265 /// `travis_fold:end:<name>` around the block. Time elapsed is recognized
266 /// similarly with `travis_time:[start|end]:<name>`. These are undocumented, but
267 /// can easily be deduced from source code of the [Travis build commands].
268 ///
269 /// [Travis build commands]:
270 /// https://github.com/travis-ci/travis-build/blob/f603c0089/lib/travis/build/templates/header.sh
271 pub struct OutputFolder {
272     name: String,
273     start_time: SystemTime, // we need SystemTime to get the UNIX timestamp.
274 }
275
276 impl OutputFolder {
277     /// Creates a new output folder with the given group name.
278     pub fn new(name: String) -> OutputFolder {
279         // "\r" moves the cursor to the beginning of the line, and "\x1b[0K" is
280         // the ANSI escape code to clear from the cursor to end of line.
281         // Travis seems to have trouble when _not_ using "\r\x1b[0K", that will
282         // randomly put lines to the top of the webpage.
283         print!("travis_fold:start:{0}\r\x1b[0Ktravis_time:start:{0}\r\x1b[0K", name);
284         OutputFolder {
285             name,
286             start_time: SystemTime::now(),
287         }
288     }
289 }
290
291 impl Drop for OutputFolder {
292     fn drop(&mut self) {
293         use std::time::*;
294         use std::u64;
295
296         fn to_nanos(duration: Result<Duration, SystemTimeError>) -> u64 {
297             match duration {
298                 Ok(d) => d.as_secs() * 1_000_000_000 + d.subsec_nanos() as u64,
299                 Err(_) => u64::MAX,
300             }
301         }
302
303         let end_time = SystemTime::now();
304         let duration = end_time.duration_since(self.start_time);
305         let start = self.start_time.duration_since(UNIX_EPOCH);
306         let finish = end_time.duration_since(UNIX_EPOCH);
307         println!(
308             "travis_fold:end:{0}\r\x1b[0K\n\
309                 travis_time:end:{0}:start={1},finish={2},duration={3}\r\x1b[0K",
310             self.name,
311             to_nanos(start),
312             to_nanos(finish),
313             to_nanos(duration)
314         );
315         io::stdout().flush().unwrap();
316     }
317 }
318
319 /// The CI environment rustbuild is running in. This mainly affects how the logs
320 /// are printed.
321 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
322 pub enum CiEnv {
323     /// Not a CI environment.
324     None,
325     /// The Travis CI environment, for Linux (including Docker) and macOS builds.
326     Travis,
327     /// The AppVeyor environment, for Windows builds.
328     AppVeyor,
329     /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
330     AzurePipelines,
331 }
332
333 impl CiEnv {
334     /// Obtains the current CI environment.
335     pub fn current() -> CiEnv {
336         if env::var("TRAVIS").ok().map_or(false, |e| &*e == "true") {
337             CiEnv::Travis
338         } else if env::var("APPVEYOR").ok().map_or(false, |e| &*e == "True") {
339             CiEnv::AppVeyor
340         } else if env::var("TF_BUILD").ok().map_or(false, |e| &*e == "True") {
341             CiEnv::AzurePipelines
342         } else {
343             CiEnv::None
344         }
345     }
346
347     /// If in a CI environment, forces the command to run with colors.
348     pub fn force_coloring_in_ci(self, cmd: &mut Command) {
349         if self != CiEnv::None {
350             // Due to use of stamp/docker, the output stream of rustbuild is not
351             // a TTY in CI, so coloring is by-default turned off.
352             // The explicit `TERM=xterm` environment is needed for
353             // `--color always` to actually work. This env var was lost when
354             // compiling through the Makefile. Very strange.
355             cmd.env("TERM", "xterm").args(&["--color", "always"]);
356         }
357     }
358 }
359
360 pub fn forcing_clang_based_tests() -> bool {
361     if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
362         match &var.to_string_lossy().to_lowercase()[..] {
363             "1" | "yes" | "on" => true,
364             "0" | "no" | "off" => false,
365             other => {
366                 // Let's make sure typos don't go unnoticed
367                 panic!("Unrecognized option '{}' set in \
368                         RUSTBUILD_FORCE_CLANG_BASED_TESTS", other)
369             }
370         }
371     } else {
372         false
373     }
374 }