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::{env, fs, str};
16
17use serde_derive::Deserialize;
18#[cfg(feature = "tracing")]
19use tracing::{instrument, span};
20
21use crate::core::build_steps::gcc::{Gcc, add_cg_gcc_cargo_flags};
22use crate::core::build_steps::tool::{SourceType, copy_lld_artifacts};
23use crate::core::build_steps::{dist, llvm};
24use crate::core::builder;
25use crate::core::builder::{
26 Builder, Cargo, Kind, PathSet, RunConfig, ShouldRun, Step, StepMetadata, TaskPath,
27 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::{
37 CLang, CodegenBackendKind, Compiler, DependencyType, FileType, GitRepo, LLVM_TOOLS, Mode,
38 debug, trace,
39};
40
41#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
43pub struct Std {
44 pub target: TargetSelection,
45 pub compiler: Compiler,
46 crates: Vec<String>,
50 force_recompile: bool,
53 extra_rust_args: &'static [&'static str],
54 is_for_mir_opt_tests: bool,
55}
56
57impl Std {
58 pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
59 Self {
60 target,
61 compiler,
62 crates: Default::default(),
63 force_recompile: false,
64 extra_rust_args: &[],
65 is_for_mir_opt_tests: false,
66 }
67 }
68
69 pub fn force_recompile(mut self, force_recompile: bool) -> Self {
70 self.force_recompile = force_recompile;
71 self
72 }
73
74 #[expect(clippy::wrong_self_convention)]
75 pub fn is_for_mir_opt_tests(mut self, is_for_mir_opt_tests: bool) -> Self {
76 self.is_for_mir_opt_tests = is_for_mir_opt_tests;
77 self
78 }
79
80 pub fn extra_rust_args(mut self, extra_rust_args: &'static [&'static str]) -> Self {
81 self.extra_rust_args = extra_rust_args;
82 self
83 }
84
85 fn copy_extra_objects(
86 &self,
87 builder: &Builder<'_>,
88 compiler: &Compiler,
89 target: TargetSelection,
90 ) -> Vec<(PathBuf, DependencyType)> {
91 let mut deps = Vec::new();
92 if !self.is_for_mir_opt_tests {
93 deps.extend(copy_third_party_objects(builder, compiler, target));
94 deps.extend(copy_self_contained_objects(builder, compiler, target));
95 }
96 deps
97 }
98}
99
100impl Step for Std {
101 type Output = ();
102 const DEFAULT: bool = true;
103
104 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
105 run.crate_or_deps("sysroot").path("library")
106 }
107
108 #[cfg_attr(feature = "tracing", instrument(level = "trace", name = "Std::make_run", skip_all))]
109 fn make_run(run: RunConfig<'_>) {
110 let crates = std_crates_for_run_make(&run);
111 let builder = run.builder;
112
113 let force_recompile = builder.rust_info().is_managed_git_subrepository()
117 && builder.download_rustc()
118 && builder.config.has_changes_from_upstream(&["library"]);
119
120 trace!("is managed git repo: {}", builder.rust_info().is_managed_git_subrepository());
121 trace!("download_rustc: {}", builder.download_rustc());
122 trace!(force_recompile);
123
124 run.builder.ensure(Std {
125 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
126 target: run.target,
127 crates,
128 force_recompile,
129 extra_rust_args: &[],
130 is_for_mir_opt_tests: false,
131 });
132 }
133
134 #[cfg_attr(
140 feature = "tracing",
141 instrument(
142 level = "debug",
143 name = "Std::run",
144 skip_all,
145 fields(
146 target = ?self.target,
147 compiler = ?self.compiler,
148 force_recompile = self.force_recompile
149 ),
150 ),
151 )]
152 fn run(self, builder: &Builder<'_>) {
153 let target = self.target;
154
155 if self.compiler.stage == 0 {
157 let compiler = self.compiler;
158 builder.ensure(StdLink::from_std(self, compiler));
159
160 return;
161 }
162
163 let compiler = if builder.download_rustc() && self.force_recompile {
164 builder.compiler(self.compiler.stage.saturating_sub(1), builder.config.host_target)
167 } else {
168 self.compiler
169 };
170
171 if builder.download_rustc()
174 && builder.config.is_host_target(target)
175 && !self.force_recompile
176 {
177 let sysroot = builder.ensure(Sysroot { compiler, force_recompile: false });
178 cp_rustc_component_to_ci_sysroot(
179 builder,
180 &sysroot,
181 builder.config.ci_rust_std_contents(),
182 );
183 return;
184 }
185
186 if builder.config.keep_stage.contains(&compiler.stage)
187 || builder.config.keep_stage_std.contains(&compiler.stage)
188 {
189 trace!(keep_stage = ?builder.config.keep_stage);
190 trace!(keep_stage_std = ?builder.config.keep_stage_std);
191
192 builder.info("WARNING: Using a potentially old libstd. This may not behave well.");
193
194 builder.ensure(StartupObjects { compiler, target });
195
196 self.copy_extra_objects(builder, &compiler, target);
197
198 builder.ensure(StdLink::from_std(self, compiler));
199 return;
200 }
201
202 let mut target_deps = builder.ensure(StartupObjects { compiler, target });
203
204 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
205 trace!(?compiler_to_use);
206
207 if compiler_to_use != compiler
208 && compiler.stage > 1
213 {
214 trace!(?compiler_to_use, ?compiler, "compiler != compiler_to_use, uplifting library");
215
216 builder.std(compiler_to_use, target);
217 let msg = if compiler_to_use.host == target {
218 format!(
219 "Uplifting library (stage{} -> stage{})",
220 compiler_to_use.stage, compiler.stage
221 )
222 } else {
223 format!(
224 "Uplifting library (stage{}:{} -> stage{}:{})",
225 compiler_to_use.stage, compiler_to_use.host, compiler.stage, target
226 )
227 };
228 builder.info(&msg);
229
230 self.copy_extra_objects(builder, &compiler, target);
233
234 builder.ensure(StdLink::from_std(self, compiler_to_use));
235 return;
236 }
237
238 trace!(
239 ?compiler_to_use,
240 ?compiler,
241 "compiler == compiler_to_use, handling not-cross-compile scenario"
242 );
243
244 target_deps.extend(self.copy_extra_objects(builder, &compiler, target));
245
246 let mut cargo = if self.is_for_mir_opt_tests {
250 trace!("building special sysroot for mir-opt tests");
251 let mut cargo = builder::Cargo::new_for_mir_opt_tests(
252 builder,
253 compiler,
254 Mode::Std,
255 SourceType::InTree,
256 target,
257 Kind::Check,
258 );
259 cargo.rustflag("-Zalways-encode-mir");
260 cargo.arg("--manifest-path").arg(builder.src.join("library/sysroot/Cargo.toml"));
261 cargo
262 } else {
263 trace!("building regular sysroot");
264 let mut cargo = builder::Cargo::new(
265 builder,
266 compiler,
267 Mode::Std,
268 SourceType::InTree,
269 target,
270 Kind::Build,
271 );
272 std_cargo(builder, target, compiler.stage, &mut cargo);
273 for krate in &*self.crates {
274 cargo.arg("-p").arg(krate);
275 }
276 cargo
277 };
278
279 if target.is_synthetic() {
281 cargo.env("RUSTC_BOOTSTRAP_SYNTHETIC_TARGET", "1");
282 }
283 for rustflag in self.extra_rust_args.iter() {
284 cargo.rustflag(rustflag);
285 }
286
287 let _guard = builder.msg(
288 Kind::Build,
289 compiler.stage,
290 format_args!("library artifacts{}", crate_description(&self.crates)),
291 compiler.host,
292 target,
293 );
294 run_cargo(
295 builder,
296 cargo,
297 vec![],
298 &build_stamp::libstd_stamp(builder, compiler, target),
299 target_deps,
300 self.is_for_mir_opt_tests, false,
302 );
303
304 builder.ensure(StdLink::from_std(
305 self,
306 builder.compiler(compiler.stage, builder.config.host_target),
307 ));
308 }
309
310 fn metadata(&self) -> Option<StepMetadata> {
311 Some(StepMetadata::build("std", self.target).built_by(self.compiler))
312 }
313}
314
315fn copy_and_stamp(
316 builder: &Builder<'_>,
317 libdir: &Path,
318 sourcedir: &Path,
319 name: &str,
320 target_deps: &mut Vec<(PathBuf, DependencyType)>,
321 dependency_type: DependencyType,
322) {
323 let target = libdir.join(name);
324 builder.copy_link(&sourcedir.join(name), &target, FileType::Regular);
325
326 target_deps.push((target, dependency_type));
327}
328
329fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
330 let libunwind_path = builder.ensure(llvm::Libunwind { target });
331 let libunwind_source = libunwind_path.join("libunwind.a");
332 let libunwind_target = libdir.join("libunwind.a");
333 builder.copy_link(&libunwind_source, &libunwind_target, FileType::NativeLibrary);
334 libunwind_target
335}
336
337fn copy_third_party_objects(
339 builder: &Builder<'_>,
340 compiler: &Compiler,
341 target: TargetSelection,
342) -> Vec<(PathBuf, DependencyType)> {
343 let mut target_deps = vec![];
344
345 if builder.config.needs_sanitizer_runtime_built(target) && compiler.stage != 0 {
346 target_deps.extend(
349 copy_sanitizers(builder, compiler, target)
350 .into_iter()
351 .map(|d| (d, DependencyType::Target)),
352 );
353 }
354
355 if target == "x86_64-fortanix-unknown-sgx"
356 || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
357 && (target.contains("linux") || target.contains("fuchsia") || target.contains("aix"))
358 {
359 let libunwind_path =
360 copy_llvm_libunwind(builder, target, &builder.sysroot_target_libdir(*compiler, target));
361 target_deps.push((libunwind_path, DependencyType::Target));
362 }
363
364 target_deps
365}
366
367fn copy_self_contained_objects(
369 builder: &Builder<'_>,
370 compiler: &Compiler,
371 target: TargetSelection,
372) -> Vec<(PathBuf, DependencyType)> {
373 let libdir_self_contained =
374 builder.sysroot_target_libdir(*compiler, target).join("self-contained");
375 t!(fs::create_dir_all(&libdir_self_contained));
376 let mut target_deps = vec![];
377
378 if target.needs_crt_begin_end() {
386 let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
387 panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
388 });
389 if !target.starts_with("wasm32") {
390 for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
391 copy_and_stamp(
392 builder,
393 &libdir_self_contained,
394 &srcdir,
395 obj,
396 &mut target_deps,
397 DependencyType::TargetSelfContained,
398 );
399 }
400 let crt_path = builder.ensure(llvm::CrtBeginEnd { target });
401 for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
402 let src = crt_path.join(obj);
403 let target = libdir_self_contained.join(obj);
404 builder.copy_link(&src, &target, FileType::NativeLibrary);
405 target_deps.push((target, DependencyType::TargetSelfContained));
406 }
407 } else {
408 for &obj in &["libc.a", "crt1-command.o"] {
411 copy_and_stamp(
412 builder,
413 &libdir_self_contained,
414 &srcdir,
415 obj,
416 &mut target_deps,
417 DependencyType::TargetSelfContained,
418 );
419 }
420 }
421 if !target.starts_with("s390x") {
422 let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
423 target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
424 }
425 } else if target.contains("-wasi") {
426 let srcdir = builder.wasi_libdir(target).unwrap_or_else(|| {
427 panic!(
428 "Target {:?} does not have a \"wasi-root\" key in bootstrap.toml \
429 or `$WASI_SDK_PATH` set",
430 target.triple
431 )
432 });
433 for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
434 copy_and_stamp(
435 builder,
436 &libdir_self_contained,
437 &srcdir,
438 obj,
439 &mut target_deps,
440 DependencyType::TargetSelfContained,
441 );
442 }
443 } else if target.is_windows_gnu() {
444 for obj in ["crt2.o", "dllcrt2.o"].iter() {
445 let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
446 let dst = libdir_self_contained.join(obj);
447 builder.copy_link(&src, &dst, FileType::NativeLibrary);
448 target_deps.push((dst, DependencyType::TargetSelfContained));
449 }
450 }
451
452 target_deps
453}
454
455pub fn std_crates_for_run_make(run: &RunConfig<'_>) -> Vec<String> {
458 let mut crates = run.make_run_crates(builder::Alias::Library);
459
460 let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
469 if target_is_no_std {
470 crates.retain(|c| c == "core" || c == "alloc");
471 }
472 crates
473}
474
475fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
481 if builder.config.llvm_from_ci {
483 builder.config.maybe_download_ci_llvm();
485 let ci_llvm_compiler_rt = builder.config.ci_llvm_root().join("compiler-rt");
486 if ci_llvm_compiler_rt.exists() {
487 return ci_llvm_compiler_rt;
488 }
489 }
490
491 builder.require_submodule("src/llvm-project", {
493 Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
494 });
495 builder.src.join("src/llvm-project/compiler-rt")
496}
497
498pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, stage: u32, cargo: &mut Cargo) {
501 if target.contains("apple") && !builder.config.dry_run() {
519 let mut cmd = command(builder.rustc(cargo.compiler()));
523 cmd.arg("--target").arg(target.rustc_target_arg());
524 cmd.arg("--print=deployment-target");
525 let output = cmd.run_capture_stdout(builder).stdout();
526
527 let (env_var, value) = output.split_once('=').unwrap();
528 cargo.env(env_var.trim(), value.trim());
531
532 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
542 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
543 }
544 }
545
546 if let Some(path) = builder.config.profiler_path(target) {
548 cargo.env("LLVM_PROFILER_RT_LIB", path);
549 } else if builder.config.profiler_enabled(target) {
550 let compiler_rt = compiler_rt_for_profiler(builder);
551 cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
555 }
556
557 let compiler_builtins_c_feature = if builder.config.optimized_compiler_builtins(target) {
571 builder.require_submodule(
579 "src/llvm-project",
580 Some(
581 "The `build.optimized-compiler-builtins` config option \
582 requires `compiler-rt` sources from LLVM.",
583 ),
584 );
585 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
586 assert!(compiler_builtins_root.exists());
587 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
590 " compiler-builtins-c"
591 } else {
592 ""
593 };
594
595 if !builder.unstable_features() {
598 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
599 }
600
601 let mut features = String::new();
602
603 if builder.no_std(target) == Some(true) {
604 features += " compiler-builtins-mem";
605 if !target.starts_with("bpf") {
606 features.push_str(compiler_builtins_c_feature);
607 }
608
609 cargo
611 .args(["-p", "alloc"])
612 .arg("--manifest-path")
613 .arg(builder.src.join("library/alloc/Cargo.toml"))
614 .arg("--features")
615 .arg(features);
616 } else {
617 features += &builder.std_features(target);
618 features.push_str(compiler_builtins_c_feature);
619
620 cargo
621 .arg("--features")
622 .arg(features)
623 .arg("--manifest-path")
624 .arg(builder.src.join("library/sysroot/Cargo.toml"));
625
626 if target.contains("musl")
629 && let Some(p) = builder.musl_libdir(target)
630 {
631 let root = format!("native={}", p.to_str().unwrap());
632 cargo.rustflag("-L").rustflag(&root);
633 }
634
635 if target.contains("-wasi")
636 && let Some(dir) = builder.wasi_libdir(target)
637 {
638 let root = format!("native={}", dir.to_str().unwrap());
639 cargo.rustflag("-L").rustflag(&root);
640 }
641 }
642
643 if stage >= 1 {
652 cargo.rustflag("-Cembed-bitcode=yes");
653 }
654 if builder.config.rust_lto == RustcLto::Off {
655 cargo.rustflag("-Clto=off");
656 }
657
658 if target.contains("riscv") {
665 cargo.rustflag("-Cforce-unwind-tables=yes");
666 }
667
668 cargo.rustflag("-Zunstable-options");
671 cargo.rustflag("-Cforce-frame-pointers=non-leaf");
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)]
682pub struct 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 pub 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)]
969pub struct Rustc {
970 pub target: TargetSelection,
972 pub build_compiler: Compiler,
974 crates: Vec<String>,
980}
981
982impl Rustc {
983 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
984 Self { target, build_compiler, crates: Default::default() }
985 }
986}
987
988impl Step for Rustc {
989 type Output = u32;
997 const ONLY_HOSTS: bool = true;
998 const DEFAULT: bool = false;
999
1000 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1001 let mut crates = run.builder.in_tree_crates("rustc-main", None);
1002 for (i, krate) in crates.iter().enumerate() {
1003 if krate.name == "rustc-main" {
1006 crates.swap_remove(i);
1007 break;
1008 }
1009 }
1010 run.crates(crates)
1011 }
1012
1013 fn make_run(run: RunConfig<'_>) {
1014 if run.builder.paths == vec![PathBuf::from("compiler")] {
1017 return;
1018 }
1019
1020 let crates = run.cargo_crates_in_set();
1021 run.builder.ensure(Rustc {
1022 build_compiler: run
1023 .builder
1024 .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1025 target: run.target,
1026 crates,
1027 });
1028 }
1029
1030 #[cfg_attr(
1036 feature = "tracing",
1037 instrument(
1038 level = "debug",
1039 name = "Rustc::run",
1040 skip_all,
1041 fields(previous_compiler = ?self.build_compiler, target = ?self.target),
1042 ),
1043 )]
1044 fn run(self, builder: &Builder<'_>) -> u32 {
1045 let build_compiler = self.build_compiler;
1046 let target = self.target;
1047
1048 if builder.download_rustc() && build_compiler.stage != 0 {
1051 trace!(stage = build_compiler.stage, "`download_rustc` requested");
1052
1053 let sysroot =
1054 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
1055 cp_rustc_component_to_ci_sysroot(
1056 builder,
1057 &sysroot,
1058 builder.config.ci_rustc_dev_contents(),
1059 );
1060 return build_compiler.stage;
1061 }
1062
1063 builder.std(build_compiler, target);
1066
1067 if builder.config.keep_stage.contains(&build_compiler.stage) {
1068 trace!(stage = build_compiler.stage, "`keep-stage` requested");
1069
1070 builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1071 builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1072 builder.ensure(RustcLink::from_rustc(self, build_compiler));
1073
1074 return build_compiler.stage;
1075 }
1076
1077 let compiler_to_use =
1078 builder.compiler_for(build_compiler.stage, build_compiler.host, target);
1079 if compiler_to_use != build_compiler {
1080 builder.ensure(Rustc::new(compiler_to_use, target));
1081 let msg = if compiler_to_use.host == target {
1082 format!(
1083 "Uplifting rustc (stage{} -> stage{})",
1084 compiler_to_use.stage,
1085 build_compiler.stage + 1
1086 )
1087 } else {
1088 format!(
1089 "Uplifting rustc (stage{}:{} -> stage{}:{})",
1090 compiler_to_use.stage,
1091 compiler_to_use.host,
1092 build_compiler.stage + 1,
1093 target
1094 )
1095 };
1096 builder.info(&msg);
1097 builder.ensure(RustcLink::from_rustc(self, compiler_to_use));
1098 return compiler_to_use.stage;
1099 }
1100
1101 builder.std(
1107 builder.compiler(self.build_compiler.stage, builder.config.host_target),
1108 builder.config.host_target,
1109 );
1110
1111 let mut cargo = builder::Cargo::new(
1112 builder,
1113 build_compiler,
1114 Mode::Rustc,
1115 SourceType::InTree,
1116 target,
1117 Kind::Build,
1118 );
1119
1120 rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
1121
1122 for krate in &*self.crates {
1126 cargo.arg("-p").arg(krate);
1127 }
1128
1129 if builder.build.config.enable_bolt_settings && build_compiler.stage == 1 {
1130 cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1132 }
1133
1134 let _guard = builder.msg_sysroot_tool(
1135 Kind::Build,
1136 build_compiler.stage,
1137 format_args!("compiler artifacts{}", crate_description(&self.crates)),
1138 build_compiler.host,
1139 target,
1140 );
1141 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
1142 run_cargo(
1143 builder,
1144 cargo,
1145 vec![],
1146 &stamp,
1147 vec![],
1148 false,
1149 true, );
1151
1152 let target_root_dir = stamp.path().parent().unwrap();
1153 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1159 && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1160 {
1161 let rustc_driver = target_root_dir.join("librustc_driver.so");
1162 strip_debug(builder, target, &rustc_driver);
1163 }
1164
1165 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1166 strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1169 }
1170
1171 builder.ensure(RustcLink::from_rustc(
1172 self,
1173 builder.compiler(build_compiler.stage, builder.config.host_target),
1174 ));
1175
1176 build_compiler.stage
1177 }
1178
1179 fn metadata(&self) -> Option<StepMetadata> {
1180 Some(StepMetadata::build("rustc", self.target).built_by(self.build_compiler))
1181 }
1182}
1183
1184pub fn rustc_cargo(
1185 builder: &Builder<'_>,
1186 cargo: &mut Cargo,
1187 target: TargetSelection,
1188 build_compiler: &Compiler,
1189 crates: &[String],
1190) {
1191 cargo
1192 .arg("--features")
1193 .arg(builder.rustc_features(builder.kind, target, crates))
1194 .arg("--manifest-path")
1195 .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1196
1197 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1198
1199 cargo.rustflag("-Zon-broken-pipe=kill");
1213
1214 if builder.config.llvm_enzyme {
1217 let arch = builder.build.host_target;
1218 let enzyme_dir = builder.build.out.join(arch).join("enzyme").join("lib");
1219 cargo.rustflag("-L").rustflag(enzyme_dir.to_str().expect("Invalid path"));
1220
1221 if let Some(llvm_config) = builder.llvm_config(builder.config.host_target) {
1222 let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
1223 cargo.rustflag("-l").rustflag(&format!("Enzyme-{llvm_version_major}"));
1224 }
1225 }
1226
1227 if builder.build.config.lld_mode.is_used() {
1232 cargo.rustflag("-Zdefault-visibility=protected");
1233 }
1234
1235 if is_lto_stage(build_compiler) {
1236 match builder.config.rust_lto {
1237 RustcLto::Thin | RustcLto::Fat => {
1238 cargo.rustflag("-Zdylib-lto");
1241 let lto_type = match builder.config.rust_lto {
1245 RustcLto::Thin => "thin",
1246 RustcLto::Fat => "fat",
1247 _ => unreachable!(),
1248 };
1249 cargo.rustflag(&format!("-Clto={lto_type}"));
1250 cargo.rustflag("-Cembed-bitcode=yes");
1251 }
1252 RustcLto::ThinLocal => { }
1253 RustcLto::Off => {
1254 cargo.rustflag("-Clto=off");
1255 }
1256 }
1257 } else if builder.config.rust_lto == RustcLto::Off {
1258 cargo.rustflag("-Clto=off");
1259 }
1260
1261 if builder.config.lld_mode.is_used() && !build_compiler.host.is_msvc() {
1269 cargo.rustflag("-Clink-args=-Wl,--icf=all");
1270 }
1271
1272 if builder.config.rust_profile_use.is_some() && builder.config.rust_profile_generate.is_some() {
1273 panic!("Cannot use and generate PGO profiles at the same time");
1274 }
1275 let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
1276 if build_compiler.stage == 1 {
1277 cargo.rustflag(&format!("-Cprofile-generate={path}"));
1278 cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
1281 true
1282 } else {
1283 false
1284 }
1285 } else if let Some(path) = &builder.config.rust_profile_use {
1286 if build_compiler.stage == 1 {
1287 cargo.rustflag(&format!("-Cprofile-use={path}"));
1288 if builder.is_verbose() {
1289 cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
1290 }
1291 true
1292 } else {
1293 false
1294 }
1295 } else {
1296 false
1297 };
1298 if is_collecting {
1299 cargo.rustflag(&format!(
1301 "-Cllvm-args=-static-func-strip-dirname-prefix={}",
1302 builder.config.src.components().count()
1303 ));
1304 }
1305
1306 if let Some(ref ccache) = builder.config.ccache
1311 && build_compiler.stage == 0
1312 && !builder.config.incremental
1313 {
1314 cargo.env("RUSTC_WRAPPER", ccache);
1315 }
1316
1317 rustc_cargo_env(builder, cargo, target);
1318}
1319
1320pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1321 cargo
1324 .env("CFG_RELEASE", builder.rust_release())
1325 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1326 .env("CFG_VERSION", builder.rust_version());
1327
1328 if builder.config.omit_git_hash {
1332 cargo.env("CFG_OMIT_GIT_HASH", "1");
1333 }
1334
1335 if let Some(backend) = builder.config.default_codegen_backend(target) {
1336 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", backend.name());
1337 }
1338
1339 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1340 let target_config = builder.config.target_config.get(&target);
1341
1342 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1343
1344 if let Some(ref ver_date) = builder.rust_info().commit_date() {
1345 cargo.env("CFG_VER_DATE", ver_date);
1346 }
1347 if let Some(ref ver_hash) = builder.rust_info().sha() {
1348 cargo.env("CFG_VER_HASH", ver_hash);
1349 }
1350 if !builder.unstable_features() {
1351 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1352 }
1353
1354 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1357 cargo.env("CFG_DEFAULT_LINKER", s);
1358 } else if let Some(ref s) = builder.config.rustc_default_linker {
1359 cargo.env("CFG_DEFAULT_LINKER", s);
1360 }
1361
1362 if builder.config.lld_enabled {
1364 cargo.env("CFG_USE_SELF_CONTAINED_LINKER", "1");
1365 }
1366
1367 if builder.config.rust_verify_llvm_ir {
1368 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1369 }
1370
1371 if builder.config.llvm_enzyme {
1372 cargo.rustflag("--cfg=llvm_enzyme");
1373 }
1374
1375 if builder.config.llvm_enabled(target) {
1387 let building_llvm_is_expensive =
1388 crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false)
1389 .should_build();
1390
1391 let skip_llvm = (builder.kind == Kind::Check) && building_llvm_is_expensive;
1392 if !skip_llvm {
1393 rustc_llvm_env(builder, cargo, target)
1394 }
1395 }
1396
1397 if builder.config.jemalloc(target)
1400 && target.starts_with("aarch64")
1401 && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none()
1402 {
1403 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1404 }
1405}
1406
1407fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1413 if builder.config.is_rust_llvm(target) {
1414 cargo.env("LLVM_RUSTLLVM", "1");
1415 }
1416 if builder.config.llvm_enzyme {
1417 cargo.env("LLVM_ENZYME", "1");
1418 }
1419 let llvm::LlvmResult { llvm_config, .. } = builder.ensure(llvm::Llvm { target });
1420 cargo.env("LLVM_CONFIG", &llvm_config);
1421
1422 let mut llvm_linker_flags = String::new();
1432 if builder.config.llvm_profile_generate
1433 && target.is_msvc()
1434 && let Some(ref clang_cl_path) = builder.config.llvm_clang_cl
1435 {
1436 let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1438 llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
1439 }
1440
1441 if let Some(ref s) = builder.config.llvm_ldflags {
1443 if !llvm_linker_flags.is_empty() {
1444 llvm_linker_flags.push(' ');
1445 }
1446 llvm_linker_flags.push_str(s);
1447 }
1448
1449 if !llvm_linker_flags.is_empty() {
1451 cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
1452 }
1453
1454 if builder.config.llvm_static_stdcpp
1457 && !target.contains("freebsd")
1458 && !target.is_msvc()
1459 && !target.contains("apple")
1460 && !target.contains("solaris")
1461 {
1462 let libstdcxx_name =
1463 if target.contains("windows-gnullvm") { "libc++.a" } else { "libstdc++.a" };
1464 let file = compiler_file(
1465 builder,
1466 &builder.cxx(target).unwrap(),
1467 target,
1468 CLang::Cxx,
1469 libstdcxx_name,
1470 );
1471 cargo.env("LLVM_STATIC_STDCPP", file);
1472 }
1473 if builder.llvm_link_shared() {
1474 cargo.env("LLVM_LINK_SHARED", "1");
1475 }
1476 if builder.config.llvm_use_libcxx {
1477 cargo.env("LLVM_USE_LIBCXX", "1");
1478 }
1479 if builder.config.llvm_assertions {
1480 cargo.env("LLVM_ASSERTIONS", "1");
1481 }
1482}
1483
1484#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1490struct RustcLink {
1491 pub compiler: Compiler,
1493 pub previous_stage_compiler: Compiler,
1495 pub target: TargetSelection,
1496 crates: Vec<String>,
1498}
1499
1500impl RustcLink {
1501 fn from_rustc(rustc: Rustc, host_compiler: Compiler) -> Self {
1502 Self {
1503 compiler: host_compiler,
1504 previous_stage_compiler: rustc.build_compiler,
1505 target: rustc.target,
1506 crates: rustc.crates,
1507 }
1508 }
1509}
1510
1511impl Step for RustcLink {
1512 type Output = ();
1513
1514 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1515 run.never()
1516 }
1517
1518 #[cfg_attr(
1520 feature = "tracing",
1521 instrument(
1522 level = "trace",
1523 name = "RustcLink::run",
1524 skip_all,
1525 fields(
1526 compiler = ?self.compiler,
1527 previous_stage_compiler = ?self.previous_stage_compiler,
1528 target = ?self.target,
1529 ),
1530 ),
1531 )]
1532 fn run(self, builder: &Builder<'_>) {
1533 let compiler = self.compiler;
1534 let previous_stage_compiler = self.previous_stage_compiler;
1535 let target = self.target;
1536 add_to_sysroot(
1537 builder,
1538 &builder.sysroot_target_libdir(previous_stage_compiler, target),
1539 &builder.sysroot_target_libdir(previous_stage_compiler, compiler.host),
1540 &build_stamp::librustc_stamp(builder, compiler, target),
1541 );
1542 }
1543}
1544
1545#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1546pub struct CodegenBackend {
1547 pub target: TargetSelection,
1548 pub compiler: Compiler,
1549 pub backend: CodegenBackendKind,
1550}
1551
1552fn needs_codegen_config(run: &RunConfig<'_>) -> bool {
1553 let mut needs_codegen_cfg = false;
1554 for path_set in &run.paths {
1555 needs_codegen_cfg = match path_set {
1556 PathSet::Set(set) => set.iter().any(|p| is_codegen_cfg_needed(p, run)),
1557 PathSet::Suite(suite) => is_codegen_cfg_needed(suite, run),
1558 }
1559 }
1560 needs_codegen_cfg
1561}
1562
1563pub(crate) const CODEGEN_BACKEND_PREFIX: &str = "rustc_codegen_";
1564
1565fn is_codegen_cfg_needed(path: &TaskPath, run: &RunConfig<'_>) -> bool {
1566 let path = path.path.to_str().unwrap();
1567
1568 let is_explicitly_called = |p| -> bool { run.builder.paths.contains(p) };
1569 let should_enforce = run.builder.kind == Kind::Dist || run.builder.kind == Kind::Install;
1570
1571 if path.contains(CODEGEN_BACKEND_PREFIX) {
1572 let mut needs_codegen_backend_config = true;
1573 for backend in run.builder.config.codegen_backends(run.target) {
1574 if path.ends_with(&(CODEGEN_BACKEND_PREFIX.to_owned() + backend.name())) {
1575 needs_codegen_backend_config = false;
1576 }
1577 }
1578 if (is_explicitly_called(&PathBuf::from(path)) || should_enforce)
1579 && needs_codegen_backend_config
1580 {
1581 run.builder.info(
1582 "WARNING: no codegen-backends config matched the requested path to build a codegen backend. \
1583 HELP: add backend to codegen-backends in bootstrap.toml.",
1584 );
1585 return true;
1586 }
1587 }
1588
1589 false
1590}
1591
1592impl Step for CodegenBackend {
1593 type Output = ();
1594 const ONLY_HOSTS: bool = true;
1595 const DEFAULT: bool = true;
1597
1598 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1599 run.paths(&["compiler/rustc_codegen_cranelift", "compiler/rustc_codegen_gcc"])
1600 }
1601
1602 fn make_run(run: RunConfig<'_>) {
1603 if needs_codegen_config(&run) {
1604 return;
1605 }
1606
1607 for backend in run.builder.config.codegen_backends(run.target) {
1608 if backend.is_llvm() {
1609 continue; }
1611
1612 run.builder.ensure(CodegenBackend {
1613 target: run.target,
1614 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
1615 backend: backend.clone(),
1616 });
1617 }
1618 }
1619
1620 #[cfg_attr(
1621 feature = "tracing",
1622 instrument(
1623 level = "debug",
1624 name = "CodegenBackend::run",
1625 skip_all,
1626 fields(
1627 compiler = ?self.compiler,
1628 target = ?self.target,
1629 backend = ?self.target,
1630 ),
1631 ),
1632 )]
1633 fn run(self, builder: &Builder<'_>) {
1634 let compiler = self.compiler;
1635 let target = self.target;
1636 let backend = self.backend;
1637
1638 builder.ensure(Rustc::new(compiler, target));
1639
1640 if builder.config.keep_stage.contains(&compiler.stage) {
1641 trace!("`keep-stage` requested");
1642 builder.info(
1643 "WARNING: Using a potentially old codegen backend. \
1644 This may not behave well.",
1645 );
1646 return;
1649 }
1650
1651 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
1652 if compiler_to_use != compiler {
1653 builder.ensure(CodegenBackend { compiler: compiler_to_use, target, backend });
1654 return;
1655 }
1656
1657 let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
1658
1659 let mut cargo = builder::Cargo::new(
1660 builder,
1661 compiler,
1662 Mode::Codegen,
1663 SourceType::InTree,
1664 target,
1665 Kind::Build,
1666 );
1667 cargo
1668 .arg("--manifest-path")
1669 .arg(builder.src.join(format!("compiler/{}/Cargo.toml", backend.crate_name())));
1670 rustc_cargo_env(builder, &mut cargo, target);
1671
1672 if backend.is_gcc() {
1676 let gcc = builder.ensure(Gcc { target });
1677 add_cg_gcc_cargo_flags(&mut cargo, &gcc);
1678 }
1679
1680 let tmp_stamp = BuildStamp::new(&out_dir).with_prefix("tmp");
1681
1682 let _guard =
1683 builder.msg_build(compiler, format_args!("codegen backend {}", backend.name()), target);
1684 let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false, false);
1685 if builder.config.dry_run() {
1686 return;
1687 }
1688 let mut files = files.into_iter().filter(|f| {
1689 let filename = f.file_name().unwrap().to_str().unwrap();
1690 is_dylib(f) && filename.contains("rustc_codegen_")
1691 });
1692 let codegen_backend = match files.next() {
1693 Some(f) => f,
1694 None => panic!("no dylibs built for codegen backend?"),
1695 };
1696 if let Some(f) = files.next() {
1697 panic!(
1698 "codegen backend built two dylibs:\n{}\n{}",
1699 codegen_backend.display(),
1700 f.display()
1701 );
1702 }
1703 let stamp = build_stamp::codegen_backend_stamp(builder, compiler, target, &backend);
1704 let codegen_backend = codegen_backend.to_str().unwrap();
1705 t!(stamp.add_stamp(codegen_backend).write());
1706 }
1707}
1708
1709fn copy_codegen_backends_to_sysroot(
1716 builder: &Builder<'_>,
1717 compiler: Compiler,
1718 target_compiler: Compiler,
1719) {
1720 let target = target_compiler.host;
1721
1722 let dst = builder.sysroot_codegen_backends(target_compiler);
1731 t!(fs::create_dir_all(&dst), dst);
1732
1733 if builder.config.dry_run() {
1734 return;
1735 }
1736
1737 for backend in builder.config.codegen_backends(target) {
1738 if backend.is_llvm() {
1739 continue; }
1741
1742 let stamp = build_stamp::codegen_backend_stamp(builder, compiler, target, backend);
1743 if stamp.path().exists() {
1744 let dylib = t!(fs::read_to_string(stamp.path()));
1745 let file = Path::new(&dylib);
1746 let filename = file.file_name().unwrap().to_str().unwrap();
1747 let target_filename = {
1750 let dash = filename.find('-').unwrap();
1751 let dot = filename.find('.').unwrap();
1752 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1753 };
1754 builder.copy_link(file, &dst.join(target_filename), FileType::NativeLibrary);
1755 }
1756 }
1757}
1758
1759pub fn compiler_file(
1760 builder: &Builder<'_>,
1761 compiler: &Path,
1762 target: TargetSelection,
1763 c: CLang,
1764 file: &str,
1765) -> PathBuf {
1766 if builder.config.dry_run() {
1767 return PathBuf::new();
1768 }
1769 let mut cmd = command(compiler);
1770 cmd.args(builder.cc_handled_clags(target, c));
1771 cmd.args(builder.cc_unhandled_cflags(target, GitRepo::Rustc, c));
1772 cmd.arg(format!("-print-file-name={file}"));
1773 let out = cmd.run_capture_stdout(builder).stdout();
1774 PathBuf::from(out.trim())
1775}
1776
1777#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1778pub struct Sysroot {
1779 pub compiler: Compiler,
1780 force_recompile: bool,
1782}
1783
1784impl Sysroot {
1785 pub(crate) fn new(compiler: Compiler) -> Self {
1786 Sysroot { compiler, force_recompile: false }
1787 }
1788}
1789
1790impl Step for Sysroot {
1791 type Output = PathBuf;
1792
1793 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1794 run.never()
1795 }
1796
1797 #[cfg_attr(
1801 feature = "tracing",
1802 instrument(
1803 level = "debug",
1804 name = "Sysroot::run",
1805 skip_all,
1806 fields(compiler = ?self.compiler),
1807 ),
1808 )]
1809 fn run(self, builder: &Builder<'_>) -> PathBuf {
1810 let compiler = self.compiler;
1811 let host_dir = builder.out.join(compiler.host);
1812
1813 let sysroot_dir = |stage| {
1814 if stage == 0 {
1815 host_dir.join("stage0-sysroot")
1816 } else if self.force_recompile && stage == compiler.stage {
1817 host_dir.join(format!("stage{stage}-test-sysroot"))
1818 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1819 host_dir.join("ci-rustc-sysroot")
1820 } else {
1821 host_dir.join(format!("stage{stage}"))
1822 }
1823 };
1824 let sysroot = sysroot_dir(compiler.stage);
1825 trace!(stage = ?compiler.stage, ?sysroot);
1826
1827 builder
1828 .verbose(|| println!("Removing sysroot {} to avoid caching bugs", sysroot.display()));
1829 let _ = fs::remove_dir_all(&sysroot);
1830 t!(fs::create_dir_all(&sysroot));
1831
1832 if compiler.stage == 0 {
1839 dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1840 }
1841
1842 if builder.download_rustc() && compiler.stage != 0 {
1844 assert_eq!(
1845 builder.config.host_target, compiler.host,
1846 "Cross-compiling is not yet supported with `download-rustc`",
1847 );
1848
1849 for stage in 0..=2 {
1851 if stage != compiler.stage {
1852 let dir = sysroot_dir(stage);
1853 if !dir.ends_with("ci-rustc-sysroot") {
1854 let _ = fs::remove_dir_all(dir);
1855 }
1856 }
1857 }
1858
1859 let mut filtered_files = Vec::new();
1869 let mut add_filtered_files = |suffix, contents| {
1870 for path in contents {
1871 let path = Path::new(&path);
1872 if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
1873 filtered_files.push(path.file_name().unwrap().to_owned());
1874 }
1875 }
1876 };
1877 let suffix = format!("lib/rustlib/{}/lib", compiler.host);
1878 add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
1879 add_filtered_files("lib", builder.config.ci_rust_std_contents());
1882
1883 let filtered_extensions = [
1884 OsStr::new("rmeta"),
1885 OsStr::new("rlib"),
1886 OsStr::new(std::env::consts::DLL_EXTENSION),
1888 ];
1889 let ci_rustc_dir = builder.config.ci_rustc_dir();
1890 builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
1891 if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
1892 return true;
1893 }
1894 if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
1895 return true;
1896 }
1897 if !filtered_files.iter().all(|f| f != path.file_name().unwrap()) {
1898 builder.verbose_than(1, || println!("ignoring {}", path.display()));
1899 false
1900 } else {
1901 true
1902 }
1903 });
1904 }
1905
1906 if compiler.stage != 0 {
1912 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
1913 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
1914 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
1915 if let Err(e) =
1916 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust)
1917 {
1918 eprintln!(
1919 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
1920 sysroot_lib_rustlib_src_rust.display(),
1921 builder.src.display(),
1922 e,
1923 );
1924 if builder.config.rust_remap_debuginfo {
1925 eprintln!(
1926 "ERROR: some `tests/ui` tests will fail when lacking `{}`",
1927 sysroot_lib_rustlib_src_rust.display(),
1928 );
1929 }
1930 build_helper::exit!(1);
1931 }
1932 }
1933
1934 if !builder.download_rustc() {
1936 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
1937 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
1938 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
1939 if let Err(e) =
1940 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
1941 {
1942 eprintln!(
1943 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
1944 sysroot_lib_rustlib_rustcsrc_rust.display(),
1945 builder.src.display(),
1946 e,
1947 );
1948 build_helper::exit!(1);
1949 }
1950 }
1951
1952 sysroot
1953 }
1954}
1955
1956#[derive(Debug, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
1957pub struct Assemble {
1958 pub target_compiler: Compiler,
1963}
1964
1965impl Step for Assemble {
1966 type Output = Compiler;
1967 const ONLY_HOSTS: bool = true;
1968
1969 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1970 run.path("compiler/rustc").path("compiler")
1971 }
1972
1973 fn make_run(run: RunConfig<'_>) {
1974 run.builder.ensure(Assemble {
1975 target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
1976 });
1977 }
1978
1979 #[cfg_attr(
1985 feature = "tracing",
1986 instrument(
1987 level = "debug",
1988 name = "Assemble::run",
1989 skip_all,
1990 fields(target_compiler = ?self.target_compiler),
1991 ),
1992 )]
1993 fn run(self, builder: &Builder<'_>) -> Compiler {
1994 let target_compiler = self.target_compiler;
1995
1996 if target_compiler.stage == 0 {
1997 trace!("stage 0 build compiler is always available, simply returning");
1998 assert_eq!(
1999 builder.config.host_target, target_compiler.host,
2000 "Cannot obtain compiler for non-native build triple at stage 0"
2001 );
2002 return target_compiler;
2004 }
2005
2006 let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2009 let libdir_bin = libdir.parent().unwrap().join("bin");
2010 t!(fs::create_dir_all(&libdir_bin));
2011
2012 if builder.config.llvm_enabled(target_compiler.host) {
2013 trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
2014
2015 let llvm::LlvmResult { llvm_config, .. } =
2016 builder.ensure(llvm::Llvm { target: target_compiler.host });
2017 if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
2018 trace!("LLVM tools enabled");
2019
2020 let llvm_bin_dir =
2021 command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
2022 let llvm_bin_dir = Path::new(llvm_bin_dir.trim());
2023
2024 #[cfg(feature = "tracing")]
2031 let _llvm_tools_span =
2032 span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
2033 .entered();
2034 for tool in LLVM_TOOLS {
2035 trace!("installing `{tool}`");
2036 let tool_exe = exe(tool, target_compiler.host);
2037 let src_path = llvm_bin_dir.join(&tool_exe);
2038
2039 if !src_path.exists() && builder.config.llvm_from_ci {
2041 eprintln!("{} does not exist; skipping copy", src_path.display());
2042 continue;
2043 }
2044
2045 builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2052 }
2053 }
2054 }
2055
2056 let maybe_install_llvm_bitcode_linker = || {
2057 if builder.config.llvm_bitcode_linker_enabled {
2058 trace!("llvm-bitcode-linker enabled, installing");
2059 let llvm_bitcode_linker = builder.ensure(
2060 crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler(
2061 builder,
2062 target_compiler,
2063 ),
2064 );
2065
2066 let bindir_self_contained = builder
2068 .sysroot(target_compiler)
2069 .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host));
2070 let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2071
2072 t!(fs::create_dir_all(&bindir_self_contained));
2073 builder.copy_link(
2074 &llvm_bitcode_linker.tool_path,
2075 &bindir_self_contained.join(tool_exe),
2076 FileType::Executable,
2077 );
2078 }
2079 };
2080
2081 if builder.download_rustc() {
2083 trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2084
2085 builder.std(target_compiler, target_compiler.host);
2086 let sysroot =
2087 builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2088 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2091 if target_compiler.stage == builder.top_stage {
2093 builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage));
2094 }
2095
2096 maybe_install_llvm_bitcode_linker();
2099
2100 return target_compiler;
2101 }
2102
2103 debug!(
2117 "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2118 target_compiler.stage - 1,
2119 builder.config.host_target,
2120 );
2121 let mut build_compiler =
2122 builder.compiler(target_compiler.stage - 1, builder.config.host_target);
2123
2124 if builder.config.llvm_enzyme && !builder.config.dry_run() {
2126 debug!("`llvm_enzyme` requested");
2127 let enzyme_install = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2128 if let Some(llvm_config) = builder.llvm_config(builder.config.host_target) {
2129 let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
2130 let lib_ext = std::env::consts::DLL_EXTENSION;
2131 let libenzyme = format!("libEnzyme-{llvm_version_major}");
2132 let src_lib =
2133 enzyme_install.join("build/Enzyme").join(&libenzyme).with_extension(lib_ext);
2134 let libdir = builder.sysroot_target_libdir(build_compiler, build_compiler.host);
2135 let target_libdir =
2136 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2137 let dst_lib = libdir.join(&libenzyme).with_extension(lib_ext);
2138 let target_dst_lib = target_libdir.join(&libenzyme).with_extension(lib_ext);
2139 builder.copy_link(&src_lib, &dst_lib, FileType::NativeLibrary);
2140 builder.copy_link(&src_lib, &target_dst_lib, FileType::NativeLibrary);
2141 }
2142 }
2143
2144 debug!(
2150 ?build_compiler,
2151 "target_compiler.host" = ?target_compiler.host,
2152 "building compiler libraries to link to"
2153 );
2154 let actual_stage = builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2155 debug!(
2158 "(old) build_compiler.stage" = build_compiler.stage,
2159 "(adjusted) build_compiler.stage" = actual_stage,
2160 "temporarily adjusting `build_compiler.stage` to account for uplifted libraries"
2161 );
2162 build_compiler.stage = actual_stage;
2163
2164 #[cfg(feature = "tracing")]
2165 let _codegen_backend_span =
2166 span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2167 for backend in builder.config.codegen_backends(target_compiler.host) {
2168 if backend.is_llvm() {
2169 debug!("llvm codegen backend is already built as part of rustc");
2170 continue; }
2172
2173 if builder.kind == Kind::Check && builder.top_stage == 1 {
2190 continue;
2191 }
2192 builder.ensure(CodegenBackend {
2193 compiler: build_compiler,
2194 target: target_compiler.host,
2195 backend: backend.clone(),
2196 });
2197 }
2198 #[cfg(feature = "tracing")]
2199 drop(_codegen_backend_span);
2200
2201 let stage = target_compiler.stage;
2202 let host = target_compiler.host;
2203 let (host_info, dir_name) = if build_compiler.host == host {
2204 ("".into(), "host".into())
2205 } else {
2206 (format!(" ({host})"), host.to_string())
2207 };
2208 let msg = format!(
2213 "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2214 );
2215 builder.info(&msg);
2216
2217 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2219 let proc_macros = builder
2220 .read_stamp_file(&stamp)
2221 .into_iter()
2222 .filter_map(|(path, dependency_type)| {
2223 if dependency_type == DependencyType::Host {
2224 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2225 } else {
2226 None
2227 }
2228 })
2229 .collect::<HashSet<_>>();
2230
2231 let sysroot = builder.sysroot(target_compiler);
2232 let rustc_libdir = builder.rustc_libdir(target_compiler);
2233 t!(fs::create_dir_all(&rustc_libdir));
2234 let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2235 for f in builder.read_dir(&src_libdir) {
2236 let filename = f.file_name().into_string().unwrap();
2237
2238 let is_proc_macro = proc_macros.contains(&filename);
2239 let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2240
2241 let can_be_rustc_dynamic_dep = if builder
2245 .link_std_into_rustc_driver(target_compiler.host)
2246 && !target_compiler.host.is_windows()
2247 {
2248 let is_std = filename.starts_with("std-") || filename.starts_with("libstd-");
2249 !is_std
2250 } else {
2251 true
2252 };
2253
2254 if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2255 builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2256 }
2257 }
2258
2259 debug!("copying codegen backends to sysroot");
2260 copy_codegen_backends_to_sysroot(builder, build_compiler, target_compiler);
2261
2262 if builder.config.lld_enabled {
2263 let lld_wrapper =
2264 builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler(
2265 builder,
2266 target_compiler,
2267 ));
2268 copy_lld_artifacts(builder, lld_wrapper, target_compiler);
2269 }
2270
2271 if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2272 debug!(
2273 "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2274 workaround faulty homebrew `strip`s"
2275 );
2276
2277 let src_exe = exe("llvm-objcopy", target_compiler.host);
2284 let dst_exe = exe("rust-objcopy", target_compiler.host);
2285 builder.copy_link(
2286 &libdir_bin.join(src_exe),
2287 &libdir_bin.join(dst_exe),
2288 FileType::Executable,
2289 );
2290 }
2291
2292 if builder.tool_enabled("wasm-component-ld") {
2295 let wasm_component = builder.ensure(
2296 crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler(
2297 builder,
2298 target_compiler,
2299 ),
2300 );
2301 builder.copy_link(
2302 &wasm_component.tool_path,
2303 &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2304 FileType::Executable,
2305 );
2306 }
2307
2308 maybe_install_llvm_bitcode_linker();
2309
2310 debug!(
2313 "target_compiler.host" = ?target_compiler.host,
2314 ?sysroot,
2315 "ensuring availability of `libLLVM.so` in compiler directory"
2316 );
2317 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2318 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2319
2320 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2322 let rustc = out_dir.join(exe("rustc-main", host));
2323 let bindir = sysroot.join("bin");
2324 t!(fs::create_dir_all(bindir));
2325 let compiler = builder.rustc(target_compiler);
2326 debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2327 builder.copy_link(&rustc, &compiler, FileType::Executable);
2328
2329 target_compiler
2330 }
2331}
2332
2333pub fn add_to_sysroot(
2338 builder: &Builder<'_>,
2339 sysroot_dst: &Path,
2340 sysroot_host_dst: &Path,
2341 stamp: &BuildStamp,
2342) {
2343 let self_contained_dst = &sysroot_dst.join("self-contained");
2344 t!(fs::create_dir_all(sysroot_dst));
2345 t!(fs::create_dir_all(sysroot_host_dst));
2346 t!(fs::create_dir_all(self_contained_dst));
2347 for (path, dependency_type) in builder.read_stamp_file(stamp) {
2348 let dst = match dependency_type {
2349 DependencyType::Host => sysroot_host_dst,
2350 DependencyType::Target => sysroot_dst,
2351 DependencyType::TargetSelfContained => self_contained_dst,
2352 };
2353 builder.copy_link(&path, &dst.join(path.file_name().unwrap()), FileType::Regular);
2354 }
2355}
2356
2357pub fn run_cargo(
2358 builder: &Builder<'_>,
2359 cargo: Cargo,
2360 tail_args: Vec<String>,
2361 stamp: &BuildStamp,
2362 additional_target_deps: Vec<(PathBuf, DependencyType)>,
2363 is_check: bool,
2364 rlib_only_metadata: bool,
2365) -> Vec<PathBuf> {
2366 let target_root_dir = stamp.path().parent().unwrap();
2368 let target_deps_dir = target_root_dir.join("deps");
2370 let host_root_dir = target_root_dir
2372 .parent()
2373 .unwrap() .parent()
2375 .unwrap() .join(target_root_dir.file_name().unwrap());
2377
2378 let mut deps = Vec::new();
2382 let mut toplevel = Vec::new();
2383 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2384 let (filenames, crate_types) = match msg {
2385 CargoMessage::CompilerArtifact {
2386 filenames,
2387 target: CargoTarget { crate_types },
2388 ..
2389 } => (filenames, crate_types),
2390 _ => return,
2391 };
2392 for filename in filenames {
2393 let mut keep = false;
2395 if filename.ends_with(".lib")
2396 || filename.ends_with(".a")
2397 || is_debug_info(&filename)
2398 || is_dylib(Path::new(&*filename))
2399 {
2400 keep = true;
2402 }
2403 if is_check && filename.ends_with(".rmeta") {
2404 keep = true;
2406 } else if rlib_only_metadata {
2407 if filename.contains("jemalloc_sys")
2408 || filename.contains("rustc_public_bridge")
2409 || filename.contains("rustc_public")
2410 {
2411 keep |= filename.ends_with(".rlib");
2414 } else {
2415 keep |= filename.ends_with(".rmeta");
2419 }
2420 } else {
2421 keep |= filename.ends_with(".rlib");
2423 }
2424
2425 if !keep {
2426 continue;
2427 }
2428
2429 let filename = Path::new(&*filename);
2430
2431 if filename.starts_with(&host_root_dir) {
2434 if crate_types.iter().any(|t| t == "proc-macro") {
2436 deps.push((filename.to_path_buf(), DependencyType::Host));
2437 }
2438 continue;
2439 }
2440
2441 if filename.starts_with(&target_deps_dir) {
2444 deps.push((filename.to_path_buf(), DependencyType::Target));
2445 continue;
2446 }
2447
2448 let expected_len = t!(filename.metadata()).len();
2459 let filename = filename.file_name().unwrap().to_str().unwrap();
2460 let mut parts = filename.splitn(2, '.');
2461 let file_stem = parts.next().unwrap().to_owned();
2462 let extension = parts.next().unwrap().to_owned();
2463
2464 toplevel.push((file_stem, extension, expected_len));
2465 }
2466 });
2467
2468 if !ok {
2469 crate::exit!(1);
2470 }
2471
2472 if builder.config.dry_run() {
2473 return Vec::new();
2474 }
2475
2476 let contents = target_deps_dir
2480 .read_dir()
2481 .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_deps_dir.display(), e))
2482 .map(|e| t!(e))
2483 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2484 .collect::<Vec<_>>();
2485 for (prefix, extension, expected_len) in toplevel {
2486 let candidates = contents.iter().filter(|&(_, filename, meta)| {
2487 meta.len() == expected_len
2488 && filename
2489 .strip_prefix(&prefix[..])
2490 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2491 .unwrap_or(false)
2492 });
2493 let max = candidates.max_by_key(|&(_, _, metadata)| {
2494 metadata.modified().expect("mtime should be available on all relevant OSes")
2495 });
2496 let path_to_add = match max {
2497 Some(triple) => triple.0.to_str().unwrap(),
2498 None => panic!("no output generated for {prefix:?} {extension:?}"),
2499 };
2500 if is_dylib(Path::new(path_to_add)) {
2501 let candidate = format!("{path_to_add}.lib");
2502 let candidate = PathBuf::from(candidate);
2503 if candidate.exists() {
2504 deps.push((candidate, DependencyType::Target));
2505 }
2506 }
2507 deps.push((path_to_add.into(), DependencyType::Target));
2508 }
2509
2510 deps.extend(additional_target_deps);
2511 deps.sort();
2512 let mut new_contents = Vec::new();
2513 for (dep, dependency_type) in deps.iter() {
2514 new_contents.extend(match *dependency_type {
2515 DependencyType::Host => b"h",
2516 DependencyType::Target => b"t",
2517 DependencyType::TargetSelfContained => b"s",
2518 });
2519 new_contents.extend(dep.to_str().unwrap().as_bytes());
2520 new_contents.extend(b"\0");
2521 }
2522 t!(fs::write(stamp.path(), &new_contents));
2523 deps.into_iter().map(|(d, _)| d).collect()
2524}
2525
2526pub fn stream_cargo(
2527 builder: &Builder<'_>,
2528 cargo: Cargo,
2529 tail_args: Vec<String>,
2530 cb: &mut dyn FnMut(CargoMessage<'_>),
2531) -> bool {
2532 let mut cmd = cargo.into_cmd();
2533
2534 #[cfg(feature = "tracing")]
2535 let _run_span = crate::trace_cmd!(cmd);
2536
2537 let mut message_format = if builder.config.json_output {
2540 String::from("json")
2541 } else {
2542 String::from("json-render-diagnostics")
2543 };
2544 if let Some(s) = &builder.config.rustc_error_format {
2545 message_format.push_str(",json-diagnostic-");
2546 message_format.push_str(s);
2547 }
2548 cmd.arg("--message-format").arg(message_format);
2549
2550 for arg in tail_args {
2551 cmd.arg(arg);
2552 }
2553
2554 builder.verbose(|| println!("running: {cmd:?}"));
2555
2556 let streaming_command = cmd.stream_capture_stdout(&builder.config.exec_ctx);
2557
2558 let Some(mut streaming_command) = streaming_command else {
2559 return true;
2560 };
2561
2562 let stdout = BufReader::new(streaming_command.stdout.take().unwrap());
2566 for line in stdout.lines() {
2567 let line = t!(line);
2568 match serde_json::from_str::<CargoMessage<'_>>(&line) {
2569 Ok(msg) => {
2570 if builder.config.json_output {
2571 println!("{line}");
2573 }
2574 cb(msg)
2575 }
2576 Err(_) => println!("{line}"),
2578 }
2579 }
2580
2581 let status = t!(streaming_command.wait(&builder.config.exec_ctx));
2583 if builder.is_verbose() && !status.success() {
2584 eprintln!(
2585 "command did not execute successfully: {cmd:?}\n\
2586 expected success, got: {status}"
2587 );
2588 }
2589
2590 status.success()
2591}
2592
2593#[derive(Deserialize)]
2594pub struct CargoTarget<'a> {
2595 crate_types: Vec<Cow<'a, str>>,
2596}
2597
2598#[derive(Deserialize)]
2599#[serde(tag = "reason", rename_all = "kebab-case")]
2600pub enum CargoMessage<'a> {
2601 CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2602 BuildScriptExecuted,
2603 BuildFinished,
2604}
2605
2606pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2607 if target != "x86_64-unknown-linux-gnu"
2611 || !builder.config.is_host_target(target)
2612 || !path.exists()
2613 {
2614 return;
2615 }
2616
2617 let previous_mtime = t!(t!(path.metadata()).modified());
2618 command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2619
2620 let file = t!(fs::File::open(path));
2621
2622 t!(file.set_modified(previous_mtime));
2635}
2636
2637pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2639 build_compiler.stage != 0
2640}