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;
14 use crate::build_helper::t;
15 use crate::builder::Builder;
16 use crate::config::{Config, TargetSelection};
18 /// Given an executable called `name`, return the filename for the
19 /// executable for a particular target.
20 pub fn exe(name: &str, target: TargetSelection) -> String {
21 if target.contains("windows") { format!("{}.exe", name) } else { name.to_string() }
24 /// Returns `true` if the file name given looks like a dynamic library.
25 pub fn is_dylib(name: &str) -> bool {
26 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
29 /// Returns `true` if the file name given looks like a debug info file
30 pub fn is_debug_info(name: &str) -> bool {
31 // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
32 name.ends_with(".pdb")
35 /// Returns the corresponding relative library directory that the compiler's
36 /// dylibs will be found in.
37 pub fn libdir(target: TargetSelection) -> &'static str {
38 if target.contains("windows") { "bin" } else { "lib" }
41 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
42 /// If The dylib_path_par is already set for this cmd, the old value will be overwritten!
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 include!("dylib_util.rs");
53 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
54 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
55 let mut list = link_lib_path();
59 cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
62 /// Returns the environment variable which the link library lookup path
63 /// resides in for this platform.
64 fn link_lib_path_var() -> &'static str {
65 if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
68 /// Parses the `link_lib_path_var()` environment variable, returning a list of
69 /// paths that are members of this lookup path.
70 fn link_lib_path() -> Vec<PathBuf> {
71 let var = match env::var_os(link_lib_path_var()) {
73 None => return vec![],
75 env::split_paths(&var).collect()
78 pub struct TimeIt(bool, Instant);
80 /// Returns an RAII structure that prints out how long it took to drop.
81 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
82 TimeIt(builder.config.dry_run, Instant::now())
85 impl Drop for TimeIt {
87 let time = self.1.elapsed();
89 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
94 /// Symlinks two directories, using junctions on Windows and normal symlinks on
96 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
100 let _ = fs::remove_dir(dest);
101 return symlink_dir_inner(src, dest);
104 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
105 use std::os::unix::fs;
106 fs::symlink(src, dest)
109 // Creating a directory junction on windows involves dealing with reparse
110 // points and the DeviceIoControl function, and this code is a skeleton of
111 // what can be found here:
113 // http://www.flexhex.com/docs/articles/hard-links.phtml
115 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
117 use std::os::windows::ffi::OsStrExt;
120 use winapi::shared::minwindef::{DWORD, WORD};
121 use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
122 use winapi::um::handleapi::CloseHandle;
123 use winapi::um::ioapiset::DeviceIoControl;
124 use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
125 use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
126 use winapi::um::winnt::{
127 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
128 IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
131 #[allow(non_snake_case)]
133 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
135 ReparseDataLength: DWORD,
137 ReparseTargetLength: WORD,
138 ReparseTargetMaximumLength: WORD,
140 ReparseTarget: WCHAR,
143 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
144 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
147 // We're using low-level APIs to create the junction, and these are more
148 // picky about paths. For example, forward slashes cannot be used as a
149 // path separator, so we should try to canonicalize the path first.
150 let target = fs::canonicalize(target)?;
152 fs::create_dir(junction)?;
154 let path = to_u16s(junction)?;
160 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
163 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
167 let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
168 let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
169 let buf = &mut (*db).ReparseTarget as *mut u16;
171 // FIXME: this conversion is very hacky
173 let v = v.iter().map(|x| *x as u16);
174 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
180 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
181 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
182 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
183 (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
186 let res = DeviceIoControl(
188 FSCTL_SET_REPARSE_POINT,
189 data.as_ptr() as *mut _,
190 (*db).ReparseDataLength + 8,
197 let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
204 /// The CI environment rustbuild is running in. This mainly affects how the logs
206 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
208 /// Not a CI environment.
210 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
212 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
217 /// Obtains the current CI environment.
218 pub fn current() -> CiEnv {
219 if env::var("TF_BUILD").map_or(false, |e| e == "True") {
220 CiEnv::AzurePipelines
221 } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
228 /// If in a CI environment, forces the command to run with colors.
229 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
230 if self != CiEnv::None {
231 // Due to use of stamp/docker, the output stream of rustbuild is not
232 // a TTY in CI, so coloring is by-default turned off.
233 // The explicit `TERM=xterm` environment is needed for
234 // `--color always` to actually work. This env var was lost when
235 // compiling through the Makefile. Very strange.
236 cmd.env("TERM", "xterm").args(&["--color", "always"]);
241 pub fn forcing_clang_based_tests() -> bool {
242 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
243 match &var.to_string_lossy().to_lowercase()[..] {
244 "1" | "yes" | "on" => true,
245 "0" | "no" | "off" => false,
247 // Let's make sure typos don't go unnoticed
249 "Unrecognized option '{}' set in \
250 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
260 pub fn use_host_linker(target: TargetSelection) -> bool {
261 // FIXME: this information should be gotten by checking the linker flavor
262 // of the rustc target
263 !(target.contains("emscripten")
264 || target.contains("wasm32")
265 || target.contains("nvptx")
266 || target.contains("fortanix")
267 || target.contains("fuchsia")
268 || target.contains("bpf"))
271 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
274 builder: &Builder<'_>,
275 ) -> Option<&'a str> {
276 let suite_path = suite_path.as_ref();
277 let path = match path.strip_prefix(".") {
281 if !path.starts_with(suite_path) {
284 let abs_path = builder.src.join(path);
285 let exists = abs_path.is_dir() || abs_path.is_file();
287 if let Some(p) = abs_path.to_str() {
288 builder.info(&format!("Warning: Skipping \"{}\": not a regular file or directory", p));
292 // Since test suite paths are themselves directories, if we don't
293 // specify a directory or file, we'll get an empty string here
294 // (the result of the test suite directory without its suite prefix).
295 // Therefore, we need to filter these out, as only the first --test-args
296 // flag is respected, so providing an empty --test-args conflicts with
298 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
299 Some(s) if !s.is_empty() => Some(s),