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.
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::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 /// The CI environment rustbuild is running in. This mainly affects how the logs
259 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
261 /// Not a CI environment.
263 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
268 /// Obtains the current CI environment.
269 pub fn current() -> CiEnv {
270 if env::var("TF_BUILD").ok().map_or(false, |e| &*e == "True") {
271 CiEnv::AzurePipelines
277 /// If in a CI environment, forces the command to run with colors.
278 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
279 if self != CiEnv::None {
280 // Due to use of stamp/docker, the output stream of rustbuild is not
281 // a TTY in CI, so coloring is by-default turned off.
282 // The explicit `TERM=xterm` environment is needed for
283 // `--color always` to actually work. This env var was lost when
284 // compiling through the Makefile. Very strange.
285 cmd.env("TERM", "xterm").args(&["--color", "always"]);
290 pub fn forcing_clang_based_tests() -> bool {
291 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
292 match &var.to_string_lossy().to_lowercase()[..] {
293 "1" | "yes" | "on" => true,
294 "0" | "no" | "off" => false,
296 // Let's make sure typos don't go unnoticed
297 panic!("Unrecognized option '{}' set in \
298 RUSTBUILD_FORCE_CLANG_BASED_TESTS", other)