1use std::ffi::OsStr;
7use std::path::{Path, PathBuf};
8use std::sync::OnceLock;
9use std::thread::panicking;
10use std::time::{Instant, SystemTime, UNIX_EPOCH};
11use std::{env, fs, io, panic, str};
12
13use build_helper::ci::CiEnv;
14use object::read::archive::ArchiveFile;
15pub(crate) use shim_utils::{dylib_path, dylib_path_var};
16
17pub(crate) use self::macros::t;
18use crate::core::builder::{Builder, StepStack};
19use crate::core::config::{BootstrapOverrideLld, Config, TargetSelection};
20use crate::utils::exec::{BootstrapCommand, command};
21
22#[cfg(test)]
23mod tests;
24
25pub struct PanicTracker<'a>(pub &'a panic::Location<'a>);
28
29impl Drop for PanicTracker<'_> {
30 fn drop(&mut self) {
31 if panicking() {
32 eprintln!(
33 "Panic was initiated from {}:{}:{}",
34 self.0.file(),
35 self.0.line(),
36 self.0.column()
37 );
38 }
39 }
40}
41
42mod macros {
43 macro_rules! t {
52 ($e:expr) => {{
53 let _panic_guard = $crate::utils::helpers::PanicTracker(std::panic::Location::caller());
54 match $e {
55 Ok(e) => e,
56 Err(e) => panic!("{} failed with {}", stringify!($e), e),
57 }
58 }};
59 ($e:expr, $extra:expr) => {{
61 let _panic_guard = $crate::utils::helpers::PanicTracker(std::panic::Location::caller());
62 match $e {
63 Ok(e) => e,
64 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
65 }
66 }};
67 }
68
69 pub(crate) use t;
70}
71
72pub fn exe(name: &str, target: TargetSelection) -> String {
73 shim_utils::exe(name, &target.triple)
74}
75
76pub fn split_debuginfo(name: impl Into<PathBuf>) -> Option<PathBuf> {
78 let path = name.into();
81 let pdb = path.with_extension("pdb");
82 if pdb.exists() {
83 return Some(pdb);
84 }
85
86 let file_name = pdb.file_name()?.to_str()?.replace("-", "_");
88
89 let pdb: PathBuf = [path.parent()?, Path::new(&file_name)].into_iter().collect();
90 pdb.exists().then_some(pdb)
91}
92
93pub fn is_dylib(path: &Path) -> bool {
95 path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| {
96 ext == "dylib" || ext == "so" || ext == "dll" || (ext == "a" && is_aix_shared_archive(path))
97 })
98}
99
100pub fn submodule_path_of(builder: &Builder<'_>, path: &str) -> Option<String> {
102 submodule_path_of_paths(builder.submodule_paths(), path)
103}
104
105fn submodule_path_of_paths(submodule_paths: &[String], path: &str) -> Option<String> {
106 let path = Path::new(path);
107 submodule_paths.iter().find_map(|submodule_path| {
108 if path.starts_with(submodule_path) { Some(submodule_path.to_string()) } else { None }
109 })
110}
111
112fn is_aix_shared_archive(path: &Path) -> bool {
113 let file = match fs::File::open(path) {
114 Ok(file) => file,
115 Err(_) => return false,
116 };
117 let reader = object::ReadCache::new(file);
118 let archive = match ArchiveFile::parse(&reader) {
119 Ok(result) => result,
120 Err(_) => return false,
121 };
122
123 archive
124 .members()
125 .filter_map(Result::ok)
126 .any(|entry| String::from_utf8_lossy(entry.name()).contains(".so"))
127}
128
129pub fn is_debug_info(name: &str) -> bool {
131 name.ends_with(".pdb")
133}
134
135pub fn libdir(target: TargetSelection) -> &'static str {
138 if target.is_windows() || target.contains("cygwin") { "bin" } else { "lib" }
139}
140
141pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut BootstrapCommand) {
144 let paths = path.into_iter().chain(dylib_path());
145 cmd.env(dylib_path_var(), t!(env::join_paths(paths)));
146}
147
148pub struct TimeIt(bool, Instant);
149
150pub fn timeit(builder: &Builder<'_>) -> TimeIt {
152 TimeIt(builder.config.dry_run(), Instant::now())
153}
154
155impl Drop for TimeIt {
156 fn drop(&mut self) {
157 let time = self.1.elapsed();
158 if !self.0 {
159 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
160 }
161 }
162}
163
164pub fn symlink_dir(config: &Config, original: &Path, link: &Path) -> io::Result<()> {
167 if config.dry_run() {
168 return Ok(());
169 }
170 let _ = fs::remove_dir_all(link);
171 return symlink_dir_inner(original, link);
172
173 #[cfg(not(windows))]
174 fn symlink_dir_inner(original: &Path, link: &Path) -> io::Result<()> {
175 use std::os::unix::fs;
176 fs::symlink(original, link)
177 }
178
179 #[cfg(windows)]
180 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
181 junction::create(target, junction)
182 }
183}
184
185pub fn is_symlink_dir(_metadata: &fs::Metadata) -> bool {
187 #[cfg(windows)]
188 {
189 use std::os::windows::fs::FileTypeExt;
190 _metadata.file_type().is_symlink_dir()
191 }
192 #[cfg(not(windows))]
193 false
194}
195
196pub fn get_host_target() -> TargetSelection {
198 TargetSelection::from_user(env!("BUILD_TRIPLE"))
199}
200
201pub fn move_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
204 match fs::rename(&from, &to) {
205 Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
206 std::fs::copy(&from, &to)?;
207 std::fs::remove_file(&from)
208 }
209 r => r,
210 }
211}
212
213pub fn forcing_clang_based_tests() -> bool {
214 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
215 match &var.to_string_lossy().to_lowercase()[..] {
216 "1" | "yes" | "on" => true,
217 "0" | "no" | "off" => false,
218 other => {
219 panic!(
221 "Unrecognized option '{other}' set in \
222 RUSTBUILD_FORCE_CLANG_BASED_TESTS"
223 )
224 }
225 }
226 } else {
227 false
228 }
229}
230
231pub fn use_host_linker(target: TargetSelection) -> bool {
232 !(target.contains("emscripten")
235 || target.contains("wasm32")
236 || target.contains("nvptx")
237 || target.contains("fortanix")
238 || target.contains("fuchsia")
239 || target.contains("bpf")
240 || target.contains("switch")
241 || target.contains("l4re"))
242}
243
244pub fn target_supports_cranelift_backend(target: TargetSelection) -> bool {
245 if target.contains("linux") {
246 target.contains("x86_64")
247 || target.contains("aarch64")
248 || target.contains("s390x")
249 || target.contains("riscv64gc")
250 } else if target.contains("darwin") {
251 target.contains("x86_64") || target.contains("aarch64")
252 } else if target.is_windows() {
253 target.contains("x86_64")
254 } else {
255 false
256 }
257}
258
259pub enum TestFilterCategory<'a> {
262 Fullsuite,
264 Arg(&'a str),
267 Uninteresting,
269}
270
271pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
272 path: &'a Path,
273 suite_path: P,
274 builder: &Builder<'_>,
275) -> TestFilterCategory<'a> {
276 let suite_path = suite_path.as_ref();
277 let path = path.trim_prefix(".");
278 if !path.starts_with(suite_path) {
279 return TestFilterCategory::Uninteresting;
280 }
281 let abs_path = builder.src.join(path);
282 let exists = abs_path.is_dir() || abs_path.is_file();
283 if !exists {
284 panic!(
285 "Invalid test suite filter \"{}\": file or directory does not exist",
286 abs_path.display()
287 );
288 }
289 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
296 Some(s) if !s.is_empty() => TestFilterCategory::Arg(s),
297 _ => TestFilterCategory::Fullsuite,
298 }
299}
300
301pub fn make(host: &str) -> PathBuf {
302 if host.contains("dragonfly")
303 || host.contains("freebsd")
304 || host.contains("netbsd")
305 || host.contains("openbsd")
306 {
307 PathBuf::from("gmake")
308 } else {
309 PathBuf::from("make")
310 }
311}
312
313pub fn mtime(path: &Path) -> SystemTime {
315 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
316}
317
318pub fn up_to_date(src: &Path, dst: &Path) -> bool {
323 if !dst.exists() {
324 return false;
325 }
326 let threshold = mtime(dst);
327 let meta = match fs::metadata(src) {
328 Ok(meta) => meta,
329 Err(e) => panic!("source {src:?} failed to get metadata: {e}"),
330 };
331 if meta.is_dir() {
332 dir_up_to_date(src, threshold)
333 } else {
334 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
335 }
336}
337
338pub fn unhashed_basename(obj: &Path) -> &str {
343 let basename = obj.file_stem().unwrap().to_str().expect("UTF-8 file name");
344 basename.split_once('-').unwrap().1
345}
346
347fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
348 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
349 let meta = t!(e.metadata());
350 if meta.is_dir() {
351 dir_up_to_date(&e.path(), threshold)
352 } else {
353 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
354 }
355 })
356}
357
358pub fn get_clang_cl_resource_dir(builder: &Builder<'_>, clang_cl_path: &str) -> PathBuf {
364 let mut builtins_locator = command(clang_cl_path);
367 builtins_locator.args(["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
368 builtins_locator.run_in_dry_run();
369
370 let clang_rt_builtins = builtins_locator.run_capture_stdout(builder).stdout();
371 let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
372 assert!(
373 clang_rt_builtins.exists(),
374 "`clang-cl` must correctly locate the library runtime directory"
375 );
376
377 let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
380 clang_rt_dir.to_path_buf()
381}
382
383fn lld_flag_no_threads(
387 builder: &Builder<'_>,
388 bootstrap_override_lld: BootstrapOverrideLld,
389 is_windows: bool,
390) -> &'static str {
391 static LLD_NO_THREADS: OnceLock<(&'static str, &'static str)> = OnceLock::new();
392
393 let new_flags = ("/threads:1", "--threads=1");
394 let old_flags = ("/no-threads", "--no-threads");
395
396 let (windows_flag, other_flag) = LLD_NO_THREADS.get_or_init(|| {
397 let newer_version = match bootstrap_override_lld {
398 BootstrapOverrideLld::External => {
399 let mut cmd = command("lld");
400 cmd.arg("-flavor").arg("ld").arg("--version");
401 let out = cmd.run_capture_stdout(builder).stdout();
402 match (out.find(char::is_numeric), out.find('.')) {
403 (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
404 _ => true,
405 }
406 }
407 _ => true,
408 };
409 if newer_version { new_flags } else { old_flags }
410 });
411 if is_windows { windows_flag } else { other_flag }
412}
413
414pub fn dir_is_empty(dir: &Path) -> bool {
415 t!(std::fs::read_dir(dir), dir).next().is_none()
416}
417
418pub fn extract_beta_rev(version: &str) -> Option<String> {
423 let parts = version.splitn(2, "-beta.").collect::<Vec<_>>();
424 parts.get(1).and_then(|s| s.find(' ').map(|p| s[..p].to_string()))
425}
426
427pub enum LldThreads {
428 Yes,
429 No,
430}
431
432pub fn linker_args(
434 builder: &Builder<'_>,
435 target: TargetSelection,
436 lld_threads: LldThreads,
437) -> Vec<String> {
438 let mut args = linker_flags(builder, target, lld_threads);
439
440 if let Some(linker) = builder.linker(target) {
441 args.push(format!("-Clinker={}", linker.display()));
442 }
443
444 args
445}
446
447pub fn linker_flags(
450 builder: &Builder<'_>,
451 target: TargetSelection,
452 lld_threads: LldThreads,
453) -> Vec<String> {
454 let mut args = vec![];
455 if !builder.is_lld_direct_linker(target) && builder.config.bootstrap_override_lld.is_used() {
456 match builder.config.bootstrap_override_lld {
457 BootstrapOverrideLld::External => {
458 args.push("-Clinker-features=+lld".to_string());
459 args.push("-Clink-self-contained=-linker".to_string());
460 args.push("-Zunstable-options".to_string());
461 }
462 BootstrapOverrideLld::SelfContained => {
463 args.push("-Clinker-features=+lld".to_string());
464 args.push("-Clink-self-contained=+linker".to_string());
465 args.push("-Zunstable-options".to_string());
466 }
467 BootstrapOverrideLld::None => unreachable!(),
468 };
469
470 if matches!(lld_threads, LldThreads::No) {
471 args.push(format!(
472 "-Clink-arg=-Wl,{}",
473 lld_flag_no_threads(
474 builder,
475 builder.config.bootstrap_override_lld,
476 target.is_windows()
477 )
478 ));
479 }
480 }
481 args
482}
483
484pub fn add_rustdoc_cargo_linker_args(
485 cmd: &mut BootstrapCommand,
486 builder: &Builder<'_>,
487 target: TargetSelection,
488 lld_threads: LldThreads,
489) {
490 let args = linker_args(builder, target, lld_threads);
491 let mut flags = cmd
492 .get_envs()
493 .find_map(|(k, v)| if k == OsStr::new("RUSTDOCFLAGS") { v } else { None })
494 .unwrap_or_default()
495 .to_os_string();
496 for arg in args {
497 if !flags.is_empty() {
498 flags.push(" ");
499 }
500 flags.push(arg);
501 }
502 if !flags.is_empty() {
503 cmd.env("RUSTDOCFLAGS", flags);
504 }
505}
506
507pub fn hex_encode<T>(input: T) -> String
509where
510 T: AsRef<[u8]>,
511{
512 use std::fmt::Write;
513
514 input.as_ref().iter().fold(String::with_capacity(input.as_ref().len() * 2), |mut acc, &byte| {
515 write!(&mut acc, "{byte:02x}").expect("Failed to write byte to the hex String.");
516 acc
517 })
518}
519
520pub fn check_cfg_arg(name: &str, values: Option<&[&str]>) -> String {
523 let next = match values {
526 Some(values) => {
527 let mut tmp = values.iter().flat_map(|val| [",", "\"", val, "\""]).collect::<String>();
528
529 tmp.insert_str(1, "values(");
530 tmp.push(')');
531 tmp
532 }
533 None => "".to_string(),
534 };
535 format!("--check-cfg=cfg({name}{next})")
536}
537
538#[track_caller]
546pub fn git(source_dir: Option<&Path>) -> BootstrapCommand {
547 let mut git = command("git");
548 git.cached();
550
551 if let Some(source_dir) = source_dir {
552 git.current_dir(source_dir);
553 git.env_remove("GIT_DIR");
556 git.env_remove("GIT_WORK_TREE")
560 .env_remove("GIT_INDEX_FILE")
561 .env_remove("GIT_OBJECT_DIRECTORY")
562 .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES");
563 }
564
565 git
566}
567
568pub fn set_file_times<P: AsRef<Path>>(path: P, times: fs::FileTimes) -> io::Result<()> {
570 let f = if cfg!(windows) {
573 fs::File::options().write(true).open(path)?
574 } else {
575 fs::File::open(path)?
576 };
577 f.set_times(times)
578}
579
580pub(crate) fn envify(s: &str) -> String {
588 s.chars()
591 .map(|c| match c {
592 '-' | '.' => '_',
593 c => c,
594 })
595 .flat_map(|c| c.to_uppercase())
596 .collect()
597}
598
599pub(crate) fn exit_process(code: i32) -> ! {
607 if cfg!(test) {
609 panic!("status code: {code}");
610 } else {
611 if CiEnv::is_ci() {
614 let bootstrap_args =
616 std::env::args().skip(1).map(|a| a.to_string()).collect::<Vec<_>>().join(" ");
617 eprintln!("Bootstrap failed while executing `{bootstrap_args}`");
618 eprintln!("Currently active steps:");
619 StepStack::with_current(|stack| {
620 for step in stack.get_active_steps() {
621 eprintln!("{} at {}", step.info, step.location);
622 }
623 });
624 }
625
626 std::process::exit(code);
628 }
629}
630
631pub fn fail(s: &str) -> ! {
632 eprintln!("\n\n{s}\n\n");
633 exit_process(1);
634}