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_lib_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 /// `push` all components to `buf`. On windows, append `.exe` to the last component.
76 pub fn push_exe_path(mut buf: PathBuf, components: &[&str]) -> PathBuf {
77 let (&file, components) = components.split_last().expect("at least one component required");
78 let mut file = file.to_owned();
81 file.push_str(".exe");
84 buf.extend(components);
90 pub struct TimeIt(bool, Instant);
92 /// Returns an RAII structure that prints out how long it took to drop.
93 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
94 TimeIt(builder.config.dry_run, Instant::now())
97 impl Drop for TimeIt {
99 let time = self.1.elapsed();
101 println!("\tfinished in {}.{:03}", time.as_secs(), time.subsec_nanos() / 1_000_000);
106 /// Symlinks two directories, using junctions on Windows and normal symlinks on
108 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
112 let _ = fs::remove_dir(dest);
113 return symlink_dir_inner(src, dest);
116 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
117 use std::os::unix::fs;
118 fs::symlink(src, dest)
121 // Creating a directory junction on windows involves dealing with reparse
122 // points and the DeviceIoControl function, and this code is a skeleton of
123 // what can be found here:
125 // http://www.flexhex.com/docs/articles/hard-links.phtml
127 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
129 use std::os::windows::ffi::OsStrExt;
132 use winapi::shared::minwindef::{DWORD, WORD};
133 use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
134 use winapi::um::handleapi::CloseHandle;
135 use winapi::um::ioapiset::DeviceIoControl;
136 use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
137 use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
138 use winapi::um::winnt::{
139 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
140 IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
143 #[allow(non_snake_case)]
145 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
147 ReparseDataLength: DWORD,
149 ReparseTargetLength: WORD,
150 ReparseTargetMaximumLength: WORD,
152 ReparseTarget: WCHAR,
155 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
156 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
159 // We're using low-level APIs to create the junction, and these are more
160 // picky about paths. For example, forward slashes cannot be used as a
161 // path separator, so we should try to canonicalize the path first.
162 let target = fs::canonicalize(target)?;
164 fs::create_dir(junction)?;
166 let path = to_u16s(junction)?;
172 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
175 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
179 let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
180 let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
181 let buf = &mut (*db).ReparseTarget as *mut u16;
183 // FIXME: this conversion is very hacky
185 let v = v.iter().map(|x| *x as u16);
186 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
192 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
193 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
194 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
195 (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
198 let res = DeviceIoControl(
200 FSCTL_SET_REPARSE_POINT,
201 data.as_ptr() as *mut _,
202 (*db).ReparseDataLength + 8,
209 let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
216 /// The CI environment rustbuild is running in. This mainly affects how the logs
218 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
220 /// Not a CI environment.
222 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
224 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
229 /// Obtains the current CI environment.
230 pub fn current() -> CiEnv {
231 if env::var("TF_BUILD").map_or(false, |e| e == "True") {
232 CiEnv::AzurePipelines
233 } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
240 /// If in a CI environment, forces the command to run with colors.
241 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
242 if self != CiEnv::None {
243 // Due to use of stamp/docker, the output stream of rustbuild is not
244 // a TTY in CI, so coloring is by-default turned off.
245 // The explicit `TERM=xterm` environment is needed for
246 // `--color always` to actually work. This env var was lost when
247 // compiling through the Makefile. Very strange.
248 cmd.env("TERM", "xterm").args(&["--color", "always"]);
253 pub fn forcing_clang_based_tests() -> bool {
254 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
255 match &var.to_string_lossy().to_lowercase()[..] {
256 "1" | "yes" | "on" => true,
257 "0" | "no" | "off" => false,
259 // Let's make sure typos don't go unnoticed
261 "Unrecognized option '{}' set in \
262 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
272 pub fn use_host_linker(target: &Interned<String>) -> bool {
273 // FIXME: this information should be gotten by checking the linker flavor
274 // of the rustc target
275 !(target.contains("emscripten")
276 || target.contains("wasm32")
277 || target.contains("nvptx")
278 || target.contains("fortanix")
279 || target.contains("fuchsia"))