1use std::cell::Cell;
2use std::collections::{BTreeSet, HashMap, HashSet};
3use std::fmt::Display;
4use std::ops::Deref;
5use std::path::{Path, PathBuf};
6use std::time::{Instant, SystemTime};
7use std::{env, fs, io, str};
8
9use build_helper::ci::gha;
10use termcolor::{ColorChoice, StandardStream, WriteColor};
11#[cfg(feature = "tracing")]
12use tracing::{instrument, span};
13
14use crate::core::build_steps::format::InternalRustfmt;
15use crate::core::build_steps::test::TestTarget;
16use crate::core::build_steps::vendor::VENDOR_DIR;
17use crate::core::builder::{Builder, Kind};
18use crate::core::compiler::Compiler;
19use crate::core::config::flags::{self, Subcommand};
20use crate::core::config::{BootstrapOverrideLld, Config, DryRun, LlvmLibunwind, TargetSelection};
21use crate::core::download::{DownloadContext, download_beta_toolchain};
22use crate::core::metadata::Crate;
23#[cfg(feature = "tracing")]
24use crate::trace_io;
25use crate::utils::build_stamp::BuildStamp;
26use crate::utils::channel::GitInfo;
27use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
28use crate::utils::helpers::{
29 self, dir_is_empty, exe, is_symlink_dir, libdir, set_file_times, split_debuginfo, symlink_dir,
30 t,
31};
32use crate::{debug, trace};
33
34pub(crate) struct Session {
40 pub(crate) config: Config,
42
43 pub(crate) version: String,
45
46 pub(crate) bootstrap_out: PathBuf,
48 pub(crate) fail_fast: bool,
49 pub(crate) test_target: TestTarget,
50 pub(crate) verbosity: usize,
51
52 pub(crate) initial_rustc: PathBuf,
53 pub(crate) initial_rustdoc: PathBuf,
54 pub(crate) initial_cargo: PathBuf,
55 pub(crate) initial_lld: PathBuf,
56 pub(crate) initial_relative_libdir: PathBuf,
57 pub(crate) initial_sysroot: PathBuf,
58
59 pub(crate) cc: HashMap<TargetSelection, cc::Tool>,
62 pub(crate) cxx: HashMap<TargetSelection, cc::Tool>,
63 pub(crate) ar: HashMap<TargetSelection, PathBuf>,
64 pub(crate) ranlib: HashMap<TargetSelection, PathBuf>,
65 pub(crate) wasi_sdk_path: Option<PathBuf>,
66
67 pub(crate) crates: HashMap<String, Crate>,
70 pub(crate) crate_paths: HashMap<PathBuf, String>,
71 pub(crate) is_sudo: bool,
72 pub(crate) prerelease_version: Cell<Option<u32>>,
73
74 #[cfg(feature = "build-metrics")]
75 pub(crate) metrics: crate::utils::metrics::BuildMetrics,
76
77 #[cfg(feature = "tracing")]
78 pub(crate) step_graph: std::cell::RefCell<crate::utils::step_graph::StepGraph>,
79}
80
81impl Deref for Session {
82 type Target = Config;
83
84 fn deref(&self) -> &Self::Target {
85 &self.config
86 }
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
91pub(crate) enum DependencyType {
92 HostProcMacro,
94 Target {
97 proc_macro: bool,
99 },
100 TargetSelfContained,
102}
103
104#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
109pub(crate) enum Mode {
110 Std,
112
113 Rustc,
115
116 Codegen,
118
119 ToolBootstrap,
131
132 ToolTarget,
143
144 ToolStd,
148
149 ToolRustcPrivate,
155}
156
157impl Mode {
158 pub(crate) fn must_support_dlopen(&self) -> bool {
159 match self {
160 Mode::Std | Mode::Codegen => true,
161 Mode::ToolBootstrap
162 | Mode::ToolRustcPrivate
163 | Mode::ToolStd
164 | Mode::ToolTarget
165 | Mode::Rustc => false,
166 }
167 }
168}
169
170pub(crate) enum RemapScheme {
174 Compiler,
176 NonCompiler,
178}
179
180#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
181pub(crate) enum CLang {
182 C,
183 Cxx,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub(crate) enum FileType {
188 Executable,
190 NativeLibrary,
192 Script,
194 Regular,
196}
197
198impl FileType {
199 pub(crate) fn perms(self) -> u32 {
201 match self {
202 FileType::Executable | FileType::Script => 0o755,
203 FileType::Regular | FileType::NativeLibrary => 0o644,
204 }
205 }
206
207 pub(crate) fn could_have_split_debuginfo(self) -> bool {
208 match self {
209 FileType::Executable | FileType::NativeLibrary => true,
210 FileType::Script | FileType::Regular => false,
211 }
212 }
213}
214
215macro_rules! forward {
216 ($( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
217 impl Session {
218 $(
219 pub(crate) fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
220 self.config.$fn( $($param),* )
221 }
222 )+
223 }
224 }
225}
226
227forward! {
228 do_if_verbose(f: impl Fn()),
229 is_verbose() -> bool,
230 create(path: &Path, s: &str),
231 remove(f: &Path),
232 tempdir() -> PathBuf,
233 download_rustc() -> bool,
234}
235
236pub(crate) struct TargetAndStage {
239 target: TargetSelection,
240 stage: u32,
241}
242
243impl From<(TargetSelection, u32)> for TargetAndStage {
244 fn from((target, stage): (TargetSelection, u32)) -> Self {
245 Self { target, stage }
246 }
247}
248
249impl From<Compiler> for TargetAndStage {
250 fn from(compiler: Compiler) -> Self {
251 Self { target: compiler.host, stage: compiler.stage }
252 }
253}
254
255impl Session {
256 pub(crate) fn new(mut config: Config) -> Session {
261 #[cfg(unix)]
262 let is_sudo = match env::var_os("SUDO_USER") {
265 Some(_sudo_user) => {
266 let uid = unsafe { libc::getuid() };
271 uid == 0
272 }
273 None => false,
274 };
275 #[cfg(not(unix))]
276 let is_sudo = false;
277
278 let dwn_ctx = DownloadContext::from(&config);
279
280 let initial_rustc = config.external_rustc.clone().unwrap_or_else(|| {
281 download_beta_toolchain(&dwn_ctx, &config.out);
282 config
283 .out
284 .join(config.host_target)
285 .join("stage0")
286 .join("bin")
287 .join(exe("rustc", config.host_target))
288 });
289
290 let initial_rustdoc = config
291 .external_rustdoc
292 .clone()
293 .unwrap_or_else(|| initial_rustc.with_file_name(exe("rustdoc", config.host_target)));
294
295 let rustc_paths = command(&initial_rustc)
298 .args(["--print", "sysroot", "--print", "target-libdir"])
299 .run_in_dry_run()
300 .run_capture_stdout(&config)
301 .stdout();
302 let mut rustc_paths = rustc_paths.lines();
303 let initial_sysroot =
304 rustc_paths.next().map(PathBuf::from).expect("Missing sysroot from initial rustc");
305 let initial_target_libdir = rustc_paths
306 .next()
307 .map(PathBuf::from)
308 .expect("Missing target libdir from initial rustc");
309 assert!(rustc_paths.next().is_none());
310
311 let initial_cargo = config.external_cargo.clone().unwrap_or_else(|| {
312 download_beta_toolchain(&dwn_ctx, &config.out);
313 initial_sysroot.join("bin").join(exe("cargo", config.host_target))
314 });
315
316 if config.exec_ctx.dry_run() {
319 config.out = config.out.join("tmp-dry-run");
320 fs::create_dir_all(&config.out).expect("Failed to create dry-run directory");
321 }
322
323 let initial_target_dir = initial_target_libdir
324 .parent()
325 .unwrap_or_else(|| panic!("{initial_target_libdir:?} has no parent"));
326
327 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
328
329 let initial_relative_libdir = if cfg!(test) {
330 PathBuf::default()
332 } else {
333 let ancestor = initial_target_dir.ancestors().nth(2).unwrap_or_else(|| {
334 panic!("Not enough ancestors for {}", initial_target_dir.display())
335 });
336
337 ancestor
338 .strip_prefix(&initial_sysroot)
339 .unwrap_or_else(|_| {
340 panic!(
341 "Couldn’t resolve the initial relative libdir from {}",
342 initial_target_dir.display()
343 )
344 })
345 .to_path_buf()
346 };
347
348 let version = std::fs::read_to_string(config.src.join("src").join("version"))
349 .expect("failed to read src/version");
350 let version = version.trim();
351
352 let mut bootstrap_out = std::env::current_exe()
353 .expect("could not determine path to running process")
354 .parent()
355 .unwrap()
356 .to_path_buf();
357 if bootstrap_out.ends_with("deps") {
360 bootstrap_out.pop();
361 }
362 if !bootstrap_out.join(exe("rustc", config.host_target)).exists() && !cfg!(test) {
363 panic!(
365 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
366 bootstrap_out.display()
367 )
368 }
369
370 if config.rust_info.is_from_tarball() && config.description.is_none() {
371 config.description = Some("built from a source tarball".to_owned());
372 }
373
374 let mut sess = Session {
375 initial_lld,
376 initial_relative_libdir,
377 initial_rustc,
378 initial_rustdoc,
379 initial_cargo,
380 initial_sysroot,
381 fail_fast: config.cmd.fail_fast(),
382 test_target: config.cmd.test_target(),
383 verbosity: config.exec_ctx.verbosity as usize,
384 config,
385 version: version.to_string(),
386 bootstrap_out,
387
388 cc: HashMap::new(),
389 cxx: HashMap::new(),
390 ar: HashMap::new(),
391 ranlib: HashMap::new(),
392 wasi_sdk_path: env::var_os("WASI_SDK_PATH").map(PathBuf::from),
393 crates: HashMap::new(),
394 crate_paths: HashMap::new(),
395 is_sudo,
396 prerelease_version: Cell::new(None),
397
398 #[cfg(feature = "build-metrics")]
399 metrics: crate::utils::metrics::BuildMetrics::init(),
400
401 #[cfg(feature = "tracing")]
402 step_graph: std::cell::RefCell::new(crate::utils::step_graph::StepGraph::default()),
403 };
404
405 let local_version_verbose = command(&sess.initial_rustc)
408 .run_in_dry_run()
409 .args(["--version", "--verbose"])
410 .run_capture_stdout(&sess)
411 .stdout();
412 let local_release = local_version_verbose
413 .lines()
414 .filter_map(|x| x.strip_prefix("release:"))
415 .next()
416 .unwrap()
417 .trim();
418 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
419 sess.do_if_verbose(|| println!("auto-detected local-rebuild {local_release}"));
420 sess.config.local_rebuild = true;
421 }
422
423 sess.do_if_verbose(|| println!("finding compilers"));
424 crate::utils::cc_detect::fill_compilers(&mut sess);
425 if !matches!(sess.config.cmd, Subcommand::Setup { .. }) {
431 sess.do_if_verbose(|| println!("running sanity check"));
432 crate::core::sanity::check(&mut sess);
433
434 let rust_submodules = ["library/backtrace"];
437 for s in rust_submodules {
438 sess.require_submodule(
439 s,
440 Some(
441 "The submodule is required for the standard library \
442 and the main Cargo workspace.",
443 ),
444 );
445 }
446 sess.update_existing_submodules();
448
449 sess.do_if_verbose(|| println!("learning about cargo"));
450 crate::core::metadata::build(&mut sess);
451 }
452
453 let build_triple = sess.out.join(sess.host_target);
455 t!(fs::create_dir_all(&build_triple));
456 let host = sess.out.join("host");
457 if host.is_symlink() {
458 #[cfg(windows)]
461 t!(fs::remove_dir(&host));
462 #[cfg(not(windows))]
463 t!(fs::remove_file(&host));
464 }
465 t!(
466 symlink_dir(&sess.config, &build_triple, &host),
467 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
468 );
469
470 sess
471 }
472
473 #[cfg_attr(
482 feature = "tracing",
483 instrument(
484 level = "trace",
485 name = "Session::require_submodule",
486 skip_all,
487 fields(submodule = submodule),
488 )
489 )]
490 pub(crate) fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
491 if self.rust_info().is_from_tarball() {
492 return;
493 }
494
495 if self.config.dry_run() {
496 return;
497 }
498
499 if cfg!(test) && !self.config.submodules() {
502 return;
503 }
504 self.config.update_submodule(submodule);
505 let absolute_path = self.config.src.join(submodule);
506 if !absolute_path.exists() || dir_is_empty(&absolute_path) {
507 let maybe_enable = if !self.config.submodules()
508 && self.config.rust_info.is_managed_git_subrepository()
509 {
510 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
511 } else {
512 ""
513 };
514 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
515 eprintln!(
516 "submodule {submodule} does not appear to be checked out, \
517 but it is required for this step{maybe_enable}{err_hint}"
518 );
519 helpers::exit_process(1);
520 }
521 }
522
523 pub(crate) fn update_existing_submodules(&self) {
526 if !self.config.submodules() {
529 return;
530 }
531 let output = helpers::git(Some(&self.src))
532 .args(["config", "--file"])
533 .arg(".gitmodules")
534 .args(["--get-regexp", "path"])
535 .run_capture(self)
536 .stdout();
537 std::thread::scope(|s| {
538 for line in output.lines() {
541 let submodule = line.split_once(' ').unwrap().1;
542 let config = self.config.clone();
543 s.spawn(move || {
544 Self::update_existing_submodule(&config, submodule);
545 });
546 }
547 });
548 }
549
550 pub(crate) fn update_existing_submodule(config: &Config, submodule: &str) {
552 if !config.submodules() {
554 return;
555 }
556
557 if config.git_info(false, Path::new(submodule)).is_managed_git_subrepository() {
558 config.update_submodule(submodule);
559 }
560 }
561
562 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Session::build", skip_all))]
564 pub(crate) fn build(&mut self) {
565 trace!("setting up job management");
566 crate::utils::job::setup(self);
567
568 {
570 #[cfg(feature = "tracing")]
571 let _hardcoded_span =
572 span!(tracing::Level::DEBUG, "handling hardcoded subcommands (Format, Perf)")
573 .entered();
574
575 match &self.config.cmd {
576 Subcommand::Format { check, all } => {
577 let builder = Builder::new(self);
578 let rustfmt_path = builder.ensure(InternalRustfmt).unwrap_or_else(|| {
579 eprintln!("fmt error: `x fmt` is not supported on this channel");
580 helpers::exit_process(1);
581 });
582 return crate::core::build_steps::format::format(
583 &builder,
584 rustfmt_path,
585 *check,
586 *all,
587 &self.config.paths,
588 );
589 }
590 Subcommand::Perf(args) => {
591 return crate::core::build_steps::perf::perf(
592 &Builder::new(self),
593 args,
594 &self.config.free_args,
595 );
596 }
597 _cmd => {
598 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
599 }
600 }
601
602 debug!("handling subcommand normally");
603 }
604
605 if !self.config.dry_run() {
606 #[cfg(feature = "tracing")]
607 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
608
609 {
612 #[cfg(feature = "tracing")]
613 let _sanity_check_span =
614 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
615 self.config.set_dry_run(DryRun::SelfCheck);
616 let builder = Builder::new(self);
617 builder.execute_cli();
618 }
619
620 {
622 #[cfg(feature = "tracing")]
623 let _actual_run_span =
624 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
625 self.config.set_dry_run(DryRun::Disabled);
626 let builder = Builder::new(self);
627 builder.execute_cli();
628 }
629 } else {
630 #[cfg(feature = "tracing")]
631 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
632
633 let builder = Builder::new(self);
634 builder.execute_cli();
635 }
636
637 #[cfg(feature = "tracing")]
638 debug!("checking for postponed test failures from `test --no-fail-fast`");
639
640 self.config.exec_ctx().report_failures_and_exit();
642
643 #[cfg(feature = "build-metrics")]
644 self.metrics.persist(self);
645 }
646
647 pub(crate) fn rust_info(&self) -> &GitInfo {
648 &self.config.rust_info
649 }
650
651 pub(crate) fn std_features(&self, target: TargetSelection) -> String {
654 let mut features: BTreeSet<&str> =
655 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
656
657 match self.config.llvm_libunwind(target) {
658 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
659 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
660 LlvmLibunwind::No => false,
661 };
662
663 if self.config.backtrace {
664 features.insert("backtrace");
665 }
666
667 if self.config.profiler_enabled(target) {
668 features.insert("profiler");
669 }
670
671 if target.contains("zkvm") {
673 features.insert("compiler-builtins-mem");
674 }
675
676 features.into_iter().collect::<Vec<_>>().join(" ")
677 }
678
679 pub(crate) fn rustc_features(
681 &self,
682 kind: Kind,
683 target: TargetSelection,
684 crates: &[String],
685 ) -> String {
686 let possible_features_by_crates: HashSet<_> = crates
687 .iter()
688 .flat_map(|krate| &self.crates[krate].features)
689 .map(std::ops::Deref::deref)
690 .collect();
691 let check = |feature: &str| -> bool {
692 crates.is_empty() || possible_features_by_crates.contains(feature)
693 };
694 let mut features = vec![];
695
696 if let Some(allocator_feature_name) = self.config.allocator(target).feature_name()
697 && check(allocator_feature_name)
698 {
699 features.push(allocator_feature_name);
700 }
701 if self.config.llvm_enabled(target) && check("llvm") {
702 features.push("llvm");
703 }
704 if self.config.llvm_offload {
705 features.push("llvm_offload");
706 }
707 if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
709 features.push("rustc_randomized_layouts");
710 }
711 if self.config.compile_time_deps && kind.is_check_like() {
712 features.push("check_only");
713 }
714
715 if crates.iter().any(|c| c == "rustc_transmute") {
716 features.push("rustc");
719 }
720
721 if !self.config.rust_debug_logging && check("max_level_info") {
727 features.push("max_level_info");
728 }
729
730 features.join(" ")
731 }
732
733 pub(crate) fn cargo_dir(&self, mode: Mode) -> &'static str {
736 match (mode, self.config.rust_optimize.is_release()) {
737 (Mode::Std, _) => "dist",
738 (_, true) => "release",
739 (_, false) => "debug",
740 }
741 }
742
743 pub(crate) fn tools_dir(&self, build_compiler: Compiler) -> PathBuf {
744 let out = self
745 .out
746 .join(build_compiler.host)
747 .join(format!("stage{}-tools-bin", build_compiler.stage + 1));
748 t!(fs::create_dir_all(&out));
749 out
750 }
751
752 pub(crate) fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
757 use std::fmt::Write;
758
759 fn bootstrap_tool() -> (Option<u32>, &'static str) {
760 (None, "bootstrap-tools")
761 }
762 fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
763 (Some(build_compiler.stage + 1), "tools")
764 }
765
766 let (stage, suffix) = match mode {
767 Mode::Std => (Some(build_compiler.stage), "std"),
769 Mode::Rustc => (Some(build_compiler.stage + 1), "rustc"),
771 Mode::Codegen => (Some(build_compiler.stage + 1), "codegen"),
772 Mode::ToolBootstrap => bootstrap_tool(),
773 Mode::ToolStd | Mode::ToolRustcPrivate => (Some(build_compiler.stage + 1), "tools"),
774 Mode::ToolTarget => {
775 if build_compiler.stage == 0 {
778 bootstrap_tool()
779 } else {
780 staged_tool(build_compiler)
781 }
782 }
783 };
784 let path = self.out.join(build_compiler.host);
785 let mut dir_name = String::new();
786 if let Some(stage) = stage {
787 write!(dir_name, "stage{stage}-").unwrap();
788 }
789 dir_name.push_str(suffix);
790 path.join(dir_name)
791 }
792
793 pub(crate) fn cargo_out(
797 &self,
798 build_compiler: Compiler,
799 mode: Mode,
800 target: TargetSelection,
801 ) -> PathBuf {
802 self.stage_out(build_compiler, mode).join(target).join(self.cargo_dir(mode))
803 }
804
805 pub(crate) fn doc_out(&self, target: TargetSelection) -> PathBuf {
807 self.out.join(target).join("doc")
808 }
809
810 pub(crate) fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
812 self.out.join(target).join("json-doc")
813 }
814
815 pub(crate) fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
817 self.out.join(target).join("compiler-doc")
818 }
819
820 pub(crate) fn vendored_crates_path(&self) -> Option<PathBuf> {
822 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
823 }
824
825 pub(crate) fn native_dir(&self, target: TargetSelection) -> PathBuf {
827 self.out.join(target).join("native")
828 }
829
830 pub(crate) fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
832 if env::var_os("RUST_TEST_THREADS").is_none() {
833 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
834 }
835 }
836
837 pub(crate) fn rustc_snapshot_libdir(&self) -> PathBuf {
839 self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
840 }
841
842 pub(crate) fn rustc_snapshot_sysroot(&self) -> &Path {
844 &self.initial_sysroot
845 }
846
847 pub(crate) fn info(&self, msg: &str) {
848 match self.config.get_dry_run() {
849 DryRun::SelfCheck => (),
850 DryRun::Disabled | DryRun::UserSelected => {
851 println!("{msg}");
852 }
853 }
854 }
855
856 #[must_use = "Groups should not be dropped until the Step finishes running"]
868 #[track_caller]
869 pub(crate) fn msg(
870 &self,
871 action: impl Into<Kind>,
872 what: impl Display,
873 mode: impl Into<Option<Mode>>,
874 target_and_stage: impl Into<TargetAndStage>,
875 target: impl Into<Option<TargetSelection>>,
876 ) -> Option<gha::Group> {
877 let target_and_stage = target_and_stage.into();
878 let action = action.into();
879 assert!(
880 action != Kind::Test,
881 "Please use `Session::msg_test` instead of `Session::msg(Kind::Test)`"
882 );
883
884 let actual_stage = match mode.into() {
885 Some(Mode::Std) => target_and_stage.stage,
887 Some(
889 Mode::Rustc
890 | Mode::Codegen
891 | Mode::ToolBootstrap
892 | Mode::ToolTarget
893 | Mode::ToolStd
894 | Mode::ToolRustcPrivate,
895 )
896 | None => target_and_stage.stage + 1,
897 };
898
899 let action = action.description();
900 let what = what.to_string();
901 let msg = |fmt| {
902 let space = if !what.is_empty() { " " } else { "" };
903 format!("{action} stage{actual_stage} {what}{space}{fmt}")
904 };
905 let msg = if let Some(target) = target.into() {
906 let build_stage = target_and_stage.stage;
907 let host = target_and_stage.target;
908 if host == target {
909 msg(format_args!("(stage{build_stage} -> stage{actual_stage}, {target})"))
910 } else {
911 msg(format_args!("(stage{build_stage}:{host} -> stage{actual_stage}:{target})"))
912 }
913 } else {
914 msg(format_args!(""))
915 };
916 self.group(&msg)
917 }
918
919 #[must_use = "Groups should not be dropped until the Step finishes running"]
925 #[track_caller]
926 pub(crate) fn msg_test(
927 &self,
928 what: impl Display,
929 target: TargetSelection,
930 stage: u32,
931 ) -> Option<gha::Group> {
932 let action = Kind::Test.description();
933 let msg = format!("{action} stage{stage} {what} ({target})");
934 self.group(&msg)
935 }
936
937 #[must_use = "Groups should not be dropped until the Step finishes running"]
941 #[track_caller]
942 pub(crate) fn msg_unstaged(
943 &self,
944 action: impl Into<Kind>,
945 what: impl Display,
946 target: TargetSelection,
947 ) -> Option<gha::Group> {
948 let action = action.into().description();
949 let msg = format!("{action} {what} for {target}");
950 self.group(&msg)
951 }
952
953 #[track_caller]
954 pub(crate) fn group(&self, msg: &str) -> Option<gha::Group> {
955 match self.config.get_dry_run() {
956 DryRun::SelfCheck => None,
957 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
958 }
959 }
960
961 pub(crate) fn jobs(&self) -> u32 {
964 self.config.jobs.unwrap_or_else(|| {
965 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
966 })
967 }
968
969 pub(crate) fn debuginfo_map_to(&self, remap_scheme: RemapScheme) -> Option<String> {
970 if !self.config.rust_remap_debuginfo {
971 return None;
972 }
973
974 let sha = self.rust_sha().unwrap_or(&self.version);
975
976 match remap_scheme {
977 RemapScheme::Compiler => {
978 Some(format!("/rustc-dev/{sha}"))
987 }
988 RemapScheme::NonCompiler => {
989 Some(format!("/rustc/{sha}"))
991 }
992 }
993 }
994
995 pub(crate) fn cc(&self, target: TargetSelection) -> PathBuf {
997 if self.config.dry_run() {
998 return PathBuf::new();
999 }
1000 self.cc[&target].path().into()
1001 }
1002
1003 pub(crate) fn cc_tool(&self, target: TargetSelection) -> cc::Tool {
1005 self.cc[&target].clone()
1006 }
1007
1008 pub(crate) fn cxx_tool(&self, target: TargetSelection) -> cc::Tool {
1010 self.cxx[&target].clone()
1011 }
1012
1013 pub(crate) fn cc_handled_cflags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1016 if self.config.dry_run() {
1017 return Vec::new();
1018 }
1019 let base = match c {
1020 CLang::C => self.cc[&target].clone(),
1021 CLang::Cxx => self.cxx[&target].clone(),
1022 };
1023
1024 base.args()
1027 .iter()
1028 .map(|s| s.to_string_lossy().into_owned())
1029 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1030 .collect::<Vec<String>>()
1031 }
1032
1033 pub(crate) fn cc_unhandled_cflags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1035 let mut base = Vec::new();
1036
1037 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1041 base.push("-stdlib=libc++".into());
1042 }
1043
1044 if &*target.triple == "i686-pc-windows-gnu" {
1048 base.push("-fno-omit-frame-pointer".into());
1049 }
1050
1051 base
1052 }
1053
1054 pub(crate) fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1056 if self.config.dry_run() {
1057 return None;
1058 }
1059 self.ar.get(&target).cloned()
1060 }
1061
1062 pub(crate) fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1064 if self.config.dry_run() {
1065 return None;
1066 }
1067 self.ranlib.get(&target).cloned()
1068 }
1069
1070 pub(crate) fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1072 if self.config.dry_run() {
1073 return Ok(PathBuf::new());
1074 }
1075 match self.cxx.get(&target) {
1076 Some(p) => Ok(p.path().into()),
1077 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1078 }
1079 }
1080
1081 pub(crate) fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1083 if self.config.dry_run() {
1084 return Some(PathBuf::new());
1085 }
1086 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1087 {
1088 Some(linker)
1089 } else if target.contains("vxworks") {
1090 Some(self.cxx[&target].path().into())
1093 } else if !self.config.is_host_target(target)
1094 && helpers::use_host_linker(target)
1095 && !target.is_msvc()
1096 {
1097 Some(self.cc(target))
1098 } else if self.config.bootstrap_override_lld.is_used()
1099 && self.is_lld_direct_linker(target)
1100 && self.host_target == target
1101 {
1102 match self.config.bootstrap_override_lld {
1103 BootstrapOverrideLld::SelfContained => Some(self.initial_lld.clone()),
1104 BootstrapOverrideLld::External => Some("lld".into()),
1105 BootstrapOverrideLld::None => None,
1106 }
1107 } else {
1108 None
1109 }
1110 }
1111
1112 pub(crate) fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1115 target.is_msvc()
1116 }
1117
1118 pub(crate) fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1120 if target.contains("pc-windows-msvc") {
1121 Some(true)
1122 } else {
1123 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1124 }
1125 }
1126
1127 pub(crate) fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1132 let configured_root = self
1133 .config
1134 .target_config
1135 .get(&target)
1136 .and_then(|t| t.musl_root.as_ref())
1137 .or(self.config.musl_root.as_ref())
1138 .map(|p| &**p);
1139
1140 if self.config.is_host_target(target) && configured_root.is_none() {
1141 Some(Path::new("/usr"))
1142 } else {
1143 configured_root
1144 }
1145 }
1146
1147 pub(crate) fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1149 self.config
1150 .target_config
1151 .get(&target)
1152 .and_then(|t| t.musl_libdir.clone())
1153 .or_else(|| self.musl_root(target).map(|root| root.join("lib")))
1154 }
1155
1156 pub(crate) fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1163 let configured =
1164 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1165 if let Some(path) = configured {
1166 return Some(path.join("lib").join(target.to_string()));
1167 }
1168 let mut env_root = self.wasi_sdk_path.clone()?;
1169 env_root.push("share");
1170 env_root.push("wasi-sysroot");
1171 env_root.push("lib");
1172 env_root.push(target.to_string());
1173 Some(env_root)
1174 }
1175
1176 pub(crate) fn no_std(&self, target: TargetSelection) -> Option<bool> {
1178 self.config.target_config.get(&target).map(|t| t.no_std)
1179 }
1180
1181 pub(crate) fn remote_tested(&self, target: TargetSelection) -> bool {
1184 self.qemu_rootfs(target).is_some()
1185 || target.contains("android")
1186 || env::var_os("TEST_DEVICE_ADDR").is_some()
1187 }
1188
1189 pub(crate) fn runner(&self, target: TargetSelection) -> Option<String> {
1195 let configured_runner =
1196 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1197 if let Some(runner) = configured_runner {
1198 return Some(runner.to_owned());
1199 }
1200
1201 if target.starts_with("wasm") && target.contains("wasi") {
1202 self.default_wasi_runner()
1203 } else {
1204 None
1205 }
1206 }
1207
1208 fn default_wasi_runner(&self) -> Option<String> {
1212 let mut finder = crate::core::sanity::Finder::new();
1213
1214 if let Some(path) = finder.maybe_have("wasmtime")
1218 && let Ok(mut path) = path.into_os_string().into_string()
1219 {
1220 path.push_str(
1221 " run -C cache=n --dir . \
1222 --wasi inherit-env,inherit-network,allow-ip-name-lookup",
1223 );
1224 return Some(path);
1225 }
1226
1227 None
1228 }
1229
1230 pub(crate) fn tool_enabled(&self, tool: &str) -> bool {
1235 if !self.config.extended {
1236 return false;
1237 }
1238 match &self.config.tools {
1239 Some(set) => set.contains(tool),
1240 None => true,
1241 }
1242 }
1243
1244 pub(crate) fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1250 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1251 }
1252
1253 pub(crate) fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1272 !self.config.full_bootstrap
1273 && !self.config.download_rustc()
1274 && stage >= 2
1275 && (self.hosts.contains(&target) || target == self.host_target)
1276 }
1277
1278 pub(crate) fn force_use_stage2(&self, stage: u32) -> bool {
1284 self.config.download_rustc() && stage >= 2
1285 }
1286
1287 pub(crate) fn release(&self, num: &str) -> String {
1293 match &self.config.channel[..] {
1294 "stable" => num.to_string(),
1295 "beta" => {
1296 if !self.config.omit_git_hash {
1297 format!("{}-beta.{}", num, self.beta_prerelease_version())
1298 } else {
1299 format!("{num}-beta")
1300 }
1301 }
1302 "nightly" => format!("{num}-nightly"),
1303 _ => format!("{num}-dev"),
1304 }
1305 }
1306
1307 fn beta_prerelease_version(&self) -> u32 {
1308 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1309 let version = fs::read_to_string(version_file).ok()?;
1310
1311 helpers::extract_beta_rev(&version)
1312 }
1313
1314 if let Some(s) = self.prerelease_version.get() {
1315 return s;
1316 }
1317
1318 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1322 helpers::git(Some(&self.src))
1326 .arg("rev-list")
1327 .arg("--count")
1328 .arg("--merges")
1329 .arg(format!(
1330 "refs/remotes/origin/{}..HEAD",
1331 self.config.stage0_metadata.config.nightly_branch
1332 ))
1333 .run_in_dry_run()
1334 .run_capture(self)
1335 .stdout()
1336 });
1337 let n = count.trim().parse().unwrap();
1338 self.prerelease_version.set(Some(n));
1339 n
1340 }
1341
1342 pub(crate) fn rust_release(&self) -> String {
1344 self.release(&self.version)
1345 }
1346
1347 pub(crate) fn rust_package_vers(&self) -> String {
1353 match &self.config.channel[..] {
1354 "stable" => self.version.to_string(),
1355 "beta" => "beta".to_string(),
1356 "nightly" => "nightly".to_string(),
1357 _ => format!("{}-dev", self.version),
1358 }
1359 }
1360
1361 pub(crate) fn rust_version(&self) -> String {
1367 let mut version = self.rust_info().version(self, &self.version);
1368 if let Some(ref s) = self.config.description
1369 && !s.is_empty()
1370 {
1371 version.push_str(" (");
1372 version.push_str(s);
1373 version.push(')');
1374 }
1375 version
1376 }
1377
1378 pub(crate) fn rust_sha(&self) -> Option<&str> {
1380 self.rust_info().sha()
1381 }
1382
1383 pub(crate) fn release_num(&self, package: &str) -> String {
1385 if self.config.dry_run() {
1386 return "0.0.0 (dry-run)".into();
1387 }
1388 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1389 let toml = t!(fs::read_to_string(toml_file_name));
1390 for line in toml.lines() {
1391 if let Some(stripped) =
1392 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1393 {
1394 return stripped.to_owned();
1395 }
1396 }
1397
1398 panic!("failed to find version in {package}'s Cargo.toml")
1399 }
1400
1401 pub(crate) fn unstable_features(&self) -> bool {
1404 !matches!(&self.config.channel[..], "stable" | "beta")
1405 }
1406
1407 pub(crate) fn in_tree_crates(
1411 &self,
1412 root: &str,
1413 target: Option<TargetSelection>,
1414 ) -> Vec<&Crate> {
1415 let mut ret = Vec::new();
1416 let mut list = vec![root.to_owned()];
1417 let mut visited = HashSet::new();
1418 while let Some(krate) = list.pop() {
1419 let krate = self
1420 .crates
1421 .get(&krate)
1422 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1423 ret.push(krate);
1424 for dep in &krate.deps {
1425 if !self.crates.contains_key(dep) {
1426 continue;
1428 }
1429 if visited.insert(dep)
1435 && (dep != "profiler_builtins"
1436 || target
1437 .map(|t| self.config.profiler_enabled(t))
1438 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1439 && (dep != "rustc_codegen_llvm"
1440 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1441 {
1442 list.push(dep.clone());
1443 }
1444 }
1445 }
1446
1447 ret.sort_unstable_by(|a, b| Ord::cmp(&a.name, &b.name));
1449 ret
1450 }
1451
1452 pub(crate) fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1453 if self.config.dry_run() {
1454 return Vec::new();
1455 }
1456
1457 if !stamp.path().exists() {
1458 eprintln!(
1459 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1460 stamp.path().display()
1461 );
1462 helpers::exit_process(1);
1463 }
1464
1465 let mut paths = Vec::new();
1466 let contents = t!(fs::read(stamp.path()), stamp.path());
1467 for part in contents.split(|b| *b == 0) {
1470 if part.is_empty() {
1471 continue;
1472 }
1473 let dependency_type = match part[0] as char {
1474 'h' => DependencyType::HostProcMacro,
1475 's' => DependencyType::TargetSelfContained,
1476 't' => DependencyType::Target { proc_macro: false },
1477 'p' => DependencyType::Target { proc_macro: true },
1478 _ => unreachable!(),
1479 };
1480 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1481 paths.push((path, dependency_type));
1482 }
1483 paths
1484 }
1485
1486 #[track_caller]
1491 pub(crate) fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1492 self.copy_link_internal(src, dst, true);
1493 }
1494
1495 #[track_caller]
1500 pub(crate) fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1501 self.copy_link_internal(src, dst, false);
1502
1503 if file_type.could_have_split_debuginfo()
1504 && let Some(dbg_file) = split_debuginfo(src)
1505 {
1506 self.copy_link_internal(
1507 &dbg_file,
1508 &dst.with_extension(dbg_file.extension().unwrap()),
1509 false,
1510 );
1511 }
1512 }
1513
1514 #[track_caller]
1515 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1516 if self.config.dry_run() {
1517 return;
1518 }
1519 if src == dst {
1520 return;
1521 }
1522
1523 #[cfg(feature = "tracing")]
1524 let _span = trace_io!("file-copy-link", ?src, ?dst);
1525
1526 if let Err(e) = fs::remove_file(dst)
1527 && cfg!(windows)
1528 && e.kind() != io::ErrorKind::NotFound
1529 {
1530 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1533 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1534 }
1535 let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1536 let mut src = src.to_path_buf();
1537 if metadata.file_type().is_symlink() {
1538 if dereference_symlinks {
1539 src = t!(fs::canonicalize(src));
1540 metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1541 } else {
1542 let link = t!(fs::read_link(src));
1543 if is_symlink_dir(&metadata) {
1544 t!(symlink_dir(&self.config, &link, dst));
1545 } else {
1546 t!(self.symlink_file(link, dst));
1547 }
1548 return;
1549 }
1550 }
1551 if let Ok(()) = fs::hard_link(&src, dst) {
1552 } else {
1555 if let Err(e) = fs::copy(&src, dst) {
1556 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1557 }
1558 t!(fs::set_permissions(dst, metadata.permissions()));
1559
1560 let file_times = fs::FileTimes::new()
1563 .set_accessed(t!(metadata.accessed()))
1564 .set_modified(t!(metadata.modified()));
1565 t!(set_file_times(dst, file_times));
1566 }
1567 }
1568
1569 #[track_caller]
1573 pub(crate) fn cp_link_r(&self, src: &Path, dst: &Path) {
1574 if self.config.dry_run() {
1575 return;
1576 }
1577 for f in self.read_dir(src) {
1578 let path = f.path();
1579 let name = path.file_name().unwrap();
1580 let dst = dst.join(name);
1581 if t!(f.file_type()).is_dir() {
1582 t!(fs::create_dir_all(&dst));
1583 self.cp_link_r(&path, &dst);
1584 } else {
1585 self.copy_link(&path, &dst, FileType::Regular);
1586 }
1587 }
1588 }
1589
1590 #[track_caller]
1596 pub(crate) fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1597 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1599 }
1600
1601 #[track_caller]
1603 fn cp_link_filtered_recurse(
1604 &self,
1605 src: &Path,
1606 dst: &Path,
1607 relative: &Path,
1608 filter: &dyn Fn(&Path) -> bool,
1609 ) {
1610 for f in self.read_dir(src) {
1611 let path = f.path();
1612 let name = path.file_name().unwrap();
1613 let dst = dst.join(name);
1614 let relative = relative.join(name);
1615 if filter(&relative) {
1617 if t!(f.file_type()).is_dir() {
1618 let _ = fs::remove_dir_all(&dst);
1619 self.create_dir(&dst);
1620 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1621 } else {
1622 self.copy_link(&path, &dst, FileType::Regular);
1623 }
1624 }
1625 }
1626 }
1627
1628 pub(crate) fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1629 let file_name = src.file_name().unwrap();
1630 let dest = dest_folder.join(file_name);
1631 self.copy_link(src, &dest, FileType::Regular);
1632 }
1633
1634 pub(crate) fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1635 if self.config.dry_run() {
1636 return;
1637 }
1638 let dst = dstdir.join(src.file_name().unwrap());
1639
1640 #[cfg(feature = "tracing")]
1641 let _span = trace_io!("install", ?src, ?dst);
1642
1643 t!(fs::create_dir_all(dstdir));
1644 if !src.exists() {
1645 panic!("ERROR: File \"{}\" not found!", src.display());
1646 }
1647
1648 self.copy_link_internal(src, &dst, true);
1649 chmod(&dst, file_type.perms());
1650
1651 if file_type.could_have_split_debuginfo()
1653 && let Some(dbg_file) = split_debuginfo(src)
1654 {
1655 self.install(&dbg_file, dstdir, FileType::Regular);
1656 }
1657 }
1658
1659 pub(crate) fn read(&self, path: &Path) -> String {
1660 if self.config.dry_run() {
1661 return String::new();
1662 }
1663 t!(fs::read_to_string(path))
1664 }
1665
1666 #[track_caller]
1667 pub(crate) fn create_dir(&self, dir: &Path) {
1668 if self.config.dry_run() {
1669 return;
1670 }
1671
1672 #[cfg(feature = "tracing")]
1673 let _span = trace_io!("dir-create", ?dir);
1674
1675 t!(fs::create_dir_all(dir))
1676 }
1677
1678 pub(crate) fn remove_dir(&self, dir: &Path) {
1679 if self.config.dry_run() {
1680 return;
1681 }
1682
1683 #[cfg(feature = "tracing")]
1684 let _span = trace_io!("dir-remove", ?dir);
1685
1686 t!(fs::remove_dir_all(dir))
1687 }
1688
1689 pub(crate) fn clear_dir(&self, dir: &Path) {
1692 if self.config.dry_run() {
1693 return;
1694 }
1695
1696 #[cfg(feature = "tracing")]
1697 let _span = trace_io!("dir-clear", ?dir);
1698
1699 let _ = std::fs::remove_dir_all(dir);
1700 self.create_dir(dir);
1701 }
1702
1703 pub(crate) fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1704 let iter = match fs::read_dir(dir) {
1705 Ok(v) => v,
1706 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1707 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1708 };
1709 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1710 }
1711
1712 pub(crate) fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(
1713 &self,
1714 src: P,
1715 link: Q,
1716 ) -> io::Result<()> {
1717 #[cfg(unix)]
1718 use std::os::unix::fs::symlink as symlink_file;
1719 #[cfg(windows)]
1720 use std::os::windows::fs::symlink_file;
1721 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1722 }
1723
1724 pub(crate) fn ninja(&self) -> bool {
1727 let mut cmd_finder = crate::core::sanity::Finder::new();
1728
1729 if self.config.ninja_in_file {
1730 if cmd_finder.maybe_have("ninja-build").is_none()
1733 && cmd_finder.maybe_have("ninja").is_none()
1734 {
1735 eprintln!(
1736 "
1737Couldn't find required command: ninja (or ninja-build)
1738
1739You should install ninja as described at
1740<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1741or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
1742Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1743to download LLVM rather than building it.
1744"
1745 );
1746 helpers::exit_process(1);
1747 }
1748 }
1749
1750 if !self.config.ninja_in_file
1758 && self.config.host_target.is_msvc()
1759 && cmd_finder.maybe_have("ninja").is_some()
1760 {
1761 return true;
1762 }
1763
1764 self.config.ninja_in_file
1765 }
1766
1767 pub(crate) fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1768 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1769 }
1770
1771 #[expect(dead_code, reason = "symmetric with `colored_stdout`")]
1772 pub(crate) fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1773 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
1774 }
1775
1776 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
1777 where
1778 C: Fn(ColorChoice) -> StandardStream,
1779 F: FnOnce(&mut dyn WriteColor) -> R,
1780 {
1781 let choice = match self.config.color {
1782 flags::Color::Always => ColorChoice::Always,
1783 flags::Color::Never => ColorChoice::Never,
1784 flags::Color::Auto if !is_tty => ColorChoice::Never,
1785 flags::Color::Auto => ColorChoice::Auto,
1786 };
1787 let mut stream = constructor(choice);
1788 let result = f(&mut stream);
1789 stream.reset().unwrap();
1790 result
1791 }
1792
1793 #[cfg_attr(not(feature = "tracing"), expect(dead_code))]
1794 pub(crate) fn report_summary(&self, path: &Path, start_time: Instant) {
1795 self.config.exec_ctx.profiler().report_summary(path, start_time);
1796 }
1797
1798 #[cfg(feature = "tracing")]
1799 pub(crate) fn report_step_graph(self, directory: &Path) {
1800 self.step_graph.into_inner().store_to_dot_files(directory);
1801 }
1802}
1803
1804impl AsRef<ExecutionContext> for Session {
1805 fn as_ref(&self) -> &ExecutionContext {
1806 &self.config.exec_ctx
1807 }
1808}
1809
1810#[cfg(unix)]
1811fn chmod(path: &Path, perms: u32) {
1812 use std::os::unix::fs::*;
1813 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1814}
1815#[cfg(windows)]
1816fn chmod(_path: &Path, _perms: u32) {}