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::path::{Path, PathBuf};
10 use std::process::Command;
12 use std::time::Instant;
16 use crate::builder::Builder;
17 use crate::cache::Interned;
18 use crate::config::Config;
20 /// Returns the `name` as the filename of a static library for `target`.
21 pub fn staticlib(name: &str, target: &str) -> String {
22 if target.contains("windows") { format!("{}.lib", name) } else { format!("lib{}.a", name) }
25 /// Given an executable called `name`, return the filename for the
26 /// executable for a particular target.
27 pub fn exe(name: &str, target: &str) -> String {
28 if target.contains("windows") { format!("{}.exe", name) } else { name.to_string() }
31 /// Returns `true` if the file name given looks like a dynamic library.
32 pub fn is_dylib(name: &str) -> bool {
33 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
36 /// Returns the corresponding relative library directory that the compiler's
37 /// dylibs will be found in.
38 pub fn libdir(target: &str) -> &'static str {
39 if target.contains("windows") { "bin" } else { "lib" }
42 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
43 pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
44 let mut list = dylib_path();
48 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
51 /// Returns the environment variable which the dynamic library lookup path
52 /// resides in for this platform.
53 pub fn dylib_path_var() -> &'static str {
54 if cfg!(target_os = "windows") {
56 } else if cfg!(target_os = "macos") {
58 } else if cfg!(target_os = "haiku") {
65 /// Parses the `dylib_path_var()` environment variable, returning a list of
66 /// paths that are members of this lookup path.
67 pub fn dylib_path() -> Vec<PathBuf> {
68 let var = match env::var_os(dylib_path_var()) {
70 None => return vec![],
72 env::split_paths(&var).collect()
75 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
76 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
77 let mut list = link_lib_path();
81 cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
84 /// Returns the environment variable which the link library lookup path
85 /// resides in for this platform.
86 fn link_lib_path_var() -> &'static str {
87 if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
90 /// Parses the `link_lib_path_var()` environment variable, returning a list of
91 /// paths that are members of this lookup path.
92 fn link_lib_path() -> Vec<PathBuf> {
93 let var = match env::var_os(link_lib_path_var()) {
95 None => return vec![],
97 env::split_paths(&var).collect()
100 /// `push` all components to `buf`. On windows, append `.exe` to the last component.
101 pub fn push_exe_path(mut buf: PathBuf, components: &[&str]) -> PathBuf {
102 let (&file, components) = components.split_last().expect("at least one component required");
103 let mut file = file.to_owned();
106 file.push_str(".exe");
109 buf.extend(components);
115 pub struct TimeIt(bool, Instant);
117 /// Returns an RAII structure that prints out how long it took to drop.
118 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
119 TimeIt(builder.config.dry_run, Instant::now())
122 impl Drop for TimeIt {
124 let time = self.1.elapsed();
126 println!("\tfinished in {}.{:03}", time.as_secs(), time.subsec_millis());
131 /// Symlinks two directories, using junctions on Windows and normal symlinks on
133 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
137 let _ = fs::remove_dir(dest);
138 return symlink_dir_inner(src, dest);
141 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
142 use std::os::unix::fs;
143 fs::symlink(src, dest)
146 // Creating a directory junction on windows involves dealing with reparse
147 // points and the DeviceIoControl function, and this code is a skeleton of
148 // what can be found here:
150 // http://www.flexhex.com/docs/articles/hard-links.phtml
152 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
154 use std::os::windows::ffi::OsStrExt;
157 use winapi::shared::minwindef::{DWORD, WORD};
158 use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
159 use winapi::um::handleapi::CloseHandle;
160 use winapi::um::ioapiset::DeviceIoControl;
161 use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
162 use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
163 use winapi::um::winnt::{
164 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
165 IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
168 #[allow(non_snake_case)]
170 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
172 ReparseDataLength: DWORD,
174 ReparseTargetLength: WORD,
175 ReparseTargetMaximumLength: WORD,
177 ReparseTarget: WCHAR,
180 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
181 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
184 // We're using low-level APIs to create the junction, and these are more
185 // picky about paths. For example, forward slashes cannot be used as a
186 // path separator, so we should try to canonicalize the path first.
187 let target = fs::canonicalize(target)?;
189 fs::create_dir(junction)?;
191 let path = to_u16s(junction)?;
197 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
200 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
204 let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
205 let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
206 let buf = &mut (*db).ReparseTarget as *mut u16;
208 // FIXME: this conversion is very hacky
210 let v = v.iter().map(|x| *x as u16);
211 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
217 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
218 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
219 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
220 (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
223 let res = DeviceIoControl(
225 FSCTL_SET_REPARSE_POINT,
226 data.as_ptr() as *mut _,
227 (*db).ReparseDataLength + 8,
234 let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
241 /// The CI environment rustbuild is running in. This mainly affects how the logs
243 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
245 /// Not a CI environment.
247 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
249 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
254 /// Obtains the current CI environment.
255 pub fn current() -> CiEnv {
256 if env::var("TF_BUILD").map_or(false, |e| e == "True") {
257 CiEnv::AzurePipelines
258 } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
265 /// If in a CI environment, forces the command to run with colors.
266 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
267 if self != CiEnv::None {
268 // Due to use of stamp/docker, the output stream of rustbuild is not
269 // a TTY in CI, so coloring is by-default turned off.
270 // The explicit `TERM=xterm` environment is needed for
271 // `--color always` to actually work. This env var was lost when
272 // compiling through the Makefile. Very strange.
273 cmd.env("TERM", "xterm").args(&["--color", "always"]);
278 pub fn forcing_clang_based_tests() -> bool {
279 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
280 match &var.to_string_lossy().to_lowercase()[..] {
281 "1" | "yes" | "on" => true,
282 "0" | "no" | "off" => false,
284 // Let's make sure typos don't go unnoticed
286 "Unrecognized option '{}' set in \
287 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
297 pub fn use_host_linker(target: &Interned<String>) -> bool {
298 // FIXME: this information should be gotten by checking the linker flavor
299 // of the rustc target
300 !(target.contains("emscripten")
301 || target.contains("wasm32")
302 || target.contains("nvptx")
303 || target.contains("fortanix")
304 || target.contains("fuchsia"))