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