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::config::{Config, TargetSelection};
19 /// Given an executable called `name`, return the filename for the
20 /// executable for a particular target.
21 pub fn exe(name: &str, target: TargetSelection) -> String {
22 if target.contains("windows") { format!("{}.exe", name) } else { name.to_string() }
25 /// Returns `true` if the file name given looks like a dynamic library.
26 pub fn is_dylib(name: &str) -> bool {
27 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
30 /// Returns `true` if the file name given looks like a debug info file
31 pub fn is_debug_info(name: &str) -> bool {
32 // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
33 name.ends_with(".pdb")
36 /// Returns the corresponding relative library directory that the compiler's
37 /// dylibs will be found in.
38 pub fn libdir(target: TargetSelection) -> &'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 /// If The dylib_path_par is already set for this cmd, the old value will be overwritten!
44 pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
45 let mut list = dylib_path();
49 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
52 include!("dylib_util.rs");
54 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
55 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
56 let mut list = link_lib_path();
60 cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
63 /// Returns the environment variable which the link library lookup path
64 /// resides in for this platform.
65 fn link_lib_path_var() -> &'static str {
66 if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
69 /// Parses the `link_lib_path_var()` environment variable, returning a list of
70 /// paths that are members of this lookup path.
71 fn link_lib_path() -> Vec<PathBuf> {
72 let var = match env::var_os(link_lib_path_var()) {
74 None => return vec![],
76 env::split_paths(&var).collect()
79 pub struct TimeIt(bool, Instant);
81 /// Returns an RAII structure that prints out how long it took to drop.
82 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
83 TimeIt(builder.config.dry_run, Instant::now())
86 impl Drop for TimeIt {
88 let time = self.1.elapsed();
90 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
95 /// Symlinks two directories, using junctions on Windows and normal symlinks on
97 pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
101 let _ = fs::remove_dir(dest);
102 return symlink_dir_inner(src, dest);
105 fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> {
106 use std::os::unix::fs;
107 fs::symlink(src, dest)
110 // Creating a directory junction on windows involves dealing with reparse
111 // points and the DeviceIoControl function, and this code is a skeleton of
112 // what can be found here:
114 // http://www.flexhex.com/docs/articles/hard-links.phtml
116 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
118 use std::os::windows::ffi::OsStrExt;
121 use winapi::shared::minwindef::{DWORD, WORD};
122 use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
123 use winapi::um::handleapi::CloseHandle;
124 use winapi::um::ioapiset::DeviceIoControl;
125 use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
126 use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
127 use winapi::um::winnt::{
128 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
129 IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
132 #[allow(non_snake_case)]
134 struct REPARSE_MOUNTPOINT_DATA_BUFFER {
136 ReparseDataLength: DWORD,
138 ReparseTargetLength: WORD,
139 ReparseTargetMaximumLength: WORD,
141 ReparseTarget: WCHAR,
144 fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
145 Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
148 // We're using low-level APIs to create the junction, and these are more
149 // picky about paths. For example, forward slashes cannot be used as a
150 // path separator, so we should try to canonicalize the path first.
151 let target = fs::canonicalize(target)?;
153 fs::create_dir(junction)?;
155 let path = to_u16s(junction)?;
161 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
164 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
168 let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
169 let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
170 let buf = &mut (*db).ReparseTarget as *mut u16;
172 // FIXME: this conversion is very hacky
174 let v = v.iter().map(|x| *x as u16);
175 for c in v.chain(target.as_os_str().encode_wide().skip(4)) {
181 (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
182 (*db).ReparseTargetMaximumLength = (i * 2) as WORD;
183 (*db).ReparseTargetLength = ((i - 1) * 2) as WORD;
184 (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12;
187 let res = DeviceIoControl(
189 FSCTL_SET_REPARSE_POINT,
190 data.as_ptr() as *mut _,
191 (*db).ReparseDataLength + 8,
198 let out = if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) };
205 /// The CI environment rustbuild is running in. This mainly affects how the logs
207 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
209 /// Not a CI environment.
211 /// The Azure Pipelines environment, for Linux (including Docker), Windows, and macOS builds.
213 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
218 /// Obtains the current CI environment.
219 pub fn current() -> CiEnv {
220 if env::var("TF_BUILD").map_or(false, |e| e == "True") {
221 CiEnv::AzurePipelines
222 } else if env::var("GITHUB_ACTIONS").map_or(false, |e| e == "true") {
229 /// If in a CI environment, forces the command to run with colors.
230 pub fn force_coloring_in_ci(self, cmd: &mut Command) {
231 if self != CiEnv::None {
232 // Due to use of stamp/docker, the output stream of rustbuild is not
233 // a TTY in CI, so coloring is by-default turned off.
234 // The explicit `TERM=xterm` environment is needed for
235 // `--color always` to actually work. This env var was lost when
236 // compiling through the Makefile. Very strange.
237 cmd.env("TERM", "xterm").args(&["--color", "always"]);
242 pub fn forcing_clang_based_tests() -> bool {
243 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
244 match &var.to_string_lossy().to_lowercase()[..] {
245 "1" | "yes" | "on" => true,
246 "0" | "no" | "off" => false,
248 // Let's make sure typos don't go unnoticed
250 "Unrecognized option '{}' set in \
251 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
261 pub fn use_host_linker(target: TargetSelection) -> bool {
262 // FIXME: this information should be gotten by checking the linker flavor
263 // of the rustc target
264 !(target.contains("emscripten")
265 || target.contains("wasm32")
266 || target.contains("nvptx")
267 || target.contains("fortanix")
268 || target.contains("fuchsia")
269 || target.contains("bpf"))
272 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
275 builder: &Builder<'_>,
276 ) -> Option<&'a str> {
277 let suite_path = suite_path.as_ref();
278 let path = match path.strip_prefix(".") {
282 if !path.starts_with(suite_path) {
285 let exists = path.is_dir() || path.is_file();
287 if let Some(p) = 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),