1use std::borrow::Cow;
10use std::collections::{BTreeMap, HashMap, HashSet};
11use std::ffi::OsStr;
12use std::io::BufReader;
13use std::io::prelude::*;
14use std::path::{Path, PathBuf};
15use std::time::SystemTime;
16use std::{env, fs, str};
17
18use serde_derive::Deserialize;
19#[cfg(feature = "tracing")]
20use tracing::span;
21
22use crate::core::backend::CodegenBackendKind;
23use crate::core::build_steps::gcc::{Gcc, GccOutput, GccTargetPair};
24use crate::core::build_steps::llvm::{LlvmFromCi, LlvmKind, prebuilt_llvm_output};
25use crate::core::build_steps::tool::{RustcPrivateCompilers, SourceType, copy_lld_artifacts};
26use crate::core::build_steps::{dist, llvm};
27use crate::core::builder::{
28 self, Builder, Cargo, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
29 apply_pgo, crate_description,
30};
31use crate::core::compiler::Compiler;
32use crate::core::config::toml::target::DefaultLinuxLinkerOverride;
33use crate::core::config::{
34 Allocator, CompilerBuiltins, DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection,
35};
36use crate::core::session::{CLang, DependencyType, FileType, Mode};
37use crate::utils::build_stamp;
38use crate::utils::build_stamp::BuildStamp;
39use crate::utils::exec::command;
40use crate::utils::helpers::{
41 self, exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date,
42};
43use crate::{debug, trace};
44
45#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub struct Std {
48 pub target: TargetSelection,
49 pub build_compiler: Compiler,
51 crates: Vec<String>,
55 force_recompile: bool,
58 extra_rust_args: &'static [&'static str],
59 is_for_mir_opt_tests: bool,
60}
61
62impl Std {
63 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
64 Self {
65 target,
66 build_compiler,
67 crates: Default::default(),
68 force_recompile: false,
69 extra_rust_args: &[],
70 is_for_mir_opt_tests: false,
71 }
72 }
73
74 pub fn force_recompile(mut self, force_recompile: bool) -> Self {
75 self.force_recompile = force_recompile;
76 self
77 }
78
79 #[expect(clippy::wrong_self_convention)]
80 pub fn is_for_mir_opt_tests(mut self, is_for_mir_opt_tests: bool) -> Self {
81 self.is_for_mir_opt_tests = is_for_mir_opt_tests;
82 self
83 }
84
85 pub fn extra_rust_args(mut self, extra_rust_args: &'static [&'static str]) -> Self {
86 self.extra_rust_args = extra_rust_args;
87 self
88 }
89
90 fn copy_extra_objects(
91 &self,
92 builder: &Builder<'_>,
93 compiler: &Compiler,
94 target: TargetSelection,
95 ) -> Vec<(PathBuf, DependencyType)> {
96 let mut deps = Vec::new();
97 if !self.is_for_mir_opt_tests {
98 deps.extend(copy_third_party_objects(builder, compiler, target));
99 deps.extend(copy_self_contained_objects(builder, compiler, target));
100 }
101 deps
102 }
103
104 pub fn should_be_uplifted_from_stage_1(builder: &Builder<'_>, stage: u32) -> bool {
109 stage > 1 && !builder.config.full_bootstrap
110 }
111}
112
113impl CommandLineStep for Std {
114 type Output = Option<BuildStamp>;
116
117 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
118 run.crate_or_deps("sysroot").path("library")
119 }
120
121 fn is_default_step(_builder: &Builder<'_>) -> bool {
122 true
123 }
124
125 fn make_run(run: RunConfig<'_>) {
126 let crates = std_crates_for_make_run(&run);
127 let builder = run.builder;
128
129 let force_recompile = builder.rust_info().is_managed_git_subrepository()
133 && builder.download_rustc()
134 && builder.config.has_changes_from_upstream(&["library"]);
135
136 trace!("is managed git repo: {}", builder.rust_info().is_managed_git_subrepository());
137 trace!("download_rustc: {}", builder.download_rustc());
138 trace!(force_recompile);
139
140 run.builder.ensure(Std {
141 build_compiler: run.builder.compiler(run.builder.top_stage, builder.host_target),
144 target: run.target,
145 crates,
146 force_recompile,
147 extra_rust_args: &[],
148 is_for_mir_opt_tests: false,
149 });
150 }
151
152 fn run(self, builder: &Builder<'_>) -> Self::Output {
158 let target = self.target;
159
160 if self.build_compiler.stage == 0
165 && !(builder.local_rebuild && target != builder.host_target)
166 {
167 let compiler = self.build_compiler;
168 builder.ensure(StdLink::from_std(self, compiler));
169
170 return None;
171 }
172
173 let build_compiler = if builder.download_rustc() && self.force_recompile {
174 builder
177 .compiler(self.build_compiler.stage.saturating_sub(1), builder.config.host_target)
178 } else {
179 self.build_compiler
180 };
181
182 if builder.download_rustc()
185 && builder.config.is_host_target(target)
186 && !self.force_recompile
187 {
188 let sysroot =
189 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
190 cp_rustc_component_to_ci_sysroot(
191 builder,
192 &sysroot,
193 builder.config.ci_rust_std_contents(),
194 );
195 return None;
196 }
197
198 if (builder.config.keep_stage.contains(&build_compiler.stage)
200 || builder.config.keep_stage_std.contains(&build_compiler.stage))
201 && build_stamp::libstd_stamp(builder, build_compiler, target).path().exists()
202 {
203 trace!(keep_stage = ?builder.config.keep_stage);
204 trace!(keep_stage_std = ?builder.config.keep_stage_std);
205
206 builder.info("WARNING: Using a potentially old libstd. This may not behave well.");
207
208 builder.ensure(StartupObjects { compiler: build_compiler, target });
209
210 self.copy_extra_objects(builder, &build_compiler, target);
211
212 builder.ensure(StdLink::from_std(self, build_compiler));
213 return Some(build_stamp::libstd_stamp(builder, build_compiler, target));
214 }
215
216 let mut target_deps = builder.ensure(StartupObjects { compiler: build_compiler, target });
217
218 let stage = build_compiler.stage;
220
221 if Self::should_be_uplifted_from_stage_1(builder, build_compiler.stage) {
222 let build_compiler_for_std_to_uplift = builder.compiler(1, builder.host_target);
223 let stage_1_stamp = builder.std(build_compiler_for_std_to_uplift, target);
224
225 let msg = if build_compiler_for_std_to_uplift.host == target {
226 format!(
227 "Uplifting library (stage{} -> stage{stage})",
228 build_compiler_for_std_to_uplift.stage
229 )
230 } else {
231 format!(
232 "Uplifting library (stage{}:{} -> stage{stage}:{target})",
233 build_compiler_for_std_to_uplift.stage, build_compiler_for_std_to_uplift.host,
234 )
235 };
236
237 builder.info(&msg);
238
239 self.copy_extra_objects(builder, &build_compiler, target);
242
243 builder.ensure(StdLink::from_std(self, build_compiler_for_std_to_uplift));
244 return stage_1_stamp;
245 }
246
247 target_deps.extend(self.copy_extra_objects(builder, &build_compiler, target));
248
249 let mut cargo = if self.is_for_mir_opt_tests {
253 trace!("building special sysroot for mir-opt tests");
254 let mut cargo = builder::Cargo::new_for_mir_opt_tests(
255 builder,
256 build_compiler,
257 Mode::Std,
258 SourceType::InTree,
259 target,
260 Kind::Check,
261 );
262 cargo.rustflag("-Zalways-encode-mir");
263 cargo.arg("--manifest-path").arg(builder.src.join("library/sysroot/Cargo.toml"));
264 cargo
265 } else {
266 trace!("building regular sysroot");
267 let mut cargo = builder::Cargo::new(
268 builder,
269 build_compiler,
270 Mode::Std,
271 SourceType::InTree,
272 target,
273 Kind::Build,
274 );
275 std_cargo(builder, target, &mut cargo, &self.crates);
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 format_args!("library artifacts{}", crate_description(&self.crates)),
290 Mode::Std,
291 build_compiler,
292 target,
293 );
294
295 let stamp = build_stamp::libstd_stamp(builder, build_compiler, target);
296 run_cargo(
297 builder,
298 cargo,
299 vec![],
300 &stamp,
301 target_deps,
302 if self.is_for_mir_opt_tests {
303 ArtifactKeepMode::OnlyRmeta
304 } else {
305 ArtifactKeepMode::BothRlibAndRmeta
307 },
308 );
309
310 builder.ensure(StdLink::from_std(
311 self,
312 builder.compiler(build_compiler.stage, builder.config.host_target),
313 ));
314 Some(stamp)
315 }
316
317 fn metadata(&self) -> Option<StepMetadata> {
318 Some(StepMetadata::build("std", self.target).built_by(self.build_compiler))
319 }
320}
321
322fn copy_and_stamp(
323 builder: &Builder<'_>,
324 libdir: &Path,
325 sourcedir: &Path,
326 name: &str,
327 target_deps: &mut Vec<(PathBuf, DependencyType)>,
328 dependency_type: DependencyType,
329) {
330 let target = libdir.join(name);
331 builder.copy_link(&sourcedir.join(name), &target, FileType::Regular);
332
333 target_deps.push((target, dependency_type));
334}
335
336fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
337 let libunwind_path = builder.ensure(llvm::Libunwind { target });
338 let libunwind_source = libunwind_path.join("libunwind.a");
339 let libunwind_target = libdir.join("libunwind.a");
340 builder.copy_link(&libunwind_source, &libunwind_target, FileType::NativeLibrary);
341 libunwind_target
342}
343
344fn copy_third_party_objects(
346 builder: &Builder<'_>,
347 compiler: &Compiler,
348 target: TargetSelection,
349) -> Vec<(PathBuf, DependencyType)> {
350 let mut target_deps = vec![];
351
352 if builder.config.needs_sanitizer_runtime_built(target) && compiler.stage != 0 {
353 target_deps.extend(
356 copy_sanitizers(builder, compiler, target)
357 .into_iter()
358 .map(|d| (d, DependencyType::Target { proc_macro: false })),
359 );
360 }
361
362 if target == "x86_64-fortanix-unknown-sgx"
363 || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
364 && (target.contains("linux")
365 || target.contains("fuchsia")
366 || target.contains("aix")
367 || target.contains("hexagon"))
368 {
369 let libunwind_path =
370 copy_llvm_libunwind(builder, target, &builder.sysroot_target_libdir(*compiler, target));
371 target_deps.push((libunwind_path, DependencyType::Target { proc_macro: false }));
372 }
373
374 target_deps
375}
376
377fn copy_self_contained_objects(
379 builder: &Builder<'_>,
380 compiler: &Compiler,
381 target: TargetSelection,
382) -> Vec<(PathBuf, DependencyType)> {
383 let libdir_self_contained =
384 builder.sysroot_target_libdir(*compiler, target).join("self-contained");
385 t!(fs::create_dir_all(&libdir_self_contained));
386 let mut target_deps = vec![];
387
388 if target.needs_crt_begin_end() {
396 let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
397 panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
398 });
399 if !target.starts_with("wasm32") {
400 for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
401 copy_and_stamp(
402 builder,
403 &libdir_self_contained,
404 &srcdir,
405 obj,
406 &mut target_deps,
407 DependencyType::TargetSelfContained,
408 );
409 }
410 let crt_path = builder.ensure(llvm::CrtBeginEnd { target });
411 for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
412 let src = crt_path.join(obj);
413 let target = libdir_self_contained.join(obj);
414 builder.copy_link(&src, &target, FileType::NativeLibrary);
415 target_deps.push((target, DependencyType::TargetSelfContained));
416 }
417 } else {
418 for &obj in &["libc.a", "crt1-command.o"] {
421 copy_and_stamp(
422 builder,
423 &libdir_self_contained,
424 &srcdir,
425 obj,
426 &mut target_deps,
427 DependencyType::TargetSelfContained,
428 );
429 }
430 }
431 if !target.starts_with("s390x") {
432 let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
433 target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
434 }
435 } else if target.contains("-wasi") {
436 let srcdir = builder.wasi_libdir(target).unwrap_or_else(|| {
437 panic!(
438 "Target {:?} does not have a \"wasi-root\" key in bootstrap.toml \
439 or `$WASI_SDK_PATH` set",
440 target.triple
441 )
442 });
443
444 for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
445 copy_and_stamp(
446 builder,
447 &libdir_self_contained,
448 &srcdir,
449 obj,
450 &mut target_deps,
451 DependencyType::TargetSelfContained,
452 );
453 }
454 if srcdir.join("eh").exists() {
455 copy_and_stamp(
456 builder,
457 &libdir_self_contained,
458 &srcdir.join("eh"),
459 "libunwind.a",
460 &mut target_deps,
461 DependencyType::TargetSelfContained,
462 );
463 }
464 } else if target.is_windows_gnu() || target.is_windows_gnullvm() {
465 for obj in ["crt2.o", "dllcrt2.o"].iter() {
466 let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
467 let dst = libdir_self_contained.join(obj);
468 builder.copy_link(&src, &dst, FileType::NativeLibrary);
469 target_deps.push((dst, DependencyType::TargetSelfContained));
470 }
471 }
472
473 target_deps
474}
475
476pub fn std_crates_for_make_run(run: &RunConfig<'_>) -> Vec<String> {
479 let mut crates = run.make_run_crates(builder::Alias::Library);
480
481 let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
490 if target_is_no_std {
491 crates.retain(|c| c == "core" || c == "alloc");
492 }
493 crates
494}
495
496fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
502 if let Some(downloaded_llvm) = builder.ensure(LlvmFromCi { target: builder.host_target }) {
504 let ci_llvm_compiler_rt = downloaded_llvm.output.root_dir().join("compiler-rt");
505 if !builder.config.dry_run() {
506 assert!(
507 ci_llvm_compiler_rt.exists(),
508 "compiler-rt sources not found in LLVM downloaded from CI at {ci_llvm_compiler_rt:?}"
509 );
510 }
511 return ci_llvm_compiler_rt;
512 }
513
514 builder.require_submodule("src/llvm-project", {
516 Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
517 });
518 builder.src.join("src/llvm-project/compiler-rt")
519}
520
521pub fn std_cargo(
524 builder: &Builder<'_>,
525 target: TargetSelection,
526 cargo: &mut Cargo,
527 crates: &[String],
528) {
529 if target.contains("apple") && !builder.config.dry_run() {
547 let mut cmd = builder.rustc_cmd(cargo.compiler());
551 cmd.arg("--target").arg(target.rustc_target_arg());
552 cmd.arg("-Zunstable-options").env("RUSTC_BOOTSTRAP", "1");
555 cmd.arg("--print=deployment-target");
556 let output = cmd.run_capture_stdout(builder).stdout();
557
558 let (env_var, value) = output.split_once('=').unwrap();
559 cargo.env(env_var.trim(), value.trim());
562
563 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
573 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
574 }
575 }
576
577 if let Some(path) = builder.config.profiler_path(target) {
579 cargo.env("LLVM_PROFILER_RT_LIB", path);
580 } else if builder.config.profiler_enabled(target) {
581 let compiler_rt = compiler_rt_for_profiler(builder);
582 cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
586 }
587
588 let compiler_builtins_c_feature = match builder.config.optimized_compiler_builtins(target) {
602 CompilerBuiltins::LinkLLVMBuiltinsLib(path) => {
603 cargo.env("LLVM_COMPILER_RT_LIB", path);
604 " compiler-builtins-c"
605 }
606 CompilerBuiltins::BuildLLVMFuncs => {
607 builder.require_submodule(
617 "src/llvm-project",
618 Some(
619 "The `build.optimized-compiler-builtins` config option \
620 requires `compiler-rt` sources from LLVM.",
621 ),
622 );
623 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
624 if !builder.config.dry_run() {
625 assert!(compiler_builtins_root.exists());
628 }
629
630 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
633 " compiler-builtins-c"
634 }
635 CompilerBuiltins::BuildRustOnly => "",
636 };
637
638 for krate in crates {
639 cargo.args(["-p", krate]);
640 }
641
642 let mut features = String::new();
643
644 if builder.no_std(target) == Some(true) {
645 features += " compiler-builtins-mem";
646 if !target.starts_with("bpf") {
647 features.push_str(compiler_builtins_c_feature);
648 }
649
650 if crates.is_empty() {
652 cargo.args(["-p", "alloc"]);
653 }
654 cargo
655 .arg("--manifest-path")
656 .arg(builder.src.join("library/alloc/Cargo.toml"))
657 .arg("--features")
658 .arg(features);
659 } else {
660 features += &builder.std_features(target);
661 features.push_str(compiler_builtins_c_feature);
662
663 cargo
664 .arg("--features")
665 .arg(features)
666 .arg("--manifest-path")
667 .arg(builder.src.join("library/sysroot/Cargo.toml"));
668
669 if target.contains("musl")
672 && let Some(p) = builder.musl_libdir(target)
673 {
674 let root = format!("native={}", p.to_str().unwrap());
675 cargo.rustflag("-L").rustflag(&root);
676 }
677
678 if target.contains("-wasi")
679 && let Some(dir) = builder.wasi_libdir(target)
680 {
681 let root = format!("native={}", dir.to_str().unwrap());
682 cargo.rustflag("-L").rustflag(&root);
683 }
684 }
685
686 if builder.config.rust_lto == RustcLto::Off {
687 cargo.rustflag("-Clto=off");
688 }
689
690 if target.contains("riscv") {
697 cargo.rustflag("-Cforce-unwind-tables=yes");
698 }
699
700 let html_root =
701 format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
702 cargo.rustflag(&html_root);
703 cargo.rustdocflag(&html_root);
704
705 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
706}
707
708#[derive(Debug, Clone, PartialEq, Eq, Hash)]
717pub struct StdLink {
718 pub compiler: Compiler,
719 pub target_compiler: Compiler,
720 pub target: TargetSelection,
721 crates: Vec<String>,
723 force_recompile: bool,
725}
726
727impl StdLink {
728 pub fn from_std(std: Std, host_compiler: Compiler) -> Self {
729 Self {
730 compiler: host_compiler,
731 target_compiler: std.build_compiler,
732 target: std.target,
733 crates: std.crates,
734 force_recompile: std.force_recompile,
735 }
736 }
737}
738
739impl Step for StdLink {
740 type Output = ();
741
742 fn run(self, builder: &Builder<'_>) {
751 let compiler = self.compiler;
752 let target_compiler = self.target_compiler;
753 let target = self.target;
754
755 let (libdir, hostdir) = if !self.force_recompile && builder.download_rustc() {
757 let lib = builder.sysroot_libdir_relative(self.compiler);
759 let sysroot = builder.ensure(crate::core::build_steps::compile::Sysroot {
760 compiler: self.compiler,
761 force_recompile: self.force_recompile,
762 });
763 let libdir = sysroot.join(lib).join("rustlib").join(target).join("lib");
764 let hostdir = sysroot.join(lib).join("rustlib").join(compiler.host).join("lib");
765 (libdir, hostdir)
766 } else {
767 let libdir = builder.sysroot_target_libdir(target_compiler, target);
768 let hostdir = builder.sysroot_target_libdir(target_compiler, compiler.host);
769 (libdir, hostdir)
770 };
771
772 let is_downloaded_beta_stage0 = builder
773 .sess
774 .initial_rustc
775 .starts_with(builder.out.join(compiler.host).join("stage0/bin"));
776
777 if compiler.stage == 0 && is_downloaded_beta_stage0 {
781 let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
783
784 let host = compiler.host;
785 let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
786 let sysroot_bin_dir = sysroot.join("bin");
787 t!(fs::create_dir_all(&sysroot_bin_dir));
788 builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
789
790 let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
791 t!(fs::create_dir_all(sysroot.join("lib")));
792 builder.cp_link_r(&stage0_lib_dir, &sysroot.join("lib"));
793
794 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
796 t!(fs::create_dir_all(&sysroot_codegen_backends));
797 let stage0_codegen_backends = builder
798 .out
799 .join(host)
800 .join("stage0/lib/rustlib")
801 .join(host)
802 .join("codegen-backends");
803 if stage0_codegen_backends.exists() {
804 builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
805 }
806 } else if compiler.stage == 0 {
807 let sysroot = builder.out.join(compiler.host.triple).join("stage0-sysroot");
808
809 if builder.local_rebuild {
810 let _ = fs::remove_dir_all(sysroot.join("lib/rustlib/src/rust"));
814 }
815
816 builder.cp_link_r(&builder.initial_sysroot.join("lib"), &sysroot.join("lib"));
817 } else {
818 if builder.download_rustc() {
819 let _ = fs::remove_dir_all(&libdir);
821 let _ = fs::remove_dir_all(&hostdir);
822 }
823
824 add_to_sysroot(
825 builder,
826 &libdir,
827 &hostdir,
828 &build_stamp::libstd_stamp(builder, compiler, target),
829 );
830 }
831 }
832}
833
834fn copy_sanitizers(
836 builder: &Builder<'_>,
837 compiler: &Compiler,
838 target: TargetSelection,
839) -> Vec<PathBuf> {
840 let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
841
842 if builder.config.dry_run() {
843 return Vec::new();
844 }
845
846 let mut target_deps = Vec::new();
847 let libdir = builder.sysroot_target_libdir(*compiler, target);
848
849 for runtime in &runtimes {
850 let dst = libdir.join(&runtime.name);
851 builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
852
853 if target == "x86_64-apple-darwin"
857 || target == "aarch64-apple-darwin"
858 || target == "aarch64-apple-ios"
859 || target == "aarch64-apple-ios-sim"
860 || target == "x86_64-apple-ios"
861 {
862 apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
864 apple_darwin_sign_file(builder, &dst);
867 }
868
869 target_deps.push(dst);
870 }
871
872 target_deps
873}
874
875fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
876 command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
877}
878
879fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
880 command("codesign")
881 .arg("-f") .arg("-s")
883 .arg("-")
884 .arg(file_path)
885 .run(builder);
886}
887
888#[derive(Debug, Clone, PartialEq, Eq, Hash)]
889pub struct StartupObjects {
890 pub compiler: Compiler,
891 pub target: TargetSelection,
892}
893
894impl CommandLineStep for StartupObjects {
895 type Output = Vec<(PathBuf, DependencyType)>;
896
897 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
898 run.path("library/rtstartup")
899 }
900
901 fn make_run(run: RunConfig<'_>) {
902 run.builder.ensure(StartupObjects {
903 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
904 target: run.target,
905 });
906 }
907
908 fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
915 let for_compiler = self.compiler;
916 let target = self.target;
917 if !target.is_windows_gnu() {
920 return vec![];
921 }
922
923 let mut target_deps = vec![];
924
925 let src_dir = &builder.src.join("library").join("rtstartup");
926 let dst_dir = &builder.native_dir(target).join("rtstartup");
927 let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
928 t!(fs::create_dir_all(dst_dir));
929
930 for file in &["rsbegin", "rsend"] {
931 let src_file = &src_dir.join(file.to_string() + ".rs");
932 let dst_file = &dst_dir.join(file.to_string() + ".o");
933 if !up_to_date(src_file, dst_file) {
934 let mut cmd = command(&builder.initial_rustc);
935 cmd.env("RUSTC_BOOTSTRAP", "1");
936 if !builder.local_rebuild {
937 cmd.arg("--cfg").arg("bootstrap");
939 }
940 cmd.arg("--target")
941 .arg(target.rustc_target_arg())
942 .arg("--emit=obj")
943 .arg("-o")
944 .arg(dst_file)
945 .arg(src_file)
946 .run(builder);
947 }
948
949 let obj = sysroot_dir.join((*file).to_string() + ".o");
950 builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
951 target_deps.push((obj, DependencyType::Target { proc_macro: false }));
952 }
953
954 target_deps
955 }
956}
957
958fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
959 let ci_rustc_dir = builder.config.ci_rustc_dir();
960
961 for file in contents {
962 let src = ci_rustc_dir.join(&file);
963 let dst = sysroot.join(file);
964 if src.is_dir() {
965 t!(fs::create_dir_all(dst));
966 } else {
967 builder.copy_link(&src, &dst, FileType::Regular);
968 }
969 }
970}
971
972#[derive(Clone, Debug)]
974pub struct BuiltRustc {
975 pub build_compiler: Compiler,
979}
980
981#[derive(Debug, Clone, PartialEq, Eq, Hash)]
988pub struct Rustc {
989 pub target: TargetSelection,
991 pub build_compiler: Compiler,
993 crates: Vec<String>,
999}
1000
1001impl Rustc {
1002 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
1003 Self { target, build_compiler, crates: Default::default() }
1004 }
1005}
1006
1007impl CommandLineStep for Rustc {
1008 type Output = BuiltRustc;
1009 const IS_HOST: bool = true;
1010
1011 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1012 run.crate_or_deps_filtered("rustc-main", |krate| {
1013 krate.name != "rustc-main"
1016 })
1017 }
1018
1019 fn is_default_step(_builder: &Builder<'_>) -> bool {
1020 false
1021 }
1022
1023 fn make_run(run: RunConfig<'_>) {
1024 if run.builder.paths == vec![PathBuf::from("compiler")] {
1027 return;
1028 }
1029
1030 let crates = run.cargo_crates_in_set();
1031 run.builder.ensure(Rustc {
1032 build_compiler: run
1033 .builder
1034 .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1035 target: run.target,
1036 crates,
1037 });
1038 }
1039
1040 fn run(self, builder: &Builder<'_>) -> Self::Output {
1046 let build_compiler = self.build_compiler;
1047 let target = self.target;
1048
1049 if builder.download_rustc() && build_compiler.stage != 0 {
1052 trace!(stage = build_compiler.stage, "`download_rustc` requested");
1053
1054 let sysroot =
1055 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
1056 cp_rustc_component_to_ci_sysroot(
1057 builder,
1058 &sysroot,
1059 builder.config.ci_rustc_dev_contents(),
1060 );
1061 return BuiltRustc { build_compiler };
1062 }
1063
1064 builder.std(build_compiler, target);
1067
1068 if builder.config.keep_stage.contains(&build_compiler.stage) {
1069 trace!(stage = build_compiler.stage, "`keep-stage` requested");
1070
1071 builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1072 builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1073 builder.ensure(RustcLink::from_rustc(self));
1074
1075 return BuiltRustc { build_compiler };
1076 }
1077
1078 let stage = build_compiler.stage + 1;
1080
1081 if build_compiler.stage >= 2
1086 && !builder.config.full_bootstrap
1087 && target == builder.host_target
1088 {
1089 let uplift_build_compiler = builder.compiler(1, build_compiler.host);
1093
1094 let msg = format!("Uplifting rustc from stage2 to stage{stage})");
1095 builder.info(&msg);
1096
1097 builder.ensure(RustcLink::from_build_compiler_and_sysroot(
1101 uplift_build_compiler,
1103 build_compiler,
1105 target,
1106 self.crates,
1107 ));
1108
1109 return BuiltRustc { build_compiler: uplift_build_compiler };
1112 }
1113
1114 builder.std(
1120 builder.compiler(self.build_compiler.stage, builder.config.host_target),
1121 builder.config.host_target,
1122 );
1123
1124 let mut cargo = builder::Cargo::new(
1125 builder,
1126 build_compiler,
1127 Mode::Rustc,
1128 SourceType::InTree,
1129 target,
1130 Kind::Build,
1131 );
1132
1133 rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
1134
1135 for krate in &*self.crates {
1139 cargo.arg("-p").arg(krate);
1140 }
1141
1142 if builder.sess.config.enable_bolt_settings && build_compiler.stage == 1 {
1143 cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1145 }
1146
1147 let _guard = builder.msg(
1148 Kind::Build,
1149 format_args!("compiler artifacts{}", crate_description(&self.crates)),
1150 Mode::Rustc,
1151 build_compiler,
1152 target,
1153 );
1154 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
1155
1156 run_cargo(
1157 builder,
1158 cargo,
1159 vec![],
1160 &stamp,
1161 vec![],
1162 ArtifactKeepMode::Custom(Box::new(|filename| {
1163 if filename.contains("jemalloc_sys")
1164 || filename.contains("rustc_public_bridge")
1165 || filename.contains("rustc_public")
1166 {
1167 if filename.ends_with(".rlib") {
1170 return true;
1171 }
1172 }
1173
1174 filename.ends_with(".rmeta")
1178 })),
1179 );
1180
1181 let target_root_dir = stamp.path().parent().unwrap();
1182 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1188 && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1189 {
1190 let rustc_driver = target_root_dir.join("librustc_driver.so");
1191 strip_debug(builder, target, &rustc_driver);
1192 }
1193
1194 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1195 strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1198 }
1199
1200 builder.ensure(RustcLink::from_rustc(self));
1201 BuiltRustc { build_compiler }
1202 }
1203
1204 fn metadata(&self) -> Option<StepMetadata> {
1205 Some(StepMetadata::build("rustc", self.target).built_by(self.build_compiler))
1206 }
1207}
1208
1209pub fn rustc_cargo(
1210 builder: &Builder<'_>,
1211 cargo: &mut Cargo,
1212 target: TargetSelection,
1213 build_compiler: &Compiler,
1214 crates: &[String],
1215) {
1216 let kind = cargo.kind();
1217 cargo
1218 .arg("--features")
1219 .arg(builder.rustc_features(kind, target, crates))
1220 .arg("--manifest-path")
1221 .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1222
1223 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1224
1225 cargo.rustflag("-Zon-broken-pipe=kill");
1239
1240 if target.is_msvc() {
1245 cargo.rustflag("-Clink-arg=/Brepro");
1246 }
1247
1248 if builder.sess.config.bootstrap_override_lld.is_used() {
1253 cargo.rustflag("-Zdefault-visibility=protected");
1254 }
1255
1256 apply_dylib_lto(builder, build_compiler, cargo);
1257
1258 if builder.config.bootstrap_override_lld.is_used() && !build_compiler.host.is_msvc() {
1266 cargo.rustflag("-Clink-args=-Wl,--icf=all");
1267 }
1268
1269 apply_pgo(builder, cargo, *build_compiler, &builder.config.rust_pgo);
1270
1271 if let Some(ref ccache) = builder.config.ccache
1279 && build_compiler.stage == 0
1280 && !cfg!(windows)
1281 && !builder.config.incremental
1282 {
1283 cargo.env("RUSTC_WRAPPER", ccache);
1284 }
1285
1286 rustc_cargo_env(builder, cargo, target);
1287}
1288
1289fn apply_dylib_lto(builder: &Builder<'_>, build_compiler: &Compiler, cargo: &mut Cargo) {
1290 if is_lto_stage(build_compiler) {
1291 match builder.config.rust_lto {
1292 RustcLto::Thin | RustcLto::Fat => {
1293 cargo.rustflag("-Zdylib-lto");
1296 let lto_type = match builder.config.rust_lto {
1300 RustcLto::Thin => "thin",
1301 RustcLto::Fat => "fat",
1302 _ => unreachable!(),
1303 };
1304 cargo.rustflag(&format!("-Clto={lto_type}"));
1305 cargo.rustflag("-Cembed-bitcode=yes");
1306 }
1307 RustcLto::ThinLocal => { }
1308 RustcLto::Off => {
1309 cargo.rustflag("-Clto=off");
1310 }
1311 }
1312 } else if builder.config.rust_lto == RustcLto::Off {
1313 cargo.rustflag("-Clto=off");
1314 }
1315}
1316
1317fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1318 cargo
1321 .env("CFG_RELEASE", builder.rust_release())
1322 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1323 .env("CFG_VERSION", builder.rust_version());
1324
1325 if builder.config.omit_git_hash {
1329 cargo.env("CFG_OMIT_GIT_HASH", "1");
1330 }
1331
1332 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", builder.config.default_codegen_backend(target).name());
1333
1334 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1335 let target_config = builder.config.target_config.get(&target);
1336
1337 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1338
1339 if let Some(ref ver_date) = builder.rust_info().commit_date() {
1340 cargo.env("CFG_VER_DATE", ver_date);
1341 }
1342 if let Some(ref ver_hash) = builder.rust_info().sha() {
1343 cargo.env("CFG_VER_HASH", ver_hash);
1344 }
1345 if !builder.unstable_features() {
1346 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1347 }
1348
1349 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1352 cargo.env("CFG_DEFAULT_LINKER", s);
1353 } else if let Some(ref s) = builder.config.rustc_default_linker {
1354 cargo.env("CFG_DEFAULT_LINKER", s);
1355 }
1356
1357 if let Some(linker) = target_config.map(|c| c.default_linker_linux_override) {
1359 match linker {
1360 DefaultLinuxLinkerOverride::Off => {}
1361 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1362 cargo.env("CFG_DEFAULT_LINKER_SELF_CONTAINED_LLD_CC", "1");
1363 }
1364 }
1365 }
1366
1367 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1369
1370 if builder.config.rust_verify_llvm_ir {
1371 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1372 }
1373
1374 let nightly = builder.config.channel == "nightly" || builder.config.channel == "dev";
1375 if nightly {
1376 cargo.env("CFG_DEFAULT_POLONIUS_NEXT", "1");
1378 cargo.env("CFG_DEFAULT_NEXT_SOLVER_GLOBALLY", "1");
1379 cargo.env("CFG_DEFAULT_FRONTEND_JOBS", "2");
1381 }
1382
1383 if builder.config.llvm_enabled(target) {
1404 let building_llvm_is_expensive = prebuilt_llvm_output(builder, target).is_none();
1405
1406 let skip_llvm = cargo.kind().is_check_like() && building_llvm_is_expensive;
1407 if skip_llvm {
1408 cargo.env("RUST_CHECK", "1");
1409 } else {
1410 rustc_llvm_env(builder, cargo, target);
1411 }
1412 }
1413
1414 if builder.config.allocator(target) == Allocator::Jemalloc
1416 && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none()
1417 {
1418 if target.starts_with("aarch64") {
1421 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1422 }
1423 else if target.starts_with("loongarch") {
1425 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "14");
1426 }
1427 }
1428
1429 if builder.config.wasm_panic_unwind_default {
1432 cargo.env("CFG_WASM_PANIC_UNWIND_DEFAULT", "1");
1433 }
1434}
1435
1436fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1442 let llvm_output = builder.ensure(llvm::Llvm { target });
1443 if builder.config.is_rust_llvm(&llvm_output, target) {
1444 cargo.env("LLVM_RUSTLLVM", "1");
1445 }
1446 if builder.config.llvm_enzyme {
1447 cargo.env("LLVM_ENZYME", "1");
1448 }
1449 if builder.config.llvm_offload {
1450 builder.ensure(llvm::OmpOffload { target });
1451 cargo.env("LLVM_OFFLOAD", "1");
1452 }
1453
1454 cargo.env("LLVM_CONFIG", builder.host_llvm_config());
1456
1457 let mut llvm_linker_flags = String::new();
1467 if builder.config.llvm_pgo.generate_profile.is_some()
1468 && target.is_msvc()
1469 && let Some(ref clang_cl_path) = builder.config.llvm_clang_cl
1470 {
1471 let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1473 llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
1474 }
1475
1476 if let Some(ref s) = builder.config.llvm_ldflags {
1478 if !llvm_linker_flags.is_empty() {
1479 llvm_linker_flags.push(' ');
1480 }
1481 llvm_linker_flags.push_str(s);
1482 }
1483
1484 if !llvm_linker_flags.is_empty() {
1486 cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
1487 }
1488
1489 if builder.config.llvm_static_stdcpp
1492 && !target.contains("freebsd")
1493 && !target.is_msvc()
1494 && !target.contains("apple")
1495 && !target.contains("solaris")
1496 {
1497 let libstdcxx_name =
1498 if target.contains("windows-gnullvm") { "libc++.a" } else { "libstdc++.a" };
1499 let file = compiler_file(
1500 builder,
1501 &builder.cxx(target).unwrap(),
1502 target,
1503 CLang::Cxx,
1504 libstdcxx_name,
1505 );
1506 cargo.env("LLVM_STATIC_STDCPP", file);
1507 }
1508 if llvm_output.link_shared() {
1509 cargo.env("LLVM_LINK_SHARED", "1");
1510 }
1511 if builder.config.llvm_use_libcxx {
1512 cargo.env("LLVM_USE_LIBCXX", "1");
1513 }
1514 if builder.config.llvm_assertions {
1515 cargo.env("LLVM_ASSERTIONS", "1");
1516 }
1517 if builder.cxx_tool(target).is_like_gnu() || builder.cc_tool(target).is_like_gnu() {
1518 cargo.env("LLVM_COMPILER_IS_GNU_LIKE", "1");
1519 }
1520}
1521
1522#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1535struct RustcLink {
1536 build_compiler: Compiler,
1538 sysroot_compiler: Compiler,
1541 target: TargetSelection,
1542 crates: Vec<String>,
1544}
1545
1546impl RustcLink {
1547 fn from_rustc(rustc: Rustc) -> Self {
1550 Self {
1551 build_compiler: rustc.build_compiler,
1552 sysroot_compiler: rustc.build_compiler,
1553 target: rustc.target,
1554 crates: rustc.crates,
1555 }
1556 }
1557
1558 fn from_build_compiler_and_sysroot(
1560 build_compiler: Compiler,
1561 sysroot_compiler: Compiler,
1562 target: TargetSelection,
1563 crates: Vec<String>,
1564 ) -> Self {
1565 Self { build_compiler, sysroot_compiler, target, crates }
1566 }
1567}
1568
1569impl Step for RustcLink {
1570 type Output = ();
1571
1572 fn run(self, builder: &Builder<'_>) {
1574 let build_compiler = self.build_compiler;
1575 let sysroot_compiler = self.sysroot_compiler;
1576 let target = self.target;
1577 add_to_sysroot(
1578 builder,
1579 &builder.sysroot_target_libdir(sysroot_compiler, target),
1580 &builder.sysroot_target_libdir(sysroot_compiler, sysroot_compiler.host),
1581 &build_stamp::librustc_stamp(builder, build_compiler, target),
1582 );
1583 }
1584}
1585
1586#[derive(Clone)]
1592pub struct GccDylibSet {
1593 dylibs: BTreeMap<GccTargetPair, GccOutput>,
1594}
1595
1596impl GccDylibSet {
1597 pub fn build(
1600 builder: &Builder<'_>,
1601 host: TargetSelection,
1602 targets: Vec<TargetSelection>,
1603 ) -> Self {
1604 let dylibs = targets
1605 .iter()
1606 .map(|t| GccTargetPair::for_target_pair(host, *t))
1607 .map(|target_pair| (target_pair, builder.ensure(Gcc { target_pair })))
1608 .collect();
1609 Self { dylibs }
1610 }
1611
1612 pub fn install_to(&self, builder: &Builder<'_>, compiler: Compiler) {
1616 if builder.config.dry_run() {
1617 return;
1618 }
1619
1620 let cg_sysroot = builder.sysroot_codegen_backends(compiler);
1622
1623 for (target_pair, libgccjit) in &self.dylibs {
1624 assert_eq!(
1625 target_pair.host(),
1626 compiler.host,
1627 "Trying to install libgccjit ({target_pair}) to a compiler with a different host ({})",
1628 compiler.host
1629 );
1630 let libgccjit_path = libgccjit.libgccjit();
1631
1632 let libgccjit_path = t!(
1636 libgccjit_path.canonicalize(),
1637 format!("Cannot find libgccjit at {}", libgccjit_path.display())
1638 );
1639
1640 let dst = cg_sysroot.join(libgccjit_path_relative_to_cg_dir(target_pair, libgccjit));
1641 t!(std::fs::create_dir_all(dst.parent().unwrap()));
1642 builder.copy_link(&libgccjit_path, &dst, FileType::NativeLibrary);
1643 }
1644 }
1645}
1646
1647pub fn libgccjit_path_relative_to_cg_dir(
1650 target_pair: &GccTargetPair,
1651 libgccjit: &GccOutput,
1652) -> PathBuf {
1653 let target_filename = libgccjit.libgccjit().file_name().unwrap().to_str().unwrap();
1654
1655 Path::new("lib").join(target_pair.target()).join(target_filename)
1657}
1658
1659#[derive(Clone)]
1663pub struct GccCodegenBackendOutput {
1664 stamp: BuildStamp,
1665}
1666
1667impl GccCodegenBackendOutput {
1668 pub fn stamp(&self) -> &BuildStamp {
1669 &self.stamp
1670 }
1671}
1672
1673#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1680pub struct GccCodegenBackend {
1681 compilers: RustcPrivateCompilers,
1682 target: TargetSelection,
1683}
1684
1685impl GccCodegenBackend {
1686 pub fn for_target(compilers: RustcPrivateCompilers, target: TargetSelection) -> Self {
1688 Self { compilers, target }
1689 }
1690}
1691
1692impl CommandLineStep for GccCodegenBackend {
1693 type Output = GccCodegenBackendOutput;
1694
1695 const IS_HOST: bool = true;
1696
1697 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1698 run.alias("rustc_codegen_gcc").alias("cg_gcc")
1699 }
1700
1701 fn make_run(run: RunConfig<'_>) {
1702 let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target);
1703 run.builder.ensure(GccCodegenBackend::for_target(compilers, run.target));
1704 }
1705
1706 fn run(self, builder: &Builder<'_>) -> Self::Output {
1707 let host = self.compilers.target();
1708 let build_compiler = self.compilers.build_compiler();
1709
1710 let stamp = build_stamp::codegen_backend_stamp(
1711 builder,
1712 build_compiler,
1713 host,
1714 &CodegenBackendKind::Gcc,
1715 );
1716
1717 if builder.config.keep_stage.contains(&build_compiler.stage) && stamp.path().exists() {
1718 trace!("`keep-stage` requested");
1719 builder.info(
1720 "WARNING: Using a potentially old codegen backend. \
1721 This may not behave well.",
1722 );
1723 return GccCodegenBackendOutput { stamp };
1726 }
1727
1728 let mut cargo = builder::Cargo::new(
1729 builder,
1730 build_compiler,
1731 Mode::Codegen,
1732 SourceType::InTree,
1733 host,
1734 Kind::Build,
1735 );
1736 cargo.arg("--manifest-path").arg(builder.src.join("compiler/rustc_codegen_gcc/Cargo.toml"));
1737 apply_dylib_lto(builder, &build_compiler, &mut cargo);
1738
1739 let _guard =
1740 builder.msg(Kind::Build, "codegen backend gcc", Mode::Codegen, build_compiler, host);
1741 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyDylib);
1742
1743 GccCodegenBackendOutput {
1744 stamp: write_codegen_backend_stamp(stamp, files, builder.config.dry_run()),
1745 }
1746 }
1747
1748 fn metadata(&self) -> Option<StepMetadata> {
1749 Some(
1750 StepMetadata::build("rustc_codegen_gcc", self.compilers.target())
1751 .built_by(self.compilers.build_compiler()),
1752 )
1753 }
1754}
1755
1756#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1757pub struct CraneliftCodegenBackend {
1758 pub compilers: RustcPrivateCompilers,
1759}
1760
1761impl CommandLineStep for CraneliftCodegenBackend {
1762 type Output = BuildStamp;
1763 const IS_HOST: bool = true;
1764
1765 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1766 run.alias("rustc_codegen_cranelift").alias("cg_clif")
1767 }
1768
1769 fn make_run(run: RunConfig<'_>) {
1770 run.builder.ensure(CraneliftCodegenBackend {
1771 compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1772 });
1773 }
1774
1775 fn run(self, builder: &Builder<'_>) -> Self::Output {
1776 let target = self.compilers.target();
1777 let build_compiler = self.compilers.build_compiler();
1778
1779 let stamp = build_stamp::codegen_backend_stamp(
1780 builder,
1781 build_compiler,
1782 target,
1783 &CodegenBackendKind::Cranelift,
1784 );
1785
1786 if builder.config.keep_stage.contains(&build_compiler.stage) {
1787 trace!("`keep-stage` requested");
1788 builder.info(
1789 "WARNING: Using a potentially old codegen backend. \
1790 This may not behave well.",
1791 );
1792 return stamp;
1795 }
1796
1797 let mut cargo = builder::Cargo::new(
1798 builder,
1799 build_compiler,
1800 Mode::Codegen,
1801 SourceType::InTree,
1802 target,
1803 Kind::Build,
1804 );
1805 cargo
1806 .arg("--manifest-path")
1807 .arg(builder.src.join("compiler/rustc_codegen_cranelift/Cargo.toml"));
1808 apply_dylib_lto(builder, &build_compiler, &mut cargo);
1809 apply_pgo(builder, &mut cargo, build_compiler, &builder.config.cranelift_pgo);
1810
1811 let _guard = builder.msg(
1812 Kind::Build,
1813 "codegen backend cranelift",
1814 Mode::Codegen,
1815 build_compiler,
1816 target,
1817 );
1818 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyDylib);
1819 write_codegen_backend_stamp(stamp, files, builder.config.dry_run())
1820 }
1821
1822 fn metadata(&self) -> Option<StepMetadata> {
1823 Some(
1824 StepMetadata::build("rustc_codegen_cranelift", self.compilers.target())
1825 .built_by(self.compilers.build_compiler()),
1826 )
1827 }
1828}
1829
1830fn write_codegen_backend_stamp(
1832 mut stamp: BuildStamp,
1833 files: Vec<PathBuf>,
1834 dry_run: bool,
1835) -> BuildStamp {
1836 if dry_run {
1837 return stamp;
1838 }
1839
1840 let mut files = files.into_iter().filter(|f| looks_like_codegen_backend(Path::new(f)));
1841 let codegen_backend = match files.next() {
1842 Some(f) => f,
1843 None => panic!("no dylibs built for codegen backend?"),
1844 };
1845 if let Some(f) = files.next() {
1846 panic!("codegen backend built two dylibs:\n{}\n{}", codegen_backend.display(), f.display());
1847 }
1848
1849 let codegen_backend = codegen_backend.to_str().unwrap();
1850 stamp = stamp.add_stamp(codegen_backend);
1851 t!(stamp.write());
1852 stamp
1853}
1854
1855pub fn looks_like_codegen_backend(path: &Path) -> bool {
1856 is_dylib(path)
1857 && path.file_name().and_then(|p| p.to_str()).is_some_and(|n| n.contains("rustc_codegen_"))
1858}
1859
1860fn copy_codegen_backends_to_sysroot(
1867 builder: &Builder<'_>,
1868 stamp: BuildStamp,
1869 target_compiler: Compiler,
1870) {
1871 let dst = builder.sysroot_codegen_backends(target_compiler);
1880 t!(fs::create_dir_all(&dst), dst);
1881
1882 if builder.config.dry_run() {
1883 return;
1884 }
1885
1886 if stamp.path().exists() {
1887 let file = get_codegen_backend_file(&stamp);
1888 builder.copy_link(
1889 &file,
1890 &dst.join(normalize_codegen_backend_name(builder, &file)),
1891 FileType::NativeLibrary,
1892 );
1893 }
1894}
1895
1896pub fn get_codegen_backend_file(stamp: &BuildStamp) -> PathBuf {
1898 PathBuf::from(t!(fs::read_to_string(stamp.path())))
1899}
1900
1901pub fn normalize_codegen_backend_name(builder: &Builder<'_>, path: &Path) -> String {
1903 let filename = path.file_name().unwrap().to_str().unwrap();
1904 let dash = filename.find('-').unwrap();
1907 let dot = filename.find('.').unwrap();
1908 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1909}
1910
1911pub fn compiler_file(
1912 builder: &Builder<'_>,
1913 compiler: &Path,
1914 target: TargetSelection,
1915 c: CLang,
1916 file: &str,
1917) -> PathBuf {
1918 if builder.config.dry_run() {
1919 return PathBuf::new();
1920 }
1921 let mut cmd = command(compiler);
1922 cmd.args(builder.cc_handled_cflags(target, c));
1923 cmd.args(builder.cc_unhandled_cflags(target, c));
1924 cmd.arg(format!("-print-file-name={file}"));
1925 let out = cmd.run_capture_stdout(builder).stdout();
1926 PathBuf::from(out.trim())
1927}
1928
1929#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1930pub struct Sysroot {
1931 pub compiler: Compiler,
1932 force_recompile: bool,
1934}
1935
1936impl Sysroot {
1937 pub(crate) fn new(compiler: Compiler) -> Self {
1938 Sysroot { compiler, force_recompile: false }
1939 }
1940}
1941
1942impl Step for Sysroot {
1943 type Output = PathBuf;
1944
1945 fn run(self, builder: &Builder<'_>) -> PathBuf {
1949 let compiler = self.compiler;
1950 let host_dir = builder.out.join(compiler.host);
1951
1952 let sysroot_dir = |stage| {
1953 if stage == 0 {
1954 host_dir.join("stage0-sysroot")
1955 } else if self.force_recompile && stage == compiler.stage {
1956 host_dir.join(format!("stage{stage}-test-sysroot"))
1957 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1958 host_dir.join("ci-rustc-sysroot")
1959 } else {
1960 host_dir.join(format!("stage{stage}"))
1961 }
1962 };
1963 let sysroot = sysroot_dir(compiler.stage);
1964 trace!(stage = ?compiler.stage, ?sysroot);
1965
1966 builder.do_if_verbose(|| {
1967 println!("Removing sysroot {} to avoid caching bugs", sysroot.display())
1968 });
1969 let _ = fs::remove_dir_all(&sysroot);
1970 t!(fs::create_dir_all(&sysroot));
1971
1972 if compiler.stage == 0 {
1979 dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1980 }
1981
1982 if builder.download_rustc() && compiler.stage != 0 {
1984 assert_eq!(
1985 builder.config.host_target, compiler.host,
1986 "Cross-compiling is not yet supported with `download-rustc`",
1987 );
1988
1989 for stage in 0..=2 {
1991 if stage != compiler.stage {
1992 let dir = sysroot_dir(stage);
1993 if !dir.ends_with("ci-rustc-sysroot") {
1994 let _ = fs::remove_dir_all(dir);
1995 }
1996 }
1997 }
1998
1999 let mut filtered_files = Vec::new();
2013 let mut add_filtered_files = |suffix, contents| {
2014 for path in contents {
2015 let path = Path::new(&path);
2016 if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
2017 filtered_files.push(path.file_name().unwrap().to_owned());
2018 }
2019 }
2020 };
2021 let suffix = format!("lib/rustlib/{}/lib", compiler.host);
2022 add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
2023 add_filtered_files("lib", builder.config.ci_rust_std_contents());
2026
2027 let filtered_extensions = [
2028 OsStr::new("rmeta"),
2029 OsStr::new("rlib"),
2030 OsStr::new(std::env::consts::DLL_EXTENSION),
2032 ];
2033 let ci_rustc_dir = builder.config.ci_rustc_dir();
2034 builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
2035 if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
2036 return true;
2037 }
2038 if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
2039 return true;
2040 }
2041 filtered_files.iter().all(|f| f != path.file_name().unwrap())
2042 });
2043 }
2044
2045 if compiler.stage != 0 {
2051 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
2052 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
2053 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
2054 if let Err(e) =
2055 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust)
2056 {
2057 eprintln!(
2058 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2059 sysroot_lib_rustlib_src_rust.display(),
2060 builder.src.display(),
2061 e,
2062 );
2063 if builder.config.rust_remap_debuginfo {
2064 eprintln!(
2065 "ERROR: some `tests/ui` tests will fail when lacking `{}`",
2066 sysroot_lib_rustlib_src_rust.display(),
2067 );
2068 }
2069 helpers::exit_process(1);
2070 }
2071 }
2072
2073 if !builder.download_rustc() {
2075 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
2076 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
2077 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
2078 if let Err(e) =
2079 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
2080 {
2081 eprintln!(
2082 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2083 sysroot_lib_rustlib_rustcsrc_rust.display(),
2084 builder.src.display(),
2085 e,
2086 );
2087 helpers::exit_process(1);
2088 }
2089 }
2090
2091 sysroot
2092 }
2093}
2094
2095#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2102pub struct Assemble {
2103 pub target_compiler: Compiler,
2108}
2109
2110impl CommandLineStep for Assemble {
2111 type Output = Compiler;
2112 const IS_HOST: bool = true;
2113
2114 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2115 run.path("compiler/rustc").path("compiler")
2116 }
2117
2118 fn make_run(run: RunConfig<'_>) {
2119 run.builder.ensure(Assemble {
2120 target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2121 });
2122 }
2123
2124 fn run(self, builder: &Builder<'_>) -> Compiler {
2125 let target_compiler = self.target_compiler;
2126
2127 if target_compiler.stage == 0 {
2128 trace!("stage 0 build compiler is always available, simply returning");
2129 assert_eq!(
2130 builder.config.host_target, target_compiler.host,
2131 "Cannot obtain compiler for non-native build triple at stage 0"
2132 );
2133 return target_compiler;
2135 }
2136
2137 let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2140 let libdir_bin = libdir.parent().unwrap().join("bin");
2141 t!(fs::create_dir_all(&libdir_bin));
2142
2143 if builder.config.llvm_enabled(target_compiler.host) {
2144 trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
2145
2146 let target = target_compiler.host;
2147 let llvm_output = builder.ensure(llvm::Llvm { target });
2148 if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
2149 trace!("LLVM tools enabled");
2150
2151 let host_llvm = builder.ensure(llvm::Llvm { target: builder.host_target });
2152 let host_llvm_bin_dir = command(host_llvm.llvm_config())
2153 .arg("--bindir")
2154 .cached()
2155 .run_capture_stdout(builder)
2156 .stdout()
2157 .trim()
2158 .to_string();
2159
2160 let llvm_bin_dir = if target == builder.host_target {
2161 PathBuf::from(host_llvm_bin_dir)
2162 } else {
2163 let external_llvm_config = builder
2166 .config
2167 .target_config
2168 .get(&target)
2169 .and_then(|t| t.llvm_config.clone());
2170 if let Some(external_llvm_config) = external_llvm_config {
2171 external_llvm_config.parent().unwrap().to_path_buf()
2174 } else {
2175 let host_llvm_out = host_llvm.root_dir();
2179 let target_llvm_out = llvm_output.root_dir();
2180 if let Ok(relative_path) =
2181 Path::new(&host_llvm_bin_dir).strip_prefix(host_llvm_out)
2182 {
2183 target_llvm_out.join(relative_path)
2184 } else {
2185 PathBuf::from(
2188 host_llvm_bin_dir
2189 .replace(&*builder.host_target.triple, &target.triple),
2190 )
2191 }
2192 }
2193 };
2194
2195 #[cfg(feature = "tracing")]
2202 let _llvm_tools_span =
2203 span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
2204 .entered();
2205 for tool in dist::LLVM_TOOLS {
2206 trace!("installing `{tool}`");
2207 let tool_exe = exe(tool, target_compiler.host);
2208 let src_path = llvm_bin_dir.join(&tool_exe);
2209
2210 if !src_path.exists() {
2211 if llvm_output.kind() == LlvmKind::DownloadedFromCi {
2213 eprintln!("{} does not exist; skipping copy", src_path.display());
2214 continue;
2215 }
2216 if *tool == "llubi" {
2219 continue;
2220 }
2221 }
2222
2223 builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2230 }
2231 }
2232 }
2233
2234 let maybe_install_llvm_bitcode_linker = || {
2235 if builder.config.llvm_bitcode_linker_enabled {
2236 trace!("llvm-bitcode-linker enabled, installing");
2237 let llvm_bitcode_linker = builder.ensure(
2238 crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler(
2239 builder,
2240 target_compiler,
2241 ),
2242 );
2243
2244 let bindir_self_contained = builder
2246 .sysroot(target_compiler)
2247 .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host));
2248 let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2249
2250 t!(fs::create_dir_all(&bindir_self_contained));
2251 builder.copy_link(
2252 &llvm_bitcode_linker.tool_path,
2253 &bindir_self_contained.join(tool_exe),
2254 FileType::Executable,
2255 );
2256 }
2257 };
2258
2259 if builder.download_rustc() {
2261 trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2262
2263 builder.std(target_compiler, target_compiler.host);
2264 let sysroot =
2265 builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2266 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2269 if target_compiler.stage == builder.top_stage {
2271 builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage));
2272 }
2273
2274 maybe_install_llvm_bitcode_linker();
2277
2278 return target_compiler;
2279 }
2280
2281 debug!(
2295 "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2296 target_compiler.stage - 1,
2297 builder.config.host_target,
2298 );
2299 let build_compiler =
2300 builder.compiler(target_compiler.stage - 1, builder.config.host_target);
2301
2302 if builder.config.llvm_enzyme {
2304 debug!("`llvm_enzyme` requested");
2305 let enzyme = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2306 let target_libdir =
2307 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2308 let target_dst_lib = target_libdir.join(enzyme.enzyme_filename());
2309 builder.copy_link(&enzyme.enzyme_path(), &target_dst_lib, FileType::NativeLibrary);
2310 }
2311
2312 if builder.config.llvm_offload && !builder.config.dry_run() {
2313 debug!("`llvm_offload` requested");
2314 if builder.is_llvm_enabled_for(builder.config.host_target) {
2315 let rust_offload =
2316 builder.ensure(llvm::RustOffload { target: build_compiler.host });
2317 let target_libdir =
2318 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2319 let rust_offload_dst_lib = target_libdir.join(rust_offload.rust_offload_filename());
2320 builder.copy_link(
2321 &rust_offload.rust_offload_path(),
2322 &rust_offload_dst_lib,
2323 FileType::NativeLibrary,
2324 );
2325
2326 let omp_offload = builder.ensure(llvm::OmpOffload { target: build_compiler.host });
2327 for p in omp_offload.artifact_paths_with_symlink_targets() {
2328 let libname = p.file_name().unwrap();
2329 let dst_lib = target_libdir.join(libname);
2330 builder.resolve_symlink_and_copy(&p, &dst_lib);
2331 }
2332 }
2333 }
2334
2335 debug!(
2338 ?build_compiler,
2339 "target_compiler.host" = ?target_compiler.host,
2340 "building compiler libraries to link to"
2341 );
2342
2343 let BuiltRustc { build_compiler } =
2345 builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2346
2347 let stage = target_compiler.stage;
2348 let host = target_compiler.host;
2349 let (host_info, dir_name) = if build_compiler.host == host {
2350 ("".into(), "host".into())
2351 } else {
2352 (format!(" ({host})"), host.to_string())
2353 };
2354 let msg = format!(
2359 "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2360 );
2361 builder.info(&msg);
2362
2363 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2365 let proc_macros = builder
2366 .read_stamp_file(&stamp)
2367 .into_iter()
2368 .filter_map(|(path, dependency_type)| match dependency_type {
2369 DependencyType::HostProcMacro | DependencyType::Target { proc_macro: true } => {
2370 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2371 }
2372 DependencyType::Target { proc_macro: false }
2373 | DependencyType::TargetSelfContained => None,
2374 })
2375 .collect::<HashSet<_>>();
2376
2377 let sysroot = builder.sysroot(target_compiler);
2378 let rustc_libdir = builder.rustc_libdir(target_compiler);
2379 t!(fs::create_dir_all(&rustc_libdir));
2380 let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2381 for f in builder.read_dir(&src_libdir) {
2382 let filename = f.file_name().into_string().unwrap();
2383
2384 let is_proc_macro = proc_macros.contains(&filename);
2385 let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2386
2387 let can_be_rustc_dynamic_dep =
2389 !(filename.starts_with("std-") || filename.starts_with("libstd-"));
2390
2391 if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2392 builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2393 }
2394 }
2395
2396 {
2397 #[cfg(feature = "tracing")]
2398 let _codegen_backend_span =
2399 span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2400
2401 for backend in builder.config.enabled_codegen_backends(target_compiler.host) {
2402 if builder.kind == Kind::Check && builder.top_stage == 1 {
2419 continue;
2420 }
2421
2422 let prepare_compilers = || {
2423 RustcPrivateCompilers::from_build_and_target_compiler(
2424 build_compiler,
2425 target_compiler,
2426 )
2427 };
2428
2429 match backend {
2430 CodegenBackendKind::Cranelift => {
2431 let stamp = builder
2432 .ensure(CraneliftCodegenBackend { compilers: prepare_compilers() });
2433 copy_codegen_backends_to_sysroot(builder, stamp, target_compiler);
2434 }
2435 CodegenBackendKind::Gcc => {
2436 let compilers = prepare_compilers();
2469 let cg_gcc = builder
2470 .ensure(GccCodegenBackend::for_target(compilers, target_compiler.host));
2471 copy_codegen_backends_to_sysroot(builder, cg_gcc.stamp, target_compiler);
2472
2473 let mut targets = HashSet::new();
2480 for target in &builder.hosts {
2483 targets.insert(*target);
2484 }
2485 for target in &builder.targets {
2487 targets.insert(*target);
2488 }
2489 targets.insert(compilers.target_compiler().host);
2492
2493 let dylib_set = GccDylibSet::build(
2495 builder,
2496 compilers.target_compiler().host,
2497 targets.into_iter().collect(),
2498 );
2499
2500 dylib_set.install_to(builder, target_compiler);
2503 }
2504 CodegenBackendKind::Llvm | CodegenBackendKind::Custom(_) => continue,
2505 }
2506 }
2507 }
2508
2509 if builder.config.lld_enabled {
2510 let lld_wrapper =
2511 builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler(
2512 builder,
2513 target_compiler,
2514 ));
2515 copy_lld_artifacts(builder, lld_wrapper, target_compiler);
2516 }
2517
2518 if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2519 debug!(
2520 "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2521 workaround faulty homebrew `strip`s"
2522 );
2523
2524 let src_exe = exe("llvm-objcopy", target_compiler.host);
2531 let dst_exe = exe("rust-objcopy", target_compiler.host);
2532 builder.copy_link(
2533 &libdir_bin.join(src_exe),
2534 &libdir_bin.join(dst_exe),
2535 FileType::Executable,
2536 );
2537 }
2538
2539 if builder.tool_enabled("wasm-component-ld") {
2543 let wasm_component = builder.ensure(
2544 crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler(
2545 builder,
2546 target_compiler,
2547 ),
2548 );
2549 builder.copy_link(
2550 &wasm_component.tool_path,
2551 &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2552 FileType::Executable,
2553 );
2554 }
2555
2556 maybe_install_llvm_bitcode_linker();
2557
2558 if builder.config.llvm_tpde {
2559 debug!("`llvm_tpde` requested");
2560 if !host.contains("linux") {
2562 builder.info(&format!("host target `{host}` not supported by tpde. skipping"));
2563 } else {
2564 let tpde_output = builder.ensure(llvm::Tpde { target: host });
2566 let target_libdir =
2567 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2568 let target_dst_lib =
2569 target_libdir.join(tpde_output.plugin_path().file_name().unwrap());
2570 builder.copy_link(
2571 tpde_output.plugin_path(),
2572 &target_dst_lib,
2573 FileType::NativeLibrary,
2574 );
2575 }
2576 }
2577
2578 debug!(
2581 "target_compiler.host" = ?target_compiler.host,
2582 ?sysroot,
2583 "ensuring availability of `libLLVM.so` in compiler directory"
2584 );
2585 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2586 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2587
2588 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2590 let rustc = out_dir.join(exe("rustc-main", host));
2591 let bindir = sysroot.join("bin");
2592 t!(fs::create_dir_all(bindir));
2593 let compiler = builder.rustc(target_compiler);
2594 debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2595 builder.copy_link(&rustc, &compiler, FileType::Executable);
2596
2597 target_compiler
2598 }
2599}
2600
2601#[track_caller]
2606pub fn add_to_sysroot(
2607 builder: &Builder<'_>,
2608 sysroot_dst: &Path,
2609 sysroot_host_dst: &Path,
2610 stamp: &BuildStamp,
2611) {
2612 let self_contained_dst = &sysroot_dst.join("self-contained");
2613 t!(fs::create_dir_all(sysroot_dst));
2614 t!(fs::create_dir_all(sysroot_host_dst));
2615 t!(fs::create_dir_all(self_contained_dst));
2616
2617 let mut crates = HashMap::new();
2618 for (path, dependency_type) in builder.read_stamp_file(stamp) {
2619 let filename = path.file_name().unwrap().to_str().unwrap();
2620 let dst = match dependency_type {
2621 DependencyType::HostProcMacro => {
2622 if sysroot_dst == sysroot_host_dst {
2623 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2626 }
2627
2628 sysroot_host_dst
2629 }
2630 DependencyType::Target { .. } => {
2631 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2634
2635 sysroot_dst
2636 }
2637 DependencyType::TargetSelfContained => self_contained_dst,
2638 };
2639 builder.copy_link(&path, &dst.join(filename), FileType::Regular);
2640 }
2641
2642 let mut seen_crates = HashMap::new();
2648 for (filestem, path) in crates {
2649 if !filestem.contains("rustc_") || filestem.contains("rustc_hash") {
2650 continue;
2651 }
2652 if let Some(other_path) =
2653 seen_crates.insert(filestem.split_once('-').unwrap().0.to_owned(), path.clone())
2654 {
2655 panic!(
2656 "duplicate rustc crate {}\n- first copy at {}\n- second copy at {}",
2657 filestem.split_once('-').unwrap().0.to_owned(),
2658 other_path.display(),
2659 path.display(),
2660 );
2661 }
2662 }
2663}
2664
2665pub enum ArtifactKeepMode {
2669 OnlyDylib,
2671 OnlyRmeta,
2673 BothRlibAndRmeta,
2675 Custom(Box<dyn Fn(&str) -> bool>),
2678}
2679
2680pub fn run_cargo(
2681 builder: &Builder<'_>,
2682 cargo: Cargo,
2683 tail_args: Vec<String>,
2684 stamp: &BuildStamp,
2685 additional_target_deps: Vec<(PathBuf, DependencyType)>,
2686 artifact_keep_mode: ArtifactKeepMode,
2687) -> Vec<PathBuf> {
2688 let target_root_dir = stamp.path().parent().unwrap();
2690 let target_build_dir = target_root_dir.join("build");
2692 let host_root_dir = target_root_dir
2694 .parent()
2695 .unwrap() .parent()
2697 .unwrap() .join(target_root_dir.file_name().unwrap());
2699
2700 let mut deps = Vec::new();
2704 let mut toplevel = Vec::new();
2705 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2706 let (filenames_vec, crate_types) = match msg {
2707 CargoMessage::CompilerArtifact {
2708 filenames,
2709 target: CargoTarget { crate_types, .. },
2710 ..
2711 } => {
2712 let mut f: Vec<String> = filenames.into_iter().map(|s| s.into_owned()).collect();
2713 f.sort(); (f, crate_types)
2715 }
2716 _ => return,
2717 };
2718 for filename in filenames_vec {
2719 let keep = if filename.ends_with(".lib")
2721 || filename.ends_with(".a")
2722 || is_debug_info(&filename)
2723 || is_dylib(Path::new(&*filename))
2724 {
2725 true
2727 } else {
2728 match &artifact_keep_mode {
2729 ArtifactKeepMode::OnlyDylib => false,
2730 ArtifactKeepMode::OnlyRmeta => filename.ends_with(".rmeta"),
2731 ArtifactKeepMode::BothRlibAndRmeta => {
2732 filename.ends_with(".rmeta") || filename.ends_with(".rlib")
2733 }
2734 ArtifactKeepMode::Custom(func) => func(&filename),
2735 }
2736 };
2737
2738 if !keep {
2739 continue;
2740 }
2741
2742 let filename = Path::new(&*filename);
2743
2744 let is_proc_macro = crate_types.iter().any(|t| t == "proc-macro");
2745
2746 if filename.starts_with(&host_root_dir) {
2749 if is_proc_macro {
2751 if filename.file_name().unwrap().to_str().unwrap().contains("-") {
2756 deps.push((filename.to_path_buf(), DependencyType::HostProcMacro));
2757 }
2758 }
2759 continue;
2760 }
2761
2762 if filename.starts_with(&target_build_dir) {
2765 deps.push((
2766 filename.to_path_buf(),
2767 DependencyType::Target { proc_macro: is_proc_macro },
2768 ));
2769 continue;
2770 }
2771
2772 let expected_len = t!(filename.metadata()).len();
2783 let filename = filename.file_name().unwrap().to_str().unwrap();
2784 let mut parts = filename.splitn(2, '.');
2785 let file_stem = parts.next().unwrap().to_owned();
2786 let extension = parts.next().unwrap().to_owned();
2787
2788 toplevel.push((file_stem, extension, expected_len, is_proc_macro));
2789 }
2790 });
2791
2792 if !ok {
2793 helpers::exit_process(1);
2794 }
2795
2796 if builder.config.dry_run() {
2797 return Vec::new();
2798 }
2799
2800 let read_dir = |path: &Path| path.read_dir().ok().into_iter().flatten().filter_map(Result::ok);
2807 let contents = target_build_dir
2808 .read_dir()
2809 .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_build_dir.display(), e))
2810 .map(|e| e.unwrap())
2811 .flat_map(|e| read_dir(&e.path()))
2812 .flat_map(|e| read_dir(&e.path()))
2813 .flat_map(|e| read_dir(&e.path()))
2814 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2815 .collect::<Vec<_>>();
2816 for (prefix, extension, expected_len, is_proc_macro) in toplevel {
2817 let candidates = contents.iter().filter(|&(_, filename, meta)| {
2818 meta.len() == expected_len
2819 && filename
2820 .strip_prefix(&prefix[..])
2821 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2822 .unwrap_or(false)
2823 });
2824 let max = candidates.max_by_key(|&(_, _, metadata)| {
2825 metadata.modified().expect("mtime should be available on all relevant OSes")
2826 });
2827 let path_to_add = match max {
2828 Some(triple) => triple.0.to_str().unwrap(),
2829 None => panic!("no output generated for {prefix:?} {extension:?}"),
2830 };
2831 if is_dylib(Path::new(path_to_add)) {
2832 let candidate = format!("{path_to_add}.lib");
2833 let candidate = PathBuf::from(candidate);
2834 if candidate.exists() {
2835 deps.push((candidate, DependencyType::Target { proc_macro: is_proc_macro }));
2836 }
2837 }
2838 deps.push((path_to_add.into(), DependencyType::Target { proc_macro: is_proc_macro }));
2839 }
2840
2841 deps.extend(additional_target_deps);
2842 deps.sort();
2843 let mut new_contents = Vec::new();
2844 for (dep, dependency_type) in deps.iter() {
2845 new_contents.extend(match *dependency_type {
2846 DependencyType::HostProcMacro => b"h",
2847 DependencyType::Target { proc_macro: false } => b"t",
2848 DependencyType::Target { proc_macro: true } => b"p",
2849 DependencyType::TargetSelfContained => b"s",
2850 });
2851 new_contents.extend(dep.to_str().unwrap().as_bytes());
2852 new_contents.extend(b"\0");
2853 }
2854 t!(fs::write(stamp.path(), &new_contents));
2855 deps.into_iter().map(|(d, _)| d).collect()
2856}
2857
2858pub fn stream_cargo(
2859 builder: &Builder<'_>,
2860 cargo: Cargo,
2861 tail_args: Vec<String>,
2862 cb: &mut dyn FnMut(CargoMessage<'_>),
2863) -> bool {
2864 let mut cmd = cargo.into_cmd();
2865
2866 let mut message_format = if builder.config.json_output {
2869 String::from("json")
2870 } else {
2871 String::from("json-render-diagnostics")
2872 };
2873 if let Some(s) = &builder.config.rustc_error_format {
2874 message_format.push_str(",json-diagnostic-");
2875 message_format.push_str(s);
2876 }
2877 cmd.arg("--message-format").arg(message_format);
2878
2879 for arg in tail_args {
2880 cmd.arg(arg);
2881 }
2882
2883 builder.do_if_verbose(|| println!("running: {cmd:?}"));
2884
2885 let streaming_command = cmd.stream_capture_stdout(&builder.config.exec_ctx);
2886
2887 let Some(mut streaming_command) = streaming_command else {
2888 return true;
2889 };
2890
2891 let stdout = BufReader::new(streaming_command.stdout.take().unwrap());
2895 for line in stdout.lines() {
2896 let line = t!(line);
2897 match serde_json::from_str::<CargoMessage<'_>>(&line) {
2898 Ok(msg) => {
2899 if builder.config.json_output {
2900 println!("{line}");
2902 }
2903 cb(msg)
2904 }
2905 Err(_) => println!("{line}"),
2907 }
2908 }
2909
2910 let status = t!(streaming_command.wait(&builder.config.exec_ctx));
2912 if builder.is_verbose() && !status.success() {
2913 eprintln!(
2914 "command did not execute successfully: {cmd:?}\n\
2915 expected success, got: {status}"
2916 );
2917 }
2918
2919 status.success()
2920}
2921
2922#[derive(Deserialize, Debug)]
2923pub struct CargoTarget<'a> {
2924 pub crate_types: Vec<Cow<'a, str>>,
2925 #[serde(default)]
2926 pub doc: bool,
2927}
2928
2929#[derive(Deserialize, Debug)]
2930#[serde(tag = "reason", rename_all = "kebab-case")]
2931pub enum CargoMessage<'a> {
2932 CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2933 BuildScriptExecuted,
2934 BuildFinished,
2935}
2936
2937pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2938 if target != "x86_64-unknown-linux-gnu"
2942 || !builder.config.is_host_target(target)
2943 || !path.exists()
2944 {
2945 return;
2946 }
2947
2948 let previous_mtime = t!(t!(path.metadata()).modified());
2949 let stamp = BuildStamp::new(path.parent().unwrap())
2950 .with_prefix(path.file_name().unwrap().to_str().unwrap())
2951 .with_prefix("strip")
2952 .add_stamp(previous_mtime.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos());
2953
2954 if !stamp.is_up_to_date() {
2957 command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2958 }
2959 t!(stamp.write());
2960
2961 let file = t!(fs::File::open(path));
2962
2963 t!(file.set_modified(previous_mtime));
2976}
2977
2978pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2980 build_compiler.stage != 0
2981}