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