1 //! Various utility functions used throughout rustbuild.
2 //!
3 //! Simple things like testing the various filesystem operations here and there,
4 //! not a lot of interesting happenings here unfortunately.
5
6 use build_helper::util::{fail, try_run};
7 use std::env;
8 use std::fs;
9 use std::io;
10 use std::path::{Path, PathBuf};
11 use std::process::{Command, Stdio};
12 use std::str;
13 use std::time::{Instant, SystemTime, UNIX_EPOCH};
14
15 use crate::builder::Builder;
16 use crate::config::{Config, TargetSelection};
17 use crate::OnceCell;
18
19 /// A helper macro to `unwrap` a result except also print out details like:
20 ///
21 /// * The file/line of the panic
22 /// * The expression that failed
23 /// * The error itself
24 ///
25 /// This is currently used judiciously throughout the build system rather than
26 /// using a `Result` with `try!`, but this may change one day...
27 #[macro_export]
28 macro_rules! t {
29 ($e:expr) => {
30 match $e {
31 Ok(e) => e,
32 Err(e) => panic!("{} failed with {}", stringify!($e), e),
33 }
34 };
35 // it can show extra info in the second parameter
36 ($e:expr, $extra:expr) => {
37 match $e {
38 Ok(e) => e,
39 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
40 }
41 };
42 }
43 pub use t;
44
45 /// Given an executable called `name`, return the filename for the
46 /// executable for a particular target.
exe(name: &str, target: TargetSelection) -> String47 pub fn exe(name: &str, target: TargetSelection) -> String {
48 if target.contains("windows") {
49 format!("{}.exe", name)
50 } else if target.contains("uefi") {
51 format!("{}.efi", name)
52 } else {
53 name.to_string()
54 }
55 }
56
57 /// Returns `true` if the file name given looks like a dynamic library.
is_dylib(name: &str) -> bool58 pub fn is_dylib(name: &str) -> bool {
59 name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
60 }
61
62 /// Returns `true` if the file name given looks like a debug info file
is_debug_info(name: &str) -> bool63 pub fn is_debug_info(name: &str) -> bool {
64 // FIXME: consider split debug info on other platforms (e.g., Linux, macOS)
65 name.ends_with(".pdb")
66 }
67
68 /// Returns the corresponding relative library directory that the compiler's
69 /// dylibs will be found in.
libdir(target: TargetSelection) -> &'static str70 pub fn libdir(target: TargetSelection) -> &'static str {
71 if target.contains("windows") { "bin" } else { "lib" }
72 }
73
74 /// Adds a list of lookup paths to `cmd`'s dynamic library lookup path.
75 /// If the dylib_path_var is already set for this cmd, the old value will be overwritten!
add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command)76 pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
77 let mut list = dylib_path();
78 for path in path {
79 list.insert(0, path);
80 }
81 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
82 }
83
84 include!("dylib_util.rs");
85
86 /// Adds a list of lookup paths to `cmd`'s link library lookup path.
add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command)87 pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
88 let mut list = link_lib_path();
89 for path in path {
90 list.insert(0, path);
91 }
92 cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
93 }
94
95 /// Returns the environment variable which the link library lookup path
96 /// resides in for this platform.
link_lib_path_var() -> &'static str97 fn link_lib_path_var() -> &'static str {
98 if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
99 }
100
101 /// Parses the `link_lib_path_var()` environment variable, returning a list of
102 /// paths that are members of this lookup path.
link_lib_path() -> Vec<PathBuf>103 fn link_lib_path() -> Vec<PathBuf> {
104 let var = match env::var_os(link_lib_path_var()) {
105 Some(v) => v,
106 None => return vec![],
107 };
108 env::split_paths(&var).collect()
109 }
110
111 pub struct TimeIt(bool, Instant);
112
113 /// Returns an RAII structure that prints out how long it took to drop.
timeit(builder: &Builder<'_>) -> TimeIt114 pub fn timeit(builder: &Builder<'_>) -> TimeIt {
115 TimeIt(builder.config.dry_run(), Instant::now())
116 }
117
118 impl Drop for TimeIt {
drop(&mut self)119 fn drop(&mut self) {
120 let time = self.1.elapsed();
121 if !self.0 {
122 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
123 }
124 }
125 }
126
127 /// Used for download caching
program_out_of_date(stamp: &Path, key: &str) -> bool128 pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
129 if !stamp.exists() {
130 return true;
131 }
132 t!(fs::read_to_string(stamp)) != key
133 }
134
135 /// Symlinks two directories, using junctions on Windows and normal symlinks on
136 /// Unix.
symlink_dir(config: &Config, original: &Path, link: &Path) -> io::Result<()>137 pub fn symlink_dir(config: &Config, original: &Path, link: &Path) -> io::Result<()> {
138 if config.dry_run() {
139 return Ok(());
140 }
141 let _ = fs::remove_dir(link);
142 return symlink_dir_inner(original, link);
143
144 #[cfg(not(windows))]
145 fn symlink_dir_inner(original: &Path, link: &Path) -> io::Result<()> {
146 use std::os::unix::fs;
147 fs::symlink(original, link)
148 }
149
150 #[cfg(windows)]
151 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
152 junction::create(&target, &junction)
153 }
154 }
155
156 /// The CI environment rustbuild is running in. This mainly affects how the logs
157 /// are printed.
158 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
159 pub enum CiEnv {
160 /// Not a CI environment.
161 None,
162 /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds.
163 GitHubActions,
164 }
165
forcing_clang_based_tests() -> bool166 pub fn forcing_clang_based_tests() -> bool {
167 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
168 match &var.to_string_lossy().to_lowercase()[..] {
169 "1" | "yes" | "on" => true,
170 "0" | "no" | "off" => false,
171 other => {
172 // Let's make sure typos don't go unnoticed
173 panic!(
174 "Unrecognized option '{}' set in \
175 RUSTBUILD_FORCE_CLANG_BASED_TESTS",
176 other
177 )
178 }
179 }
180 } else {
181 false
182 }
183 }
184
use_host_linker(target: TargetSelection) -> bool185 pub fn use_host_linker(target: TargetSelection) -> bool {
186 // FIXME: this information should be gotten by checking the linker flavor
187 // of the rustc target
188 !(target.contains("emscripten")
189 || target.contains("wasm32")
190 || target.contains("nvptx")
191 || target.contains("fortanix")
192 || target.contains("fuchsia")
193 || target.contains("bpf")
194 || target.contains("switch"))
195 }
196
is_valid_test_suite_arg<'a, P: AsRef<Path>>( path: &'a Path, suite_path: P, builder: &Builder<'_>, ) -> Option<&'a str>197 pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
198 path: &'a Path,
199 suite_path: P,
200 builder: &Builder<'_>,
201 ) -> Option<&'a str> {
202 let suite_path = suite_path.as_ref();
203 let path = match path.strip_prefix(".") {
204 Ok(p) => p,
205 Err(_) => path,
206 };
207 if !path.starts_with(suite_path) {
208 return None;
209 }
210 let abs_path = builder.src.join(path);
211 let exists = abs_path.is_dir() || abs_path.is_file();
212 if !exists {
213 panic!(
214 "Invalid test suite filter \"{}\": file or directory does not exist",
215 abs_path.display()
216 );
217 }
218 // Since test suite paths are themselves directories, if we don't
219 // specify a directory or file, we'll get an empty string here
220 // (the result of the test suite directory without its suite prefix).
221 // Therefore, we need to filter these out, as only the first --test-args
222 // flag is respected, so providing an empty --test-args conflicts with
223 // any following it.
224 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
225 Some(s) if !s.is_empty() => Some(s),
226 _ => None,
227 }
228 }
229
run(cmd: &mut Command, print_cmd_on_fail: bool)230 pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
231 if try_run(cmd, print_cmd_on_fail).is_err() {
232 crate::detail_exit_macro!(1);
233 }
234 }
235
check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool236 pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
237 let status = match cmd.status() {
238 Ok(status) => status,
239 Err(e) => {
240 println!("failed to execute command: {:?}\nerror: {}", cmd, e);
241 return false;
242 }
243 };
244 if !status.success() && print_cmd_on_fail {
245 println!(
246 "\n\ncommand did not execute successfully: {:?}\n\
247 expected success, got: {}\n\n",
248 cmd, status
249 );
250 }
251 status.success()
252 }
253
run_suppressed(cmd: &mut Command)254 pub fn run_suppressed(cmd: &mut Command) {
255 if !try_run_suppressed(cmd) {
256 crate::detail_exit_macro!(1);
257 }
258 }
259
try_run_suppressed(cmd: &mut Command) -> bool260 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
261 let output = match cmd.output() {
262 Ok(status) => status,
263 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
264 };
265 if !output.status.success() {
266 println!(
267 "\n\ncommand did not execute successfully: {:?}\n\
268 expected success, got: {}\n\n\
269 stdout ----\n{}\n\
270 stderr ----\n{}\n\n",
271 cmd,
272 output.status,
273 String::from_utf8_lossy(&output.stdout),
274 String::from_utf8_lossy(&output.stderr)
275 );
276 }
277 output.status.success()
278 }
279
make(host: &str) -> PathBuf280 pub fn make(host: &str) -> PathBuf {
281 if host.contains("dragonfly")
282 || host.contains("freebsd")
283 || host.contains("netbsd")
284 || host.contains("openbsd")
285 {
286 PathBuf::from("gmake")
287 } else {
288 PathBuf::from("make")
289 }
290 }
291
292 #[track_caller]
output(cmd: &mut Command) -> String293 pub fn output(cmd: &mut Command) -> String {
294 let output = match cmd.stderr(Stdio::inherit()).output() {
295 Ok(status) => status,
296 Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)),
297 };
298 if !output.status.success() {
299 panic!(
300 "command did not execute successfully: {:?}\n\
301 expected success, got: {}",
302 cmd, output.status
303 );
304 }
305 String::from_utf8(output.stdout).unwrap()
306 }
307
output_result(cmd: &mut Command) -> Result<String, String>308 pub fn output_result(cmd: &mut Command) -> Result<String, String> {
309 let output = match cmd.stderr(Stdio::inherit()).output() {
310 Ok(status) => status,
311 Err(e) => return Err(format!("failed to run command: {:?}: {}", cmd, e)),
312 };
313 if !output.status.success() {
314 return Err(format!(
315 "command did not execute successfully: {:?}\n\
316 expected success, got: {}\n{}",
317 cmd,
318 output.status,
319 String::from_utf8(output.stderr).map_err(|err| format!("{err:?}"))?
320 ));
321 }
322 Ok(String::from_utf8(output.stdout).map_err(|err| format!("{err:?}"))?)
323 }
324
325 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
mtime(path: &Path) -> SystemTime326 pub fn mtime(path: &Path) -> SystemTime {
327 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
328 }
329
330 /// Returns `true` if `dst` is up to date given that the file or files in `src`
331 /// are used to generate it.
332 ///
333 /// Uses last-modified time checks to verify this.
up_to_date(src: &Path, dst: &Path) -> bool334 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
335 if !dst.exists() {
336 return false;
337 }
338 let threshold = mtime(dst);
339 let meta = match fs::metadata(src) {
340 Ok(meta) => meta,
341 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
342 };
343 if meta.is_dir() {
344 dir_up_to_date(src, threshold)
345 } else {
346 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
347 }
348 }
349
dir_up_to_date(src: &Path, threshold: SystemTime) -> bool350 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
351 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
352 let meta = t!(e.metadata());
353 if meta.is_dir() {
354 dir_up_to_date(&e.path(), threshold)
355 } else {
356 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
357 }
358 })
359 }
360
361 /// Copied from `std::path::absolute` until it stabilizes.
362 ///
363 /// FIXME: this shouldn't exist.
absolute(path: &Path) -> PathBuf364 pub(crate) fn absolute(path: &Path) -> PathBuf {
365 if path.as_os_str().is_empty() {
366 panic!("can't make empty path absolute");
367 }
368 #[cfg(unix)]
369 {
370 t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
371 }
372 #[cfg(windows)]
373 {
374 t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
375 }
376 #[cfg(not(any(unix, windows)))]
377 {
378 println!("warning: bootstrap is not supported on non-unix platforms");
379 t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
380 }
381 }
382
383 #[cfg(unix)]
384 /// Make a POSIX path absolute without changing its semantics.
absolute_unix(path: &Path) -> io::Result<PathBuf>385 fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
386 // This is mostly a wrapper around collecting `Path::components`, with
387 // exceptions made where this conflicts with the POSIX specification.
388 // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
389 // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
390
391 use std::os::unix::prelude::OsStrExt;
392 let mut components = path.components();
393 let path_os = path.as_os_str().as_bytes();
394
395 let mut normalized = if path.is_absolute() {
396 // "If a pathname begins with two successive <slash> characters, the
397 // first component following the leading <slash> characters may be
398 // interpreted in an implementation-defined manner, although more than
399 // two leading <slash> characters shall be treated as a single <slash>
400 // character."
401 if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
402 components.next();
403 PathBuf::from("//")
404 } else {
405 PathBuf::new()
406 }
407 } else {
408 env::current_dir()?
409 };
410 normalized.extend(components);
411
412 // "Interfaces using pathname resolution may specify additional constraints
413 // when a pathname that does not name an existing directory contains at
414 // least one non- <slash> character and contains one or more trailing
415 // <slash> characters".
416 // A trailing <slash> is also meaningful if "a symbolic link is
417 // encountered during pathname resolution".
418
419 if path_os.ends_with(b"/") {
420 normalized.push("");
421 }
422
423 Ok(normalized)
424 }
425
426 #[cfg(windows)]
absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf>427 fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
428 use std::ffi::OsString;
429 use std::io::Error;
430 use std::os::windows::ffi::{OsStrExt, OsStringExt};
431 use std::ptr::null_mut;
432 #[link(name = "kernel32")]
433 extern "system" {
434 fn GetFullPathNameW(
435 lpFileName: *const u16,
436 nBufferLength: u32,
437 lpBuffer: *mut u16,
438 lpFilePart: *mut *const u16,
439 ) -> u32;
440 }
441
442 unsafe {
443 // encode the path as UTF-16
444 let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
445 let mut buffer = Vec::new();
446 // Loop until either success or failure.
447 loop {
448 // Try to get the absolute path
449 let len = GetFullPathNameW(
450 path.as_ptr(),
451 buffer.len().try_into().unwrap(),
452 buffer.as_mut_ptr(),
453 null_mut(),
454 );
455 match len as usize {
456 // Failure
457 0 => return Err(Error::last_os_error()),
458 // Buffer is too small, resize.
459 len if len > buffer.len() => buffer.resize(len, 0),
460 // Success!
461 len => {
462 buffer.truncate(len);
463 return Ok(OsString::from_wide(&buffer).into());
464 }
465 }
466 }
467 }
468 }
469
470 /// Adapted from <https://github.com/llvm/llvm-project/blob/782e91224601e461c019e0a4573bbccc6094fbcd/llvm/cmake/modules/HandleLLVMOptions.cmake#L1058-L1079>
471 ///
472 /// When `clang-cl` is used with instrumentation, we need to add clang's runtime library resource
473 /// directory to the linker flags, otherwise there will be linker errors about the profiler runtime
474 /// missing. This function returns the path to that directory.
get_clang_cl_resource_dir(clang_cl_path: &str) -> PathBuf475 pub fn get_clang_cl_resource_dir(clang_cl_path: &str) -> PathBuf {
476 // Similar to how LLVM does it, to find clang's library runtime directory:
477 // - we ask `clang-cl` to locate the `clang_rt.builtins` lib.
478 let mut builtins_locator = Command::new(clang_cl_path);
479 builtins_locator.args(&["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
480
481 let clang_rt_builtins = output(&mut builtins_locator);
482 let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
483 assert!(
484 clang_rt_builtins.exists(),
485 "`clang-cl` must correctly locate the library runtime directory"
486 );
487
488 // - the profiler runtime will be located in the same directory as the builtins lib, like
489 // `$LLVM_DISTRO_ROOT/lib/clang/$LLVM_VERSION/lib/windows`.
490 let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
491 clang_rt_dir.to_path_buf()
492 }
493
lld_flag_no_threads(is_windows: bool) -> &'static str494 pub fn lld_flag_no_threads(is_windows: bool) -> &'static str {
495 static LLD_NO_THREADS: OnceCell<(&'static str, &'static str)> = OnceCell::new();
496 let (windows, other) = LLD_NO_THREADS.get_or_init(|| {
497 let out = output(Command::new("lld").arg("-flavor").arg("ld").arg("--version"));
498 let newer = match (out.find(char::is_numeric), out.find('.')) {
499 (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
500 _ => true,
501 };
502 if newer { ("/threads:1", "--threads=1") } else { ("/no-threads", "--no-threads") }
503 });
504 if is_windows { windows } else { other }
505 }
506