1 //! Various utility functions used throughout rustbuild.
3 //! Simple things like testing the various filesystem operations here and there,
4 //! not a lot of interesting happenings here unfortunately.
9 use std::io::{self, Write};
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{SystemTime, Instant};
16 use crate::config::Config;
17 use crate::builder::Builder;
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)
24 format!("lib{}.a", name)
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)
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")
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"}
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();
55 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
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") {
63 } else if cfg!(target_os = "macos") {
65 } else if cfg!(target_os = "haiku") {
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()) {
77 None => return vec![],
79 env::split_paths(&var).collect()
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();
88 file.push_str(".exe");
91 buf.extend(components);
97 pub struct TimeIt(bool, Instant);
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())
104 impl Drop for TimeIt {
106 let time = self.1.elapsed();
108 println!("\tfinished in {}.{:03}",
110 time.subsec_nanos() / 1_000_000);
115 /// Symlinks two directories, using junctions on Windows and normal symlinks on
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);
123 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
124 use std::os::unix::fs;
125 fs::symlink(src, dest)
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:
132 // http://www.flexhex.com/docs/articles/hard-links.phtml
136 #[allow(nonstandard_style)]
137 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
140 use std::os::windows::ffi::OsStrExt;
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;
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;
165 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
167 ReparseDataLength: DWORD,
169 ReparseTargetLength: WORD,
170 ReparseTargetMaximumLength: WORD,
172 ReparseTarget: WCHAR,
176 fn CreateFileW(lpFileName: LPCWSTR,
177 dwDesiredAccess: DWORD,
179 lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
180 dwCreationDisposition: DWORD,
181 dwFlagsAndAttributes: DWORD,
182 hTemplateFile: HANDLE)
184 fn DeviceIoControl(hDevice: HANDLE,
185 dwIoControlCode: DWORD,
187 nInBufferSize: DWORD,
189 nOutBufferSize: DWORD,
190 lpBytesReturned: LPDWORD,
191 lpOverlapped: LPOVERLAPPED) -> BOOL;
192 fn CloseHandle(hObject: HANDLE) -> BOOL;
195 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
196 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
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)?;
204 fs::create_dir(junction)?;
206 let path = to_u16s(junction)?;
209 let h = CreateFileW(path.as_ptr(),
211 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
214 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
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;
222 // FIXME: this conversion is very hacky
224 let v = v.iter().map(|x| *x as u16);
225 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
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;
238 let res = DeviceIoControl(h as *mut _,
239 FSCTL_SET_REPARSE_POINT,
240 data.as_ptr() as *mut _,
241 (*db).ReparseDataLength + 8,
246 let out = if res == 0 {
247 Err(io::Error::last_os_error())
257 /// An RAII structure that indicates all output until this instance is dropped
258 /// is part of the same group.
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.
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].
269 /// [Travis build commands]:
270 /// https://github.com/travis-ci/travis-build/blob/f603c0089/lib/travis/build/templates/header.sh
271 pub struct OutputFolder {
273 start_time: SystemTime, // we need SystemTime to get the UNIX timestamp.
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);
286 start_time: SystemTime::now(),
291 impl Drop for OutputFolder {
296 fn to_nanos(duration: Result<Duration, SystemTimeError>) -> u64 {
298 Ok(d) => d.as_secs() * 1_000_000_000 + d.subsec_nanos() as u64,
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);
308 "travis_fold:end:{0}\r\x1b[0K\n\
309 travis_time:end:{0}:start={1},finish={2},duration={3}\r\x1b[0K",
315 io::stdout().flush().unwrap();
319 /// The CI environment rustbuild is running in. This mainly affects how the logs
321 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
323 /// Not a CI environment.
325 /// The Travis CI environment, for Linux (including Docker) and macOS builds.
327 /// The AppVeyor environment, for Windows builds.
329 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
334 /// Obtains the current CI environment.
335 pub fn current() -> CiEnv {
336 if env::var("TRAVIS").ok().map_or(false, |e| &*e == "true") {
338 } else if env::var("APPVEYOR").ok().map_or(false, |e| &*e == "True") {
340 } else if env::var("TF_BUILD").ok().map_or(false, |e| &*e == "True") {
341 CiEnv::AzurePipelines
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"]);