1use std::borrow::Cow;
10use std::collections::HashSet;
11use std::ffi::OsStr;
12use std::io::BufReader;
13use std::io::prelude::*;
14use std::path::{Path, PathBuf};
15use std::process::Stdio;
16use std::{env, fs, str};
17
18use serde_derive::Deserialize;
19#[cfg(feature = "tracing")]
20use tracing::{instrument, span};
21
22use crate::core::build_steps::gcc::{Gcc, add_cg_gcc_cargo_flags};
23use crate::core::build_steps::tool::SourceType;
24use crate::core::build_steps::{dist, llvm};
25use crate::core::builder;
26use crate::core::builder::{
27 Builder, Cargo, Kind, PathSet, RunConfig, ShouldRun, Step, TaskPath, crate_description,
28};
29use crate::core::config::{DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection};
30use crate::utils::build_stamp;
31use crate::utils::build_stamp::BuildStamp;
32use crate::utils::exec::command;
33use crate::utils::helpers::{
34 exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date,
35};
36use crate::{CLang, Compiler, DependencyType, FileType, GitRepo, LLVM_TOOLS, Mode, debug, trace};
37
38#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct Std {
40 pub target: TargetSelection,
41 pub compiler: Compiler,
42 crates: Vec<String>,
46 force_recompile: bool,
49 extra_rust_args: &'static [&'static str],
50 is_for_mir_opt_tests: bool,
51}
52
53impl Std {
54 pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
55 Self {
56 target,
57 compiler,
58 crates: Default::default(),
59 force_recompile: false,
60 extra_rust_args: &[],
61 is_for_mir_opt_tests: false,
62 }
63 }
64
65 pub fn force_recompile(mut self, force_recompile: bool) -> Self {
66 self.force_recompile = force_recompile;
67 self
68 }
69
70 #[expect(clippy::wrong_self_convention)]
71 pub fn is_for_mir_opt_tests(mut self, is_for_mir_opt_tests: bool) -> Self {
72 self.is_for_mir_opt_tests = is_for_mir_opt_tests;
73 self
74 }
75
76 pub fn extra_rust_args(mut self, extra_rust_args: &'static [&'static str]) -> Self {
77 self.extra_rust_args = extra_rust_args;
78 self
79 }
80
81 fn copy_extra_objects(
82 &self,
83 builder: &Builder<'_>,
84 compiler: &Compiler,
85 target: TargetSelection,
86 ) -> Vec<(PathBuf, DependencyType)> {
87 let mut deps = Vec::new();
88 if !self.is_for_mir_opt_tests {
89 deps.extend(copy_third_party_objects(builder, compiler, target));
90 deps.extend(copy_self_contained_objects(builder, compiler, target));
91 }
92 deps
93 }
94}
95
96impl Step for Std {
97 type Output = ();
98 const DEFAULT: bool = true;
99
100 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
101 run.crate_or_deps("sysroot").path("library")
102 }
103
104 #[cfg_attr(feature = "tracing", instrument(level = "trace", name = "Std::make_run", skip_all))]
105 fn make_run(run: RunConfig<'_>) {
106 let crates = std_crates_for_run_make(&run);
107 let builder = run.builder;
108
109 let force_recompile = builder.rust_info().is_managed_git_subrepository()
113 && builder.download_rustc()
114 && builder.config.has_changes_from_upstream(&["library"]);
115
116 trace!("is managed git repo: {}", builder.rust_info().is_managed_git_subrepository());
117 trace!("download_rustc: {}", builder.download_rustc());
118 trace!(force_recompile);
119
120 run.builder.ensure(Std {
121 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
122 target: run.target,
123 crates,
124 force_recompile,
125 extra_rust_args: &[],
126 is_for_mir_opt_tests: false,
127 });
128 }
129
130 #[cfg_attr(
136 feature = "tracing",
137 instrument(
138 level = "debug",
139 name = "Std::run",
140 skip_all,
141 fields(
142 target = ?self.target,
143 compiler = ?self.compiler,
144 force_recompile = self.force_recompile
145 ),
146 ),
147 )]
148 fn run(self, builder: &Builder<'_>) {
149 let target = self.target;
150
151 if self.compiler.stage == 0 {
153 let compiler = self.compiler;
154 builder.ensure(StdLink::from_std(self, compiler));
155
156 return;
157 }
158
159 let compiler = if builder.download_rustc() && self.force_recompile {
160 builder.compiler(self.compiler.stage.saturating_sub(1), builder.config.build)
163 } else {
164 self.compiler
165 };
166
167 if builder.download_rustc()
170 && builder.config.is_host_target(target)
171 && !self.force_recompile
172 {
173 let sysroot = builder.ensure(Sysroot { compiler, force_recompile: false });
174 cp_rustc_component_to_ci_sysroot(
175 builder,
176 &sysroot,
177 builder.config.ci_rust_std_contents(),
178 );
179 return;
180 }
181
182 if builder.config.keep_stage.contains(&compiler.stage)
183 || builder.config.keep_stage_std.contains(&compiler.stage)
184 {
185 trace!(keep_stage = ?builder.config.keep_stage);
186 trace!(keep_stage_std = ?builder.config.keep_stage_std);
187
188 builder.info("WARNING: Using a potentially old libstd. This may not behave well.");
189
190 builder.ensure(StartupObjects { compiler, target });
191
192 self.copy_extra_objects(builder, &compiler, target);
193
194 builder.ensure(StdLink::from_std(self, compiler));
195 return;
196 }
197
198 builder.require_submodule("library/stdarch", None);
199
200 let mut target_deps = builder.ensure(StartupObjects { compiler, target });
201
202 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
203 trace!(?compiler_to_use);
204
205 if compiler_to_use != compiler
206 && compiler.stage > 1
211 {
212 trace!(?compiler_to_use, ?compiler, "compiler != compiler_to_use, uplifting library");
213
214 builder.ensure(Std::new(compiler_to_use, target));
215 let msg = if compiler_to_use.host == target {
216 format!(
217 "Uplifting library (stage{} -> stage{})",
218 compiler_to_use.stage, compiler.stage
219 )
220 } else {
221 format!(
222 "Uplifting library (stage{}:{} -> stage{}:{})",
223 compiler_to_use.stage, compiler_to_use.host, compiler.stage, target
224 )
225 };
226 builder.info(&msg);
227
228 self.copy_extra_objects(builder, &compiler, target);
231
232 builder.ensure(StdLink::from_std(self, compiler_to_use));
233 return;
234 }
235
236 trace!(
237 ?compiler_to_use,
238 ?compiler,
239 "compiler == compiler_to_use, handling not-cross-compile scenario"
240 );
241
242 target_deps.extend(self.copy_extra_objects(builder, &compiler, target));
243
244 let mut cargo = if self.is_for_mir_opt_tests {
248 trace!("building special sysroot for mir-opt tests");
249 let mut cargo = builder::Cargo::new_for_mir_opt_tests(
250 builder,
251 compiler,
252 Mode::Std,
253 SourceType::InTree,
254 target,
255 Kind::Check,
256 );
257 cargo.rustflag("-Zalways-encode-mir");
258 cargo.arg("--manifest-path").arg(builder.src.join("library/sysroot/Cargo.toml"));
259 cargo
260 } else {
261 trace!("building regular sysroot");
262 let mut cargo = builder::Cargo::new(
263 builder,
264 compiler,
265 Mode::Std,
266 SourceType::InTree,
267 target,
268 Kind::Build,
269 );
270 std_cargo(builder, target, compiler.stage, &mut cargo);
271 for krate in &*self.crates {
272 cargo.arg("-p").arg(krate);
273 }
274 cargo
275 };
276
277 if target.is_synthetic() {
279 cargo.env("RUSTC_BOOTSTRAP_SYNTHETIC_TARGET", "1");
280 }
281 for rustflag in self.extra_rust_args.iter() {
282 cargo.rustflag(rustflag);
283 }
284
285 let _guard = builder.msg(
286 Kind::Build,
287 compiler.stage,
288 format_args!("library artifacts{}", crate_description(&self.crates)),
289 compiler.host,
290 target,
291 );
292 run_cargo(
293 builder,
294 cargo,
295 vec![],
296 &build_stamp::libstd_stamp(builder, compiler, target),
297 target_deps,
298 self.is_for_mir_opt_tests, false,
300 );
301
302 builder.ensure(StdLink::from_std(
303 self,
304 builder.compiler(compiler.stage, builder.config.build),
305 ));
306 }
307}
308
309fn copy_and_stamp(
310 builder: &Builder<'_>,
311 libdir: &Path,
312 sourcedir: &Path,
313 name: &str,
314 target_deps: &mut Vec<(PathBuf, DependencyType)>,
315 dependency_type: DependencyType,
316) {
317 let target = libdir.join(name);
318 builder.copy_link(&sourcedir.join(name), &target, FileType::Regular);
319
320 target_deps.push((target, dependency_type));
321}
322
323fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
324 let libunwind_path = builder.ensure(llvm::Libunwind { target });
325 let libunwind_source = libunwind_path.join("libunwind.a");
326 let libunwind_target = libdir.join("libunwind.a");
327 builder.copy_link(&libunwind_source, &libunwind_target, FileType::NativeLibrary);
328 libunwind_target
329}
330
331fn copy_third_party_objects(
333 builder: &Builder<'_>,
334 compiler: &Compiler,
335 target: TargetSelection,
336) -> Vec<(PathBuf, DependencyType)> {
337 let mut target_deps = vec![];
338
339 if builder.config.needs_sanitizer_runtime_built(target) && compiler.stage != 0 {
340 target_deps.extend(
343 copy_sanitizers(builder, compiler, target)
344 .into_iter()
345 .map(|d| (d, DependencyType::Target)),
346 );
347 }
348
349 if target == "x86_64-fortanix-unknown-sgx"
350 || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
351 && (target.contains("linux") || target.contains("fuchsia") || target.contains("aix"))
352 {
353 let libunwind_path =
354 copy_llvm_libunwind(builder, target, &builder.sysroot_target_libdir(*compiler, target));
355 target_deps.push((libunwind_path, DependencyType::Target));
356 }
357
358 target_deps
359}
360
361fn copy_self_contained_objects(
363 builder: &Builder<'_>,
364 compiler: &Compiler,
365 target: TargetSelection,
366) -> Vec<(PathBuf, DependencyType)> {
367 let libdir_self_contained =
368 builder.sysroot_target_libdir(*compiler, target).join("self-contained");
369 t!(fs::create_dir_all(&libdir_self_contained));
370 let mut target_deps = vec![];
371
372 if target.needs_crt_begin_end() {
380 let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
381 panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
382 });
383 if !target.starts_with("wasm32") {
384 for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
385 copy_and_stamp(
386 builder,
387 &libdir_self_contained,
388 &srcdir,
389 obj,
390 &mut target_deps,
391 DependencyType::TargetSelfContained,
392 );
393 }
394 let crt_path = builder.ensure(llvm::CrtBeginEnd { target });
395 for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
396 let src = crt_path.join(obj);
397 let target = libdir_self_contained.join(obj);
398 builder.copy_link(&src, &target, FileType::NativeLibrary);
399 target_deps.push((target, DependencyType::TargetSelfContained));
400 }
401 } else {
402 for &obj in &["libc.a", "crt1-command.o"] {
405 copy_and_stamp(
406 builder,
407 &libdir_self_contained,
408 &srcdir,
409 obj,
410 &mut target_deps,
411 DependencyType::TargetSelfContained,
412 );
413 }
414 }
415 if !target.starts_with("s390x") {
416 let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
417 target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
418 }
419 } else if target.contains("-wasi") {
420 let srcdir = builder.wasi_libdir(target).unwrap_or_else(|| {
421 panic!(
422 "Target {:?} does not have a \"wasi-root\" key in bootstrap.toml \
423 or `$WASI_SDK_PATH` set",
424 target.triple
425 )
426 });
427 for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
428 copy_and_stamp(
429 builder,
430 &libdir_self_contained,
431 &srcdir,
432 obj,
433 &mut target_deps,
434 DependencyType::TargetSelfContained,
435 );
436 }
437 } else if target.is_windows_gnu() {
438 for obj in ["crt2.o", "dllcrt2.o"].iter() {
439 let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
440 let dst = libdir_self_contained.join(obj);
441 builder.copy_link(&src, &dst, FileType::NativeLibrary);
442 target_deps.push((dst, DependencyType::TargetSelfContained));
443 }
444 }
445
446 target_deps
447}
448
449pub fn std_crates_for_run_make(run: &RunConfig<'_>) -> Vec<String> {
451 if cfg!(test) {
453 return vec![];
454 }
455
456 let has_alias = run.paths.iter().any(|set| set.assert_single_path().path.ends_with("library"));
457 let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
458
459 if target_is_no_std {
461 vec![]
462 }
463 else if has_alias {
465 run.make_run_crates(builder::Alias::Library)
466 } else {
467 run.cargo_crates_in_set()
468 }
469}
470
471fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
477 if builder.config.llvm_from_ci {
479 builder.config.maybe_download_ci_llvm();
481 let ci_llvm_compiler_rt = builder.config.ci_llvm_root().join("compiler-rt");
482 if ci_llvm_compiler_rt.exists() {
483 return ci_llvm_compiler_rt;
484 }
485 }
486
487 builder.require_submodule("src/llvm-project", {
489 Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
490 });
491 builder.src.join("src/llvm-project/compiler-rt")
492}
493
494pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, stage: u32, cargo: &mut Cargo) {
497 if target.contains("apple") && !builder.config.dry_run() {
515 let mut cmd = command(builder.rustc(cargo.compiler()));
519 cmd.arg("--target").arg(target.rustc_target_arg());
520 cmd.arg("--print=deployment-target");
521 let output = cmd.run_capture_stdout(builder).stdout();
522
523 let (env_var, value) = output.split_once('=').unwrap();
524 cargo.env(env_var.trim(), value.trim());
527
528 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
538 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
539 }
540 }
541
542 if let Some(path) = builder.config.profiler_path(target) {
544 cargo.env("LLVM_PROFILER_RT_LIB", path);
545 } else if builder.config.profiler_enabled(target) {
546 let compiler_rt = compiler_rt_for_profiler(builder);
547 cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
551 }
552
553 let compiler_builtins_c_feature = if builder.config.optimized_compiler_builtins(target) {
567 builder.require_submodule(
575 "src/llvm-project",
576 Some(
577 "The `build.optimized-compiler-builtins` config option \
578 requires `compiler-rt` sources from LLVM.",
579 ),
580 );
581 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
582 assert!(compiler_builtins_root.exists());
583 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
586 " compiler-builtins-c"
587 } else {
588 ""
589 };
590
591 if !builder.unstable_features() {
594 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
595 }
596
597 let mut features = String::new();
598
599 if stage != 0 && builder.config.default_codegen_backend(target).as_deref() == Some("cranelift")
600 {
601 features += "compiler-builtins-no-f16-f128 ";
602 }
603
604 if builder.no_std(target) == Some(true) {
605 features += " compiler-builtins-mem";
606 if !target.starts_with("bpf") {
607 features.push_str(compiler_builtins_c_feature);
608 }
609
610 cargo
612 .args(["-p", "alloc"])
613 .arg("--manifest-path")
614 .arg(builder.src.join("library/alloc/Cargo.toml"))
615 .arg("--features")
616 .arg(features);
617 } else {
618 features += &builder.std_features(target);
619 features.push_str(compiler_builtins_c_feature);
620
621 cargo
622 .arg("--features")
623 .arg(features)
624 .arg("--manifest-path")
625 .arg(builder.src.join("library/sysroot/Cargo.toml"));
626
627 if target.contains("musl")
630 && let Some(p) = builder.musl_libdir(target)
631 {
632 let root = format!("native={}", p.to_str().unwrap());
633 cargo.rustflag("-L").rustflag(&root);
634 }
635
636 if target.contains("-wasi")
637 && let Some(dir) = builder.wasi_libdir(target)
638 {
639 let root = format!("native={}", dir.to_str().unwrap());
640 cargo.rustflag("-L").rustflag(&root);
641 }
642 }
643
644 if stage >= 1 {
653 cargo.rustflag("-Cembed-bitcode=yes");
654 }
655 if builder.config.rust_lto == RustcLto::Off {
656 cargo.rustflag("-Clto=off");
657 }
658
659 if target.contains("riscv") {
666 cargo.rustflag("-Cforce-unwind-tables=yes");
667 }
668
669 cargo.rustflag("-Cforce-frame-pointers=yes");
672
673 let html_root =
674 format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
675 cargo.rustflag(&html_root);
676 cargo.rustdocflag(&html_root);
677
678 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
679}
680
681#[derive(Debug, Clone, PartialEq, Eq, Hash)]
682struct StdLink {
683 pub compiler: Compiler,
684 pub target_compiler: Compiler,
685 pub target: TargetSelection,
686 crates: Vec<String>,
688 force_recompile: bool,
690}
691
692impl StdLink {
693 fn from_std(std: Std, host_compiler: Compiler) -> Self {
694 Self {
695 compiler: host_compiler,
696 target_compiler: std.compiler,
697 target: std.target,
698 crates: std.crates,
699 force_recompile: std.force_recompile,
700 }
701 }
702}
703
704impl Step for StdLink {
705 type Output = ();
706
707 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
708 run.never()
709 }
710
711 #[cfg_attr(
720 feature = "tracing",
721 instrument(
722 level = "trace",
723 name = "StdLink::run",
724 skip_all,
725 fields(
726 compiler = ?self.compiler,
727 target_compiler = ?self.target_compiler,
728 target = ?self.target
729 ),
730 ),
731 )]
732 fn run(self, builder: &Builder<'_>) {
733 let compiler = self.compiler;
734 let target_compiler = self.target_compiler;
735 let target = self.target;
736
737 let (libdir, hostdir) = if !self.force_recompile && builder.download_rustc() {
739 let lib = builder.sysroot_libdir_relative(self.compiler);
741 let sysroot = builder.ensure(crate::core::build_steps::compile::Sysroot {
742 compiler: self.compiler,
743 force_recompile: self.force_recompile,
744 });
745 let libdir = sysroot.join(lib).join("rustlib").join(target).join("lib");
746 let hostdir = sysroot.join(lib).join("rustlib").join(compiler.host).join("lib");
747 (libdir, hostdir)
748 } else {
749 let libdir = builder.sysroot_target_libdir(target_compiler, target);
750 let hostdir = builder.sysroot_target_libdir(target_compiler, compiler.host);
751 (libdir, hostdir)
752 };
753
754 let is_downloaded_beta_stage0 = builder
755 .build
756 .config
757 .initial_rustc
758 .starts_with(builder.out.join(compiler.host).join("stage0/bin"));
759
760 if compiler.stage == 0 && is_downloaded_beta_stage0 {
764 let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
766
767 let host = compiler.host;
768 let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
769 let sysroot_bin_dir = sysroot.join("bin");
770 t!(fs::create_dir_all(&sysroot_bin_dir));
771 builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
772
773 let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
774 t!(fs::create_dir_all(sysroot.join("lib")));
775 builder.cp_link_r(&stage0_lib_dir, &sysroot.join("lib"));
776
777 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
779 t!(fs::create_dir_all(&sysroot_codegen_backends));
780 let stage0_codegen_backends = builder
781 .out
782 .join(host)
783 .join("stage0/lib/rustlib")
784 .join(host)
785 .join("codegen-backends");
786 if stage0_codegen_backends.exists() {
787 builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
788 }
789 } else if compiler.stage == 0 {
790 let sysroot = builder.out.join(compiler.host.triple).join("stage0-sysroot");
791
792 if builder.local_rebuild {
793 let _ = fs::remove_dir_all(sysroot.join("lib/rustlib/src/rust"));
797 }
798
799 builder.cp_link_r(&builder.initial_sysroot.join("lib"), &sysroot.join("lib"));
800 } else {
801 if builder.download_rustc() {
802 let _ = fs::remove_dir_all(&libdir);
804 let _ = fs::remove_dir_all(&hostdir);
805 }
806
807 add_to_sysroot(
808 builder,
809 &libdir,
810 &hostdir,
811 &build_stamp::libstd_stamp(builder, compiler, target),
812 );
813 }
814 }
815}
816
817fn copy_sanitizers(
819 builder: &Builder<'_>,
820 compiler: &Compiler,
821 target: TargetSelection,
822) -> Vec<PathBuf> {
823 let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
824
825 if builder.config.dry_run() {
826 return Vec::new();
827 }
828
829 let mut target_deps = Vec::new();
830 let libdir = builder.sysroot_target_libdir(*compiler, target);
831
832 for runtime in &runtimes {
833 let dst = libdir.join(&runtime.name);
834 builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
835
836 if target == "x86_64-apple-darwin"
840 || target == "aarch64-apple-darwin"
841 || target == "aarch64-apple-ios"
842 || target == "aarch64-apple-ios-sim"
843 || target == "x86_64-apple-ios"
844 {
845 apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
847 apple_darwin_sign_file(builder, &dst);
850 }
851
852 target_deps.push(dst);
853 }
854
855 target_deps
856}
857
858fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
859 command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
860}
861
862fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
863 command("codesign")
864 .arg("-f") .arg("-s")
866 .arg("-")
867 .arg(file_path)
868 .run(builder);
869}
870
871#[derive(Debug, Clone, PartialEq, Eq, Hash)]
872pub struct StartupObjects {
873 pub compiler: Compiler,
874 pub target: TargetSelection,
875}
876
877impl Step for StartupObjects {
878 type Output = Vec<(PathBuf, DependencyType)>;
879
880 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
881 run.path("library/rtstartup")
882 }
883
884 fn make_run(run: RunConfig<'_>) {
885 run.builder.ensure(StartupObjects {
886 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
887 target: run.target,
888 });
889 }
890
891 #[cfg_attr(
898 feature = "tracing",
899 instrument(
900 level = "trace",
901 name = "StartupObjects::run",
902 skip_all,
903 fields(compiler = ?self.compiler, target = ?self.target),
904 ),
905 )]
906 fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
907 let for_compiler = self.compiler;
908 let target = self.target;
909 if !target.is_windows_gnu() {
910 return vec![];
911 }
912
913 let mut target_deps = vec![];
914
915 let src_dir = &builder.src.join("library").join("rtstartup");
916 let dst_dir = &builder.native_dir(target).join("rtstartup");
917 let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
918 t!(fs::create_dir_all(dst_dir));
919
920 for file in &["rsbegin", "rsend"] {
921 let src_file = &src_dir.join(file.to_string() + ".rs");
922 let dst_file = &dst_dir.join(file.to_string() + ".o");
923 if !up_to_date(src_file, dst_file) {
924 let mut cmd = command(&builder.initial_rustc);
925 cmd.env("RUSTC_BOOTSTRAP", "1");
926 if !builder.local_rebuild {
927 cmd.arg("--cfg").arg("bootstrap");
929 }
930 cmd.arg("--target")
931 .arg(target.rustc_target_arg())
932 .arg("--emit=obj")
933 .arg("-o")
934 .arg(dst_file)
935 .arg(src_file)
936 .run(builder);
937 }
938
939 let obj = sysroot_dir.join((*file).to_string() + ".o");
940 builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
941 target_deps.push((obj, DependencyType::Target));
942 }
943
944 target_deps
945 }
946}
947
948fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
949 let ci_rustc_dir = builder.config.ci_rustc_dir();
950
951 for file in contents {
952 let src = ci_rustc_dir.join(&file);
953 let dst = sysroot.join(file);
954 if src.is_dir() {
955 t!(fs::create_dir_all(dst));
956 } else {
957 builder.copy_link(&src, &dst, FileType::Regular);
958 }
959 }
960}
961
962#[derive(Debug, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
963pub struct Rustc {
964 pub target: TargetSelection,
965 pub compiler: Compiler,
967 crates: Vec<String>,
973}
974
975impl Rustc {
976 pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
977 Self { target, compiler, crates: Default::default() }
978 }
979}
980
981impl Step for Rustc {
982 type Output = u32;
990 const ONLY_HOSTS: bool = true;
991 const DEFAULT: bool = false;
992
993 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
994 let mut crates = run.builder.in_tree_crates("rustc-main", None);
995 for (i, krate) in crates.iter().enumerate() {
996 if krate.name == "rustc-main" {
999 crates.swap_remove(i);
1000 break;
1001 }
1002 }
1003 run.crates(crates)
1004 }
1005
1006 fn make_run(run: RunConfig<'_>) {
1007 let crates = run.cargo_crates_in_set();
1008 run.builder.ensure(Rustc {
1009 compiler: run
1010 .builder
1011 .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1012 target: run.target,
1013 crates,
1014 });
1015 }
1016
1017 #[cfg_attr(
1023 feature = "tracing",
1024 instrument(
1025 level = "debug",
1026 name = "Rustc::run",
1027 skip_all,
1028 fields(previous_compiler = ?self.compiler, target = ?self.target),
1029 ),
1030 )]
1031 fn run(self, builder: &Builder<'_>) -> u32 {
1032 let compiler = self.compiler;
1033 let target = self.target;
1034
1035 if builder.download_rustc() && compiler.stage != 0 {
1038 trace!(stage = compiler.stage, "`download_rustc` requested");
1039
1040 let sysroot = builder.ensure(Sysroot { compiler, force_recompile: false });
1041 cp_rustc_component_to_ci_sysroot(
1042 builder,
1043 &sysroot,
1044 builder.config.ci_rustc_dev_contents(),
1045 );
1046 return compiler.stage;
1047 }
1048
1049 builder.ensure(Std::new(compiler, target));
1050
1051 if builder.config.keep_stage.contains(&compiler.stage) {
1052 trace!(stage = compiler.stage, "`keep-stage` requested");
1053
1054 builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1055 builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1056 builder.ensure(RustcLink::from_rustc(self, compiler));
1057
1058 return compiler.stage;
1059 }
1060
1061 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
1062 if compiler_to_use != compiler {
1063 builder.ensure(Rustc::new(compiler_to_use, target));
1064 let msg = if compiler_to_use.host == target {
1065 format!(
1066 "Uplifting rustc (stage{} -> stage{})",
1067 compiler_to_use.stage,
1068 compiler.stage + 1
1069 )
1070 } else {
1071 format!(
1072 "Uplifting rustc (stage{}:{} -> stage{}:{})",
1073 compiler_to_use.stage,
1074 compiler_to_use.host,
1075 compiler.stage + 1,
1076 target
1077 )
1078 };
1079 builder.info(&msg);
1080 builder.ensure(RustcLink::from_rustc(self, compiler_to_use));
1081 return compiler_to_use.stage;
1082 }
1083
1084 builder.ensure(Std::new(
1086 builder.compiler(self.compiler.stage, builder.config.build),
1087 builder.config.build,
1088 ));
1089
1090 let mut cargo = builder::Cargo::new(
1091 builder,
1092 compiler,
1093 Mode::Rustc,
1094 SourceType::InTree,
1095 target,
1096 Kind::Build,
1097 );
1098
1099 rustc_cargo(builder, &mut cargo, target, &compiler, &self.crates);
1100
1101 for krate in &*self.crates {
1105 cargo.arg("-p").arg(krate);
1106 }
1107
1108 if builder.build.config.enable_bolt_settings && compiler.stage == 1 {
1109 cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1111 }
1112
1113 let _guard = builder.msg_sysroot_tool(
1114 Kind::Build,
1115 compiler.stage,
1116 format_args!("compiler artifacts{}", crate_description(&self.crates)),
1117 compiler.host,
1118 target,
1119 );
1120 let stamp = build_stamp::librustc_stamp(builder, compiler, target);
1121 run_cargo(
1122 builder,
1123 cargo,
1124 vec![],
1125 &stamp,
1126 vec![],
1127 false,
1128 true, );
1130
1131 let target_root_dir = stamp.path().parent().unwrap();
1132 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1138 && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1139 {
1140 let rustc_driver = target_root_dir.join("librustc_driver.so");
1141 strip_debug(builder, target, &rustc_driver);
1142 }
1143
1144 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1145 strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1148 }
1149
1150 builder.ensure(RustcLink::from_rustc(
1151 self,
1152 builder.compiler(compiler.stage, builder.config.build),
1153 ));
1154
1155 compiler.stage
1156 }
1157}
1158
1159pub fn rustc_cargo(
1160 builder: &Builder<'_>,
1161 cargo: &mut Cargo,
1162 target: TargetSelection,
1163 compiler: &Compiler,
1164 crates: &[String],
1165) {
1166 cargo
1167 .arg("--features")
1168 .arg(builder.rustc_features(builder.kind, target, crates))
1169 .arg("--manifest-path")
1170 .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1171
1172 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1173
1174 cargo.rustflag("-Zon-broken-pipe=kill");
1188
1189 if builder.config.llvm_enzyme {
1192 let arch = builder.build.build;
1193 let enzyme_dir = builder.build.out.join(arch).join("enzyme").join("lib");
1194 cargo.rustflag("-L").rustflag(enzyme_dir.to_str().expect("Invalid path"));
1195
1196 if let Some(llvm_config) = builder.llvm_config(builder.config.build) {
1197 let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
1198 cargo.rustflag("-l").rustflag(&format!("Enzyme-{llvm_version_major}"));
1199 }
1200 }
1201
1202 if builder.build.config.lld_mode.is_used() {
1207 cargo.rustflag("-Zdefault-visibility=protected");
1208 }
1209
1210 if is_lto_stage(compiler) {
1211 match builder.config.rust_lto {
1212 RustcLto::Thin | RustcLto::Fat => {
1213 cargo.rustflag("-Zdylib-lto");
1216 let lto_type = match builder.config.rust_lto {
1220 RustcLto::Thin => "thin",
1221 RustcLto::Fat => "fat",
1222 _ => unreachable!(),
1223 };
1224 cargo.rustflag(&format!("-Clto={lto_type}"));
1225 cargo.rustflag("-Cembed-bitcode=yes");
1226 }
1227 RustcLto::ThinLocal => { }
1228 RustcLto::Off => {
1229 cargo.rustflag("-Clto=off");
1230 }
1231 }
1232 } else if builder.config.rust_lto == RustcLto::Off {
1233 cargo.rustflag("-Clto=off");
1234 }
1235
1236 if builder.config.lld_mode.is_used() && !compiler.host.is_msvc() {
1244 cargo.rustflag("-Clink-args=-Wl,--icf=all");
1245 }
1246
1247 if builder.config.rust_profile_use.is_some() && builder.config.rust_profile_generate.is_some() {
1248 panic!("Cannot use and generate PGO profiles at the same time");
1249 }
1250 let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
1251 if compiler.stage == 1 {
1252 cargo.rustflag(&format!("-Cprofile-generate={path}"));
1253 cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
1256 true
1257 } else {
1258 false
1259 }
1260 } else if let Some(path) = &builder.config.rust_profile_use {
1261 if compiler.stage == 1 {
1262 cargo.rustflag(&format!("-Cprofile-use={path}"));
1263 if builder.is_verbose() {
1264 cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
1265 }
1266 true
1267 } else {
1268 false
1269 }
1270 } else {
1271 false
1272 };
1273 if is_collecting {
1274 cargo.rustflag(&format!(
1276 "-Cllvm-args=-static-func-strip-dirname-prefix={}",
1277 builder.config.src.components().count()
1278 ));
1279 }
1280
1281 rustc_cargo_env(builder, cargo, target, compiler.stage);
1282}
1283
1284pub fn rustc_cargo_env(
1285 builder: &Builder<'_>,
1286 cargo: &mut Cargo,
1287 target: TargetSelection,
1288 stage: u32,
1289) {
1290 cargo
1293 .env("CFG_RELEASE", builder.rust_release())
1294 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1295 .env("CFG_VERSION", builder.rust_version());
1296
1297 if builder.config.omit_git_hash {
1301 cargo.env("CFG_OMIT_GIT_HASH", "1");
1302 }
1303
1304 if let Some(backend) = builder.config.default_codegen_backend(target) {
1305 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", backend);
1306 }
1307
1308 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1309 let target_config = builder.config.target_config.get(&target);
1310
1311 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1312
1313 if let Some(ref ver_date) = builder.rust_info().commit_date() {
1314 cargo.env("CFG_VER_DATE", ver_date);
1315 }
1316 if let Some(ref ver_hash) = builder.rust_info().sha() {
1317 cargo.env("CFG_VER_HASH", ver_hash);
1318 }
1319 if !builder.unstable_features() {
1320 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1321 }
1322
1323 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1326 cargo.env("CFG_DEFAULT_LINKER", s);
1327 } else if let Some(ref s) = builder.config.rustc_default_linker {
1328 cargo.env("CFG_DEFAULT_LINKER", s);
1329 }
1330
1331 if builder.config.lld_enabled
1333 && (builder.config.channel == "dev" || builder.config.channel == "nightly")
1334 {
1335 cargo.env("CFG_USE_SELF_CONTAINED_LINKER", "1");
1336 }
1337
1338 if builder.config.rust_verify_llvm_ir {
1339 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1340 }
1341
1342 if builder.config.llvm_enzyme {
1343 cargo.rustflag("--cfg=llvm_enzyme");
1344 }
1345
1346 if builder.config.llvm_enabled(target) {
1351 let building_is_expensive =
1352 crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false)
1353 .should_build();
1354 let can_skip_build = builder.kind == Kind::Check && builder.top_stage == stage;
1356 let should_skip_build = building_is_expensive && can_skip_build;
1357 if !should_skip_build {
1358 rustc_llvm_env(builder, cargo, target)
1359 }
1360 }
1361
1362 if builder.config.jemalloc(target)
1365 && target.starts_with("aarch64")
1366 && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none()
1367 {
1368 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1369 }
1370}
1371
1372fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1375 if builder.config.is_rust_llvm(target) {
1376 cargo.env("LLVM_RUSTLLVM", "1");
1377 }
1378 if builder.config.llvm_enzyme {
1379 cargo.env("LLVM_ENZYME", "1");
1380 }
1381 let llvm::LlvmResult { llvm_config, .. } = builder.ensure(llvm::Llvm { target });
1382 cargo.env("LLVM_CONFIG", &llvm_config);
1383
1384 let mut llvm_linker_flags = String::new();
1394 if builder.config.llvm_profile_generate
1395 && target.is_msvc()
1396 && let Some(ref clang_cl_path) = builder.config.llvm_clang_cl
1397 {
1398 let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1400 llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
1401 }
1402
1403 if let Some(ref s) = builder.config.llvm_ldflags {
1405 if !llvm_linker_flags.is_empty() {
1406 llvm_linker_flags.push(' ');
1407 }
1408 llvm_linker_flags.push_str(s);
1409 }
1410
1411 if !llvm_linker_flags.is_empty() {
1413 cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
1414 }
1415
1416 if builder.config.llvm_static_stdcpp
1419 && !target.contains("freebsd")
1420 && !target.is_msvc()
1421 && !target.contains("apple")
1422 && !target.contains("solaris")
1423 {
1424 let libstdcxx_name =
1425 if target.contains("windows-gnullvm") { "libc++.a" } else { "libstdc++.a" };
1426 let file = compiler_file(
1427 builder,
1428 &builder.cxx(target).unwrap(),
1429 target,
1430 CLang::Cxx,
1431 libstdcxx_name,
1432 );
1433 cargo.env("LLVM_STATIC_STDCPP", file);
1434 }
1435 if builder.llvm_link_shared() {
1436 cargo.env("LLVM_LINK_SHARED", "1");
1437 }
1438 if builder.config.llvm_use_libcxx {
1439 cargo.env("LLVM_USE_LIBCXX", "1");
1440 }
1441 if builder.config.llvm_assertions {
1442 cargo.env("LLVM_ASSERTIONS", "1");
1443 }
1444}
1445
1446#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1452struct RustcLink {
1453 pub compiler: Compiler,
1455 pub previous_stage_compiler: Compiler,
1457 pub target: TargetSelection,
1458 crates: Vec<String>,
1460}
1461
1462impl RustcLink {
1463 fn from_rustc(rustc: Rustc, host_compiler: Compiler) -> Self {
1464 Self {
1465 compiler: host_compiler,
1466 previous_stage_compiler: rustc.compiler,
1467 target: rustc.target,
1468 crates: rustc.crates,
1469 }
1470 }
1471}
1472
1473impl Step for RustcLink {
1474 type Output = ();
1475
1476 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1477 run.never()
1478 }
1479
1480 #[cfg_attr(
1482 feature = "tracing",
1483 instrument(
1484 level = "trace",
1485 name = "RustcLink::run",
1486 skip_all,
1487 fields(
1488 compiler = ?self.compiler,
1489 previous_stage_compiler = ?self.previous_stage_compiler,
1490 target = ?self.target,
1491 ),
1492 ),
1493 )]
1494 fn run(self, builder: &Builder<'_>) {
1495 let compiler = self.compiler;
1496 let previous_stage_compiler = self.previous_stage_compiler;
1497 let target = self.target;
1498 add_to_sysroot(
1499 builder,
1500 &builder.sysroot_target_libdir(previous_stage_compiler, target),
1501 &builder.sysroot_target_libdir(previous_stage_compiler, compiler.host),
1502 &build_stamp::librustc_stamp(builder, compiler, target),
1503 );
1504 }
1505}
1506
1507#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1508pub struct CodegenBackend {
1509 pub target: TargetSelection,
1510 pub compiler: Compiler,
1511 pub backend: String,
1512}
1513
1514fn needs_codegen_config(run: &RunConfig<'_>) -> bool {
1515 let mut needs_codegen_cfg = false;
1516 for path_set in &run.paths {
1517 needs_codegen_cfg = match path_set {
1518 PathSet::Set(set) => set.iter().any(|p| is_codegen_cfg_needed(p, run)),
1519 PathSet::Suite(suite) => is_codegen_cfg_needed(suite, run),
1520 }
1521 }
1522 needs_codegen_cfg
1523}
1524
1525pub(crate) const CODEGEN_BACKEND_PREFIX: &str = "rustc_codegen_";
1526
1527fn is_codegen_cfg_needed(path: &TaskPath, run: &RunConfig<'_>) -> bool {
1528 let path = path.path.to_str().unwrap();
1529
1530 let is_explicitly_called = |p| -> bool { run.builder.paths.contains(p) };
1531 let should_enforce = run.builder.kind == Kind::Dist || run.builder.kind == Kind::Install;
1532
1533 if path.contains(CODEGEN_BACKEND_PREFIX) {
1534 let mut needs_codegen_backend_config = true;
1535 for backend in run.builder.config.codegen_backends(run.target) {
1536 if path.ends_with(&(CODEGEN_BACKEND_PREFIX.to_owned() + backend)) {
1537 needs_codegen_backend_config = false;
1538 }
1539 }
1540 if (is_explicitly_called(&PathBuf::from(path)) || should_enforce)
1541 && needs_codegen_backend_config
1542 {
1543 run.builder.info(
1544 "WARNING: no codegen-backends config matched the requested path to build a codegen backend. \
1545 HELP: add backend to codegen-backends in bootstrap.toml.",
1546 );
1547 return true;
1548 }
1549 }
1550
1551 false
1552}
1553
1554impl Step for CodegenBackend {
1555 type Output = ();
1556 const ONLY_HOSTS: bool = true;
1557 const DEFAULT: bool = true;
1559
1560 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1561 run.paths(&["compiler/rustc_codegen_cranelift", "compiler/rustc_codegen_gcc"])
1562 }
1563
1564 fn make_run(run: RunConfig<'_>) {
1565 if needs_codegen_config(&run) {
1566 return;
1567 }
1568
1569 for backend in run.builder.config.codegen_backends(run.target) {
1570 if backend == "llvm" {
1571 continue; }
1573
1574 run.builder.ensure(CodegenBackend {
1575 target: run.target,
1576 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
1577 backend: backend.clone(),
1578 });
1579 }
1580 }
1581
1582 #[cfg_attr(
1583 feature = "tracing",
1584 instrument(
1585 level = "debug",
1586 name = "CodegenBackend::run",
1587 skip_all,
1588 fields(
1589 compiler = ?self.compiler,
1590 target = ?self.target,
1591 backend = ?self.target,
1592 ),
1593 ),
1594 )]
1595 fn run(self, builder: &Builder<'_>) {
1596 let compiler = self.compiler;
1597 let target = self.target;
1598 let backend = self.backend;
1599
1600 builder.ensure(Rustc::new(compiler, target));
1601
1602 if builder.config.keep_stage.contains(&compiler.stage) {
1603 trace!("`keep-stage` requested");
1604 builder.info(
1605 "WARNING: Using a potentially old codegen backend. \
1606 This may not behave well.",
1607 );
1608 return;
1611 }
1612
1613 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
1614 if compiler_to_use != compiler {
1615 builder.ensure(CodegenBackend { compiler: compiler_to_use, target, backend });
1616 return;
1617 }
1618
1619 let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
1620
1621 let mut cargo = builder::Cargo::new(
1622 builder,
1623 compiler,
1624 Mode::Codegen,
1625 SourceType::InTree,
1626 target,
1627 Kind::Build,
1628 );
1629 cargo
1630 .arg("--manifest-path")
1631 .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml")));
1632 rustc_cargo_env(builder, &mut cargo, target, compiler.stage);
1633
1634 if backend == "gcc" {
1638 let gcc = builder.ensure(Gcc { target });
1639 add_cg_gcc_cargo_flags(&mut cargo, &gcc);
1640 }
1641
1642 let tmp_stamp = BuildStamp::new(&out_dir).with_prefix("tmp");
1643
1644 let _guard = builder.msg_build(compiler, format_args!("codegen backend {backend}"), target);
1645 let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false, false);
1646 if builder.config.dry_run() {
1647 return;
1648 }
1649 let mut files = files.into_iter().filter(|f| {
1650 let filename = f.file_name().unwrap().to_str().unwrap();
1651 is_dylib(f) && filename.contains("rustc_codegen_")
1652 });
1653 let codegen_backend = match files.next() {
1654 Some(f) => f,
1655 None => panic!("no dylibs built for codegen backend?"),
1656 };
1657 if let Some(f) = files.next() {
1658 panic!(
1659 "codegen backend built two dylibs:\n{}\n{}",
1660 codegen_backend.display(),
1661 f.display()
1662 );
1663 }
1664 let stamp = build_stamp::codegen_backend_stamp(builder, compiler, target, &backend);
1665 let codegen_backend = codegen_backend.to_str().unwrap();
1666 t!(stamp.add_stamp(codegen_backend).write());
1667 }
1668}
1669
1670fn copy_codegen_backends_to_sysroot(
1677 builder: &Builder<'_>,
1678 compiler: Compiler,
1679 target_compiler: Compiler,
1680) {
1681 let target = target_compiler.host;
1682
1683 let dst = builder.sysroot_codegen_backends(target_compiler);
1692 t!(fs::create_dir_all(&dst), dst);
1693
1694 if builder.config.dry_run() {
1695 return;
1696 }
1697
1698 for backend in builder.config.codegen_backends(target) {
1699 if backend == "llvm" {
1700 continue; }
1702
1703 let stamp = build_stamp::codegen_backend_stamp(builder, compiler, target, backend);
1704 let dylib = t!(fs::read_to_string(stamp.path()));
1705 let file = Path::new(&dylib);
1706 let filename = file.file_name().unwrap().to_str().unwrap();
1707 let target_filename = {
1710 let dash = filename.find('-').unwrap();
1711 let dot = filename.find('.').unwrap();
1712 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1713 };
1714 builder.copy_link(file, &dst.join(target_filename), FileType::NativeLibrary);
1715 }
1716}
1717
1718pub fn compiler_file(
1719 builder: &Builder<'_>,
1720 compiler: &Path,
1721 target: TargetSelection,
1722 c: CLang,
1723 file: &str,
1724) -> PathBuf {
1725 if builder.config.dry_run() {
1726 return PathBuf::new();
1727 }
1728 let mut cmd = command(compiler);
1729 cmd.args(builder.cc_handled_clags(target, c));
1730 cmd.args(builder.cc_unhandled_cflags(target, GitRepo::Rustc, c));
1731 cmd.arg(format!("-print-file-name={file}"));
1732 let out = cmd.run_capture_stdout(builder).stdout();
1733 PathBuf::from(out.trim())
1734}
1735
1736#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1737pub struct Sysroot {
1738 pub compiler: Compiler,
1739 force_recompile: bool,
1741}
1742
1743impl Sysroot {
1744 pub(crate) fn new(compiler: Compiler) -> Self {
1745 Sysroot { compiler, force_recompile: false }
1746 }
1747}
1748
1749impl Step for Sysroot {
1750 type Output = PathBuf;
1751
1752 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1753 run.never()
1754 }
1755
1756 #[cfg_attr(
1760 feature = "tracing",
1761 instrument(
1762 level = "debug",
1763 name = "Sysroot::run",
1764 skip_all,
1765 fields(compiler = ?self.compiler),
1766 ),
1767 )]
1768 fn run(self, builder: &Builder<'_>) -> PathBuf {
1769 let compiler = self.compiler;
1770 let host_dir = builder.out.join(compiler.host);
1771
1772 let sysroot_dir = |stage| {
1773 if stage == 0 {
1774 host_dir.join("stage0-sysroot")
1775 } else if self.force_recompile && stage == compiler.stage {
1776 host_dir.join(format!("stage{stage}-test-sysroot"))
1777 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1778 host_dir.join("ci-rustc-sysroot")
1779 } else {
1780 host_dir.join(format!("stage{stage}"))
1781 }
1782 };
1783 let sysroot = sysroot_dir(compiler.stage);
1784 trace!(stage = ?compiler.stage, ?sysroot);
1785
1786 builder
1787 .verbose(|| println!("Removing sysroot {} to avoid caching bugs", sysroot.display()));
1788 let _ = fs::remove_dir_all(&sysroot);
1789 t!(fs::create_dir_all(&sysroot));
1790
1791 if compiler.stage == 0 {
1798 dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1799 }
1800
1801 if builder.download_rustc() && compiler.stage != 0 {
1803 assert_eq!(
1804 builder.config.build, compiler.host,
1805 "Cross-compiling is not yet supported with `download-rustc`",
1806 );
1807
1808 for stage in 0..=2 {
1810 if stage != compiler.stage {
1811 let dir = sysroot_dir(stage);
1812 if !dir.ends_with("ci-rustc-sysroot") {
1813 let _ = fs::remove_dir_all(dir);
1814 }
1815 }
1816 }
1817
1818 let mut filtered_files = Vec::new();
1828 let mut add_filtered_files = |suffix, contents| {
1829 for path in contents {
1830 let path = Path::new(&path);
1831 if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
1832 filtered_files.push(path.file_name().unwrap().to_owned());
1833 }
1834 }
1835 };
1836 let suffix = format!("lib/rustlib/{}/lib", compiler.host);
1837 add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
1838 add_filtered_files("lib", builder.config.ci_rust_std_contents());
1841
1842 let filtered_extensions = [
1843 OsStr::new("rmeta"),
1844 OsStr::new("rlib"),
1845 OsStr::new(std::env::consts::DLL_EXTENSION),
1847 ];
1848 let ci_rustc_dir = builder.config.ci_rustc_dir();
1849 builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
1850 if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
1851 return true;
1852 }
1853 if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
1854 return true;
1855 }
1856 if !filtered_files.iter().all(|f| f != path.file_name().unwrap()) {
1857 builder.verbose_than(1, || println!("ignoring {}", path.display()));
1858 false
1859 } else {
1860 true
1861 }
1862 });
1863 }
1864
1865 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
1871 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
1872 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
1873 if let Err(e) = symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust) {
1874 eprintln!(
1875 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
1876 sysroot_lib_rustlib_src_rust.display(),
1877 builder.src.display(),
1878 e,
1879 );
1880 if builder.config.rust_remap_debuginfo {
1881 eprintln!(
1882 "ERROR: some `tests/ui` tests will fail when lacking `{}`",
1883 sysroot_lib_rustlib_src_rust.display(),
1884 );
1885 }
1886 build_helper::exit!(1);
1887 }
1888
1889 if !builder.download_rustc() {
1891 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
1892 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
1893 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
1894 if let Err(e) =
1895 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
1896 {
1897 eprintln!(
1898 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
1899 sysroot_lib_rustlib_rustcsrc_rust.display(),
1900 builder.src.display(),
1901 e,
1902 );
1903 build_helper::exit!(1);
1904 }
1905 }
1906
1907 sysroot
1908 }
1909}
1910
1911#[derive(Debug, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
1912pub struct Assemble {
1913 pub target_compiler: Compiler,
1918}
1919
1920impl Step for Assemble {
1921 type Output = Compiler;
1922 const ONLY_HOSTS: bool = true;
1923
1924 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1925 run.path("compiler/rustc").path("compiler")
1926 }
1927
1928 fn make_run(run: RunConfig<'_>) {
1929 run.builder.ensure(Assemble {
1930 target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
1931 });
1932 }
1933
1934 #[cfg_attr(
1940 feature = "tracing",
1941 instrument(
1942 level = "debug",
1943 name = "Assemble::run",
1944 skip_all,
1945 fields(target_compiler = ?self.target_compiler),
1946 ),
1947 )]
1948 fn run(self, builder: &Builder<'_>) -> Compiler {
1949 let target_compiler = self.target_compiler;
1950
1951 if target_compiler.stage == 0 {
1952 trace!("stage 0 build compiler is always available, simply returning");
1953 assert_eq!(
1954 builder.config.build, target_compiler.host,
1955 "Cannot obtain compiler for non-native build triple at stage 0"
1956 );
1957 return target_compiler;
1959 }
1960
1961 let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
1964 let libdir_bin = libdir.parent().unwrap().join("bin");
1965 t!(fs::create_dir_all(&libdir_bin));
1966
1967 if builder.config.llvm_enabled(target_compiler.host) {
1968 trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
1969
1970 let llvm::LlvmResult { llvm_config, .. } =
1971 builder.ensure(llvm::Llvm { target: target_compiler.host });
1972 if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
1973 trace!("LLVM tools enabled");
1974
1975 let llvm_bin_dir =
1976 command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
1977 let llvm_bin_dir = Path::new(llvm_bin_dir.trim());
1978
1979 #[cfg(feature = "tracing")]
1986 let _llvm_tools_span =
1987 span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
1988 .entered();
1989 for tool in LLVM_TOOLS {
1990 trace!("installing `{tool}`");
1991 let tool_exe = exe(tool, target_compiler.host);
1992 let src_path = llvm_bin_dir.join(&tool_exe);
1993
1994 if !src_path.exists() && builder.config.llvm_from_ci {
1996 eprintln!("{} does not exist; skipping copy", src_path.display());
1997 continue;
1998 }
1999
2000 builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2007 }
2008 }
2009 }
2010
2011 let maybe_install_llvm_bitcode_linker = |compiler| {
2012 if builder.config.llvm_bitcode_linker_enabled {
2013 trace!("llvm-bitcode-linker enabled, installing");
2014 let llvm_bitcode_linker =
2015 builder.ensure(crate::core::build_steps::tool::LlvmBitcodeLinker {
2016 compiler,
2017 target: target_compiler.host,
2018 extra_features: vec![],
2019 });
2020 let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2021 builder.copy_link(
2022 &llvm_bitcode_linker.tool_path,
2023 &libdir_bin.join(tool_exe),
2024 FileType::Executable,
2025 );
2026 }
2027 };
2028
2029 if builder.download_rustc() {
2031 trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2032
2033 builder.ensure(Std::new(target_compiler, target_compiler.host));
2034 let sysroot =
2035 builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2036 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2039 if target_compiler.stage == builder.top_stage {
2041 builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage=target_compiler.stage));
2042 }
2043
2044 let mut precompiled_compiler = target_compiler;
2045 precompiled_compiler.forced_compiler(true);
2046 maybe_install_llvm_bitcode_linker(precompiled_compiler);
2047
2048 return target_compiler;
2049 }
2050
2051 debug!(
2065 "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2066 target_compiler.stage - 1,
2067 builder.config.build,
2068 );
2069 let mut build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
2070
2071 if builder.config.llvm_enzyme && !builder.config.dry_run() {
2073 debug!("`llvm_enzyme` requested");
2074 let enzyme_install = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2075 let llvm_config = builder.llvm_config(builder.config.build).unwrap();
2076 let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
2077 let lib_ext = std::env::consts::DLL_EXTENSION;
2078 let libenzyme = format!("libEnzyme-{llvm_version_major}");
2079 let src_lib =
2080 enzyme_install.join("build/Enzyme").join(&libenzyme).with_extension(lib_ext);
2081 let libdir = builder.sysroot_target_libdir(build_compiler, build_compiler.host);
2082 let target_libdir =
2083 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2084 let dst_lib = libdir.join(&libenzyme).with_extension(lib_ext);
2085 let target_dst_lib = target_libdir.join(&libenzyme).with_extension(lib_ext);
2086 builder.copy_link(&src_lib, &dst_lib, FileType::NativeLibrary);
2087 builder.copy_link(&src_lib, &target_dst_lib, FileType::NativeLibrary);
2088 }
2089
2090 debug!(
2096 ?build_compiler,
2097 "target_compiler.host" = ?target_compiler.host,
2098 "building compiler libraries to link to"
2099 );
2100 let actual_stage = builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2101 debug!(
2104 "(old) build_compiler.stage" = build_compiler.stage,
2105 "(adjusted) build_compiler.stage" = actual_stage,
2106 "temporarily adjusting `build_compiler.stage` to account for uplifted libraries"
2107 );
2108 build_compiler.stage = actual_stage;
2109
2110 #[cfg(feature = "tracing")]
2111 let _codegen_backend_span =
2112 span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2113 for backend in builder.config.codegen_backends(target_compiler.host) {
2114 if backend == "llvm" {
2115 debug!("llvm codegen backend is already built as part of rustc");
2116 continue; }
2118
2119 builder.ensure(CodegenBackend {
2120 compiler: build_compiler,
2121 target: target_compiler.host,
2122 backend: backend.clone(),
2123 });
2124 }
2125 #[cfg(feature = "tracing")]
2126 drop(_codegen_backend_span);
2127
2128 let stage = target_compiler.stage;
2129 let host = target_compiler.host;
2130 let (host_info, dir_name) = if build_compiler.host == host {
2131 ("".into(), "host".into())
2132 } else {
2133 (format!(" ({host})"), host.to_string())
2134 };
2135 let msg = format!(
2140 "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2141 );
2142 builder.info(&msg);
2143
2144 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2146 let proc_macros = builder
2147 .read_stamp_file(&stamp)
2148 .into_iter()
2149 .filter_map(|(path, dependency_type)| {
2150 if dependency_type == DependencyType::Host {
2151 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2152 } else {
2153 None
2154 }
2155 })
2156 .collect::<HashSet<_>>();
2157
2158 let sysroot = builder.sysroot(target_compiler);
2159 let rustc_libdir = builder.rustc_libdir(target_compiler);
2160 t!(fs::create_dir_all(&rustc_libdir));
2161 let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2162 for f in builder.read_dir(&src_libdir) {
2163 let filename = f.file_name().into_string().unwrap();
2164
2165 let is_proc_macro = proc_macros.contains(&filename);
2166 let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2167
2168 let can_be_rustc_dynamic_dep = if builder
2172 .link_std_into_rustc_driver(target_compiler.host)
2173 && !target_compiler.host.is_windows()
2174 {
2175 let is_std = filename.starts_with("std-") || filename.starts_with("libstd-");
2176 !is_std
2177 } else {
2178 true
2179 };
2180
2181 if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2182 builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2183 }
2184 }
2185
2186 debug!("copying codegen backends to sysroot");
2187 copy_codegen_backends_to_sysroot(builder, build_compiler, target_compiler);
2188
2189 if builder.config.lld_enabled && !builder.config.is_system_llvm(target_compiler.host) {
2190 builder.ensure(crate::core::build_steps::tool::LldWrapper {
2191 build_compiler,
2192 target_compiler,
2193 });
2194 }
2195
2196 if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2197 debug!(
2198 "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2199 workaround faulty homebrew `strip`s"
2200 );
2201
2202 let src_exe = exe("llvm-objcopy", target_compiler.host);
2209 let dst_exe = exe("rust-objcopy", target_compiler.host);
2210 builder.copy_link(
2211 &libdir_bin.join(src_exe),
2212 &libdir_bin.join(dst_exe),
2213 FileType::Executable,
2214 );
2215 }
2216
2217 if builder.tool_enabled("wasm-component-ld") {
2223 let wasm_component = builder.ensure(crate::core::build_steps::tool::WasmComponentLd {
2224 compiler: build_compiler,
2225 target: target_compiler.host,
2226 });
2227 builder.copy_link(
2228 &wasm_component.tool_path,
2229 &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2230 FileType::Executable,
2231 );
2232 }
2233
2234 maybe_install_llvm_bitcode_linker(target_compiler);
2235
2236 debug!(
2239 "target_compiler.host" = ?target_compiler.host,
2240 ?sysroot,
2241 "ensuring availability of `libLLVM.so` in compiler directory"
2242 );
2243 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2244 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2245
2246 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2248 let rustc = out_dir.join(exe("rustc-main", host));
2249 let bindir = sysroot.join("bin");
2250 t!(fs::create_dir_all(bindir));
2251 let compiler = builder.rustc(target_compiler);
2252 debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2253 builder.copy_link(&rustc, &compiler, FileType::Executable);
2254
2255 target_compiler
2256 }
2257}
2258
2259pub fn add_to_sysroot(
2264 builder: &Builder<'_>,
2265 sysroot_dst: &Path,
2266 sysroot_host_dst: &Path,
2267 stamp: &BuildStamp,
2268) {
2269 let self_contained_dst = &sysroot_dst.join("self-contained");
2270 t!(fs::create_dir_all(sysroot_dst));
2271 t!(fs::create_dir_all(sysroot_host_dst));
2272 t!(fs::create_dir_all(self_contained_dst));
2273 for (path, dependency_type) in builder.read_stamp_file(stamp) {
2274 let dst = match dependency_type {
2275 DependencyType::Host => sysroot_host_dst,
2276 DependencyType::Target => sysroot_dst,
2277 DependencyType::TargetSelfContained => self_contained_dst,
2278 };
2279 builder.copy_link(&path, &dst.join(path.file_name().unwrap()), FileType::Regular);
2280 }
2281}
2282
2283pub fn run_cargo(
2284 builder: &Builder<'_>,
2285 cargo: Cargo,
2286 tail_args: Vec<String>,
2287 stamp: &BuildStamp,
2288 additional_target_deps: Vec<(PathBuf, DependencyType)>,
2289 is_check: bool,
2290 rlib_only_metadata: bool,
2291) -> Vec<PathBuf> {
2292 let target_root_dir = stamp.path().parent().unwrap();
2294 let target_deps_dir = target_root_dir.join("deps");
2296 let host_root_dir = target_root_dir
2298 .parent()
2299 .unwrap() .parent()
2301 .unwrap() .join(target_root_dir.file_name().unwrap());
2303
2304 let mut deps = Vec::new();
2308 let mut toplevel = Vec::new();
2309 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2310 let (filenames, crate_types) = match msg {
2311 CargoMessage::CompilerArtifact {
2312 filenames,
2313 target: CargoTarget { crate_types },
2314 ..
2315 } => (filenames, crate_types),
2316 _ => return,
2317 };
2318 for filename in filenames {
2319 let mut keep = false;
2321 if filename.ends_with(".lib")
2322 || filename.ends_with(".a")
2323 || is_debug_info(&filename)
2324 || is_dylib(Path::new(&*filename))
2325 {
2326 keep = true;
2328 }
2329 if is_check && filename.ends_with(".rmeta") {
2330 keep = true;
2332 } else if rlib_only_metadata {
2333 if filename.contains("jemalloc_sys")
2334 || filename.contains("rustc_smir")
2335 || filename.contains("stable_mir")
2336 {
2337 keep |= filename.ends_with(".rlib");
2340 } else {
2341 keep |= filename.ends_with(".rmeta");
2345 }
2346 } else {
2347 keep |= filename.ends_with(".rlib");
2349 }
2350
2351 if !keep {
2352 continue;
2353 }
2354
2355 let filename = Path::new(&*filename);
2356
2357 if filename.starts_with(&host_root_dir) {
2360 if crate_types.iter().any(|t| t == "proc-macro") {
2362 deps.push((filename.to_path_buf(), DependencyType::Host));
2363 }
2364 continue;
2365 }
2366
2367 if filename.starts_with(&target_deps_dir) {
2370 deps.push((filename.to_path_buf(), DependencyType::Target));
2371 continue;
2372 }
2373
2374 let expected_len = t!(filename.metadata()).len();
2385 let filename = filename.file_name().unwrap().to_str().unwrap();
2386 let mut parts = filename.splitn(2, '.');
2387 let file_stem = parts.next().unwrap().to_owned();
2388 let extension = parts.next().unwrap().to_owned();
2389
2390 toplevel.push((file_stem, extension, expected_len));
2391 }
2392 });
2393
2394 if !ok {
2395 crate::exit!(1);
2396 }
2397
2398 if builder.config.dry_run() {
2399 return Vec::new();
2400 }
2401
2402 let contents = target_deps_dir
2406 .read_dir()
2407 .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_deps_dir.display(), e))
2408 .map(|e| t!(e))
2409 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2410 .collect::<Vec<_>>();
2411 for (prefix, extension, expected_len) in toplevel {
2412 let candidates = contents.iter().filter(|&(_, filename, meta)| {
2413 meta.len() == expected_len
2414 && filename
2415 .strip_prefix(&prefix[..])
2416 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2417 .unwrap_or(false)
2418 });
2419 let max = candidates.max_by_key(|&(_, _, metadata)| {
2420 metadata.modified().expect("mtime should be available on all relevant OSes")
2421 });
2422 let path_to_add = match max {
2423 Some(triple) => triple.0.to_str().unwrap(),
2424 None => panic!("no output generated for {prefix:?} {extension:?}"),
2425 };
2426 if is_dylib(Path::new(path_to_add)) {
2427 let candidate = format!("{path_to_add}.lib");
2428 let candidate = PathBuf::from(candidate);
2429 if candidate.exists() {
2430 deps.push((candidate, DependencyType::Target));
2431 }
2432 }
2433 deps.push((path_to_add.into(), DependencyType::Target));
2434 }
2435
2436 deps.extend(additional_target_deps);
2437 deps.sort();
2438 let mut new_contents = Vec::new();
2439 for (dep, dependency_type) in deps.iter() {
2440 new_contents.extend(match *dependency_type {
2441 DependencyType::Host => b"h",
2442 DependencyType::Target => b"t",
2443 DependencyType::TargetSelfContained => b"s",
2444 });
2445 new_contents.extend(dep.to_str().unwrap().as_bytes());
2446 new_contents.extend(b"\0");
2447 }
2448 t!(fs::write(stamp.path(), &new_contents));
2449 deps.into_iter().map(|(d, _)| d).collect()
2450}
2451
2452pub fn stream_cargo(
2453 builder: &Builder<'_>,
2454 cargo: Cargo,
2455 tail_args: Vec<String>,
2456 cb: &mut dyn FnMut(CargoMessage<'_>),
2457) -> bool {
2458 let mut cmd = cargo.into_cmd();
2459
2460 #[cfg(feature = "tracing")]
2461 let _run_span = crate::trace_cmd!(cmd);
2462
2463 let cargo = cmd.as_command_mut();
2464 let mut message_format = if builder.config.json_output {
2467 String::from("json")
2468 } else {
2469 String::from("json-render-diagnostics")
2470 };
2471 if let Some(s) = &builder.config.rustc_error_format {
2472 message_format.push_str(",json-diagnostic-");
2473 message_format.push_str(s);
2474 }
2475 cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
2476
2477 for arg in tail_args {
2478 cargo.arg(arg);
2479 }
2480
2481 builder.verbose(|| println!("running: {cargo:?}"));
2482
2483 if builder.config.dry_run() {
2484 return true;
2485 }
2486
2487 let mut child = match cargo.spawn() {
2488 Ok(child) => child,
2489 Err(e) => panic!("failed to execute command: {cargo:?}\nERROR: {e}"),
2490 };
2491
2492 let stdout = BufReader::new(child.stdout.take().unwrap());
2496 for line in stdout.lines() {
2497 let line = t!(line);
2498 match serde_json::from_str::<CargoMessage<'_>>(&line) {
2499 Ok(msg) => {
2500 if builder.config.json_output {
2501 println!("{line}");
2503 }
2504 cb(msg)
2505 }
2506 Err(_) => println!("{line}"),
2508 }
2509 }
2510
2511 let status = t!(child.wait());
2513 if builder.is_verbose() && !status.success() {
2514 eprintln!(
2515 "command did not execute successfully: {cargo:?}\n\
2516 expected success, got: {status}"
2517 );
2518 }
2519 status.success()
2520}
2521
2522#[derive(Deserialize)]
2523pub struct CargoTarget<'a> {
2524 crate_types: Vec<Cow<'a, str>>,
2525}
2526
2527#[derive(Deserialize)]
2528#[serde(tag = "reason", rename_all = "kebab-case")]
2529pub enum CargoMessage<'a> {
2530 CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2531 BuildScriptExecuted,
2532 BuildFinished,
2533}
2534
2535pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2536 if target != "x86_64-unknown-linux-gnu"
2540 || !builder.config.is_host_target(target)
2541 || !path.exists()
2542 {
2543 return;
2544 }
2545
2546 let previous_mtime = t!(t!(path.metadata()).modified());
2547 command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2548
2549 let file = t!(fs::File::open(path));
2550
2551 t!(file.set_modified(previous_mtime));
2564}
2565
2566pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2568 build_compiler.stage != 0
2569}