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)
199 || builder.config.keep_stage_std.contains(&build_compiler.stage)
200 {
201 trace!(keep_stage = ?builder.config.keep_stage);
202 trace!(keep_stage_std = ?builder.config.keep_stage_std);
203
204 builder.info("WARNING: Using a potentially old libstd. This may not behave well.");
205
206 builder.ensure(StartupObjects { compiler: build_compiler, target });
207
208 self.copy_extra_objects(builder, &build_compiler, target);
209
210 builder.ensure(StdLink::from_std(self, build_compiler));
211 return Some(build_stamp::libstd_stamp(builder, build_compiler, target));
212 }
213
214 let mut target_deps = builder.ensure(StartupObjects { compiler: build_compiler, target });
215
216 let stage = build_compiler.stage;
218
219 if Self::should_be_uplifted_from_stage_1(builder, build_compiler.stage) {
220 let build_compiler_for_std_to_uplift = builder.compiler(1, builder.host_target);
221 let stage_1_stamp = builder.std(build_compiler_for_std_to_uplift, target);
222
223 let msg = if build_compiler_for_std_to_uplift.host == target {
224 format!(
225 "Uplifting library (stage{} -> stage{stage})",
226 build_compiler_for_std_to_uplift.stage
227 )
228 } else {
229 format!(
230 "Uplifting library (stage{}:{} -> stage{stage}:{target})",
231 build_compiler_for_std_to_uplift.stage, build_compiler_for_std_to_uplift.host,
232 )
233 };
234
235 builder.info(&msg);
236
237 self.copy_extra_objects(builder, &build_compiler, target);
240
241 builder.ensure(StdLink::from_std(self, build_compiler_for_std_to_uplift));
242 return stage_1_stamp;
243 }
244
245 target_deps.extend(self.copy_extra_objects(builder, &build_compiler, target));
246
247 let mut cargo = if self.is_for_mir_opt_tests {
251 trace!("building special sysroot for mir-opt tests");
252 let mut cargo = builder::Cargo::new_for_mir_opt_tests(
253 builder,
254 build_compiler,
255 Mode::Std,
256 SourceType::InTree,
257 target,
258 Kind::Check,
259 );
260 cargo.rustflag("-Zalways-encode-mir");
261 cargo.arg("--manifest-path").arg(builder.src.join("library/sysroot/Cargo.toml"));
262 cargo
263 } else {
264 trace!("building regular sysroot");
265 let mut cargo = builder::Cargo::new(
266 builder,
267 build_compiler,
268 Mode::Std,
269 SourceType::InTree,
270 target,
271 Kind::Build,
272 );
273 std_cargo(builder, target, &mut cargo, &self.crates);
274 cargo
275 };
276
277 if target.is_synthetic() {
279 cargo.env("RUSTC_BOOTSTRAP_SYNTHETIC_TARGET", "1");
280 }
281 for rustflag in self.extra_rust_args.iter() {
282 cargo.rustflag(rustflag);
283 }
284
285 let _guard = builder.msg(
286 Kind::Build,
287 format_args!("library artifacts{}", crate_description(&self.crates)),
288 Mode::Std,
289 build_compiler,
290 target,
291 );
292
293 let stamp = build_stamp::libstd_stamp(builder, build_compiler, target);
294 run_cargo(
295 builder,
296 cargo,
297 vec![],
298 &stamp,
299 target_deps,
300 if self.is_for_mir_opt_tests {
301 ArtifactKeepMode::OnlyRmeta
302 } else {
303 ArtifactKeepMode::BothRlibAndRmeta
305 },
306 );
307
308 builder.ensure(StdLink::from_std(
309 self,
310 builder.compiler(build_compiler.stage, builder.config.host_target),
311 ));
312 Some(stamp)
313 }
314
315 fn metadata(&self) -> Option<StepMetadata> {
316 Some(StepMetadata::build("std", self.target).built_by(self.build_compiler))
317 }
318}
319
320fn copy_and_stamp(
321 builder: &Builder<'_>,
322 libdir: &Path,
323 sourcedir: &Path,
324 name: &str,
325 target_deps: &mut Vec<(PathBuf, DependencyType)>,
326 dependency_type: DependencyType,
327) {
328 let target = libdir.join(name);
329 builder.copy_link(&sourcedir.join(name), &target, FileType::Regular);
330
331 target_deps.push((target, dependency_type));
332}
333
334fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
335 let libunwind_path = builder.ensure(llvm::Libunwind { target });
336 let libunwind_source = libunwind_path.join("libunwind.a");
337 let libunwind_target = libdir.join("libunwind.a");
338 builder.copy_link(&libunwind_source, &libunwind_target, FileType::NativeLibrary);
339 libunwind_target
340}
341
342fn copy_third_party_objects(
344 builder: &Builder<'_>,
345 compiler: &Compiler,
346 target: TargetSelection,
347) -> Vec<(PathBuf, DependencyType)> {
348 let mut target_deps = vec![];
349
350 if builder.config.needs_sanitizer_runtime_built(target) && compiler.stage != 0 {
351 target_deps.extend(
354 copy_sanitizers(builder, compiler, target)
355 .into_iter()
356 .map(|d| (d, DependencyType::Target)),
357 );
358 }
359
360 if target == "x86_64-fortanix-unknown-sgx"
361 || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
362 && (target.contains("linux")
363 || target.contains("fuchsia")
364 || target.contains("aix")
365 || target.contains("hexagon"))
366 {
367 let libunwind_path =
368 copy_llvm_libunwind(builder, target, &builder.sysroot_target_libdir(*compiler, target));
369 target_deps.push((libunwind_path, DependencyType::Target));
370 }
371
372 target_deps
373}
374
375fn copy_self_contained_objects(
377 builder: &Builder<'_>,
378 compiler: &Compiler,
379 target: TargetSelection,
380) -> Vec<(PathBuf, DependencyType)> {
381 let libdir_self_contained =
382 builder.sysroot_target_libdir(*compiler, target).join("self-contained");
383 t!(fs::create_dir_all(&libdir_self_contained));
384 let mut target_deps = vec![];
385
386 if target.needs_crt_begin_end() {
394 let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
395 panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
396 });
397 if !target.starts_with("wasm32") {
398 for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
399 copy_and_stamp(
400 builder,
401 &libdir_self_contained,
402 &srcdir,
403 obj,
404 &mut target_deps,
405 DependencyType::TargetSelfContained,
406 );
407 }
408 let crt_path = builder.ensure(llvm::CrtBeginEnd { target });
409 for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
410 let src = crt_path.join(obj);
411 let target = libdir_self_contained.join(obj);
412 builder.copy_link(&src, &target, FileType::NativeLibrary);
413 target_deps.push((target, DependencyType::TargetSelfContained));
414 }
415 } else {
416 for &obj in &["libc.a", "crt1-command.o"] {
419 copy_and_stamp(
420 builder,
421 &libdir_self_contained,
422 &srcdir,
423 obj,
424 &mut target_deps,
425 DependencyType::TargetSelfContained,
426 );
427 }
428 }
429 if !target.starts_with("s390x") {
430 let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
431 target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
432 }
433 } else if target.contains("-wasi") {
434 let srcdir = builder.wasi_libdir(target).unwrap_or_else(|| {
435 panic!(
436 "Target {:?} does not have a \"wasi-root\" key in bootstrap.toml \
437 or `$WASI_SDK_PATH` set",
438 target.triple
439 )
440 });
441
442 for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
443 copy_and_stamp(
444 builder,
445 &libdir_self_contained,
446 &srcdir,
447 obj,
448 &mut target_deps,
449 DependencyType::TargetSelfContained,
450 );
451 }
452 if srcdir.join("eh").exists() {
453 copy_and_stamp(
454 builder,
455 &libdir_self_contained,
456 &srcdir.join("eh"),
457 "libunwind.a",
458 &mut target_deps,
459 DependencyType::TargetSelfContained,
460 );
461 }
462 } else if target.is_windows_gnu() || target.is_windows_gnullvm() {
463 for obj in ["crt2.o", "dllcrt2.o"].iter() {
464 let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
465 let dst = libdir_self_contained.join(obj);
466 builder.copy_link(&src, &dst, FileType::NativeLibrary);
467 target_deps.push((dst, DependencyType::TargetSelfContained));
468 }
469 }
470
471 target_deps
472}
473
474pub fn std_crates_for_make_run(run: &RunConfig<'_>) -> Vec<String> {
477 let mut crates = run.make_run_crates(builder::Alias::Library);
478
479 let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
488 if target_is_no_std {
489 crates.retain(|c| c == "core" || c == "alloc");
490 }
491 crates
492}
493
494fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
500 if let Some(downloaded_llvm) = builder.ensure(LlvmFromCi { target: builder.host_target }) {
502 let ci_llvm_compiler_rt = downloaded_llvm.output.root_dir().join("compiler-rt");
503 if !builder.config.dry_run() {
504 assert!(
505 ci_llvm_compiler_rt.exists(),
506 "compiler-rt sources not found in LLVM downloaded from CI at {ci_llvm_compiler_rt:?}"
507 );
508 }
509 return ci_llvm_compiler_rt;
510 }
511
512 builder.require_submodule("src/llvm-project", {
514 Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
515 });
516 builder.src.join("src/llvm-project/compiler-rt")
517}
518
519pub fn std_cargo(
522 builder: &Builder<'_>,
523 target: TargetSelection,
524 cargo: &mut Cargo,
525 crates: &[String],
526) {
527 if target.contains("apple") && !builder.config.dry_run() {
545 let mut cmd = builder.rustc_cmd(cargo.compiler());
549 cmd.arg("--target").arg(target.rustc_target_arg());
550 cmd.arg("-Zunstable-options").env("RUSTC_BOOTSTRAP", "1");
553 cmd.arg("--print=deployment-target");
554 let output = cmd.run_capture_stdout(builder).stdout();
555
556 let (env_var, value) = output.split_once('=').unwrap();
557 cargo.env(env_var.trim(), value.trim());
560
561 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
571 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
572 }
573 }
574
575 if let Some(path) = builder.config.profiler_path(target) {
577 cargo.env("LLVM_PROFILER_RT_LIB", path);
578 } else if builder.config.profiler_enabled(target) {
579 let compiler_rt = compiler_rt_for_profiler(builder);
580 cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
584 }
585
586 let compiler_builtins_c_feature = match builder.config.optimized_compiler_builtins(target) {
600 CompilerBuiltins::LinkLLVMBuiltinsLib(path) => {
601 cargo.env("LLVM_COMPILER_RT_LIB", path);
602 " compiler-builtins-c"
603 }
604 CompilerBuiltins::BuildLLVMFuncs => {
605 builder.require_submodule(
615 "src/llvm-project",
616 Some(
617 "The `build.optimized-compiler-builtins` config option \
618 requires `compiler-rt` sources from LLVM.",
619 ),
620 );
621 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
622 if !builder.config.dry_run() {
623 assert!(compiler_builtins_root.exists());
626 }
627
628 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
631 " compiler-builtins-c"
632 }
633 CompilerBuiltins::BuildRustOnly => "",
634 };
635
636 for krate in crates {
637 cargo.args(["-p", krate]);
638 }
639
640 let mut features = String::new();
641
642 if builder.no_std(target) == Some(true) {
643 features += " compiler-builtins-mem";
644 if !target.starts_with("bpf") {
645 features.push_str(compiler_builtins_c_feature);
646 }
647
648 if crates.is_empty() {
650 cargo.args(["-p", "alloc"]);
651 }
652 cargo
653 .arg("--manifest-path")
654 .arg(builder.src.join("library/alloc/Cargo.toml"))
655 .arg("--features")
656 .arg(features);
657 } else {
658 features += &builder.std_features(target);
659 features.push_str(compiler_builtins_c_feature);
660
661 cargo
662 .arg("--features")
663 .arg(features)
664 .arg("--manifest-path")
665 .arg(builder.src.join("library/sysroot/Cargo.toml"));
666
667 if target.contains("musl")
670 && let Some(p) = builder.musl_libdir(target)
671 {
672 let root = format!("native={}", p.to_str().unwrap());
673 cargo.rustflag("-L").rustflag(&root);
674 }
675
676 if target.contains("-wasi")
677 && let Some(dir) = builder.wasi_libdir(target)
678 {
679 let root = format!("native={}", dir.to_str().unwrap());
680 cargo.rustflag("-L").rustflag(&root);
681 }
682 }
683
684 if builder.config.rust_lto == RustcLto::Off {
685 cargo.rustflag("-Clto=off");
686 }
687
688 if target.contains("riscv") {
695 cargo.rustflag("-Cforce-unwind-tables=yes");
696 }
697
698 let html_root =
699 format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
700 cargo.rustflag(&html_root);
701 cargo.rustdocflag(&html_root);
702
703 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
704}
705
706#[derive(Debug, Clone, PartialEq, Eq, Hash)]
715pub struct StdLink {
716 pub compiler: Compiler,
717 pub target_compiler: Compiler,
718 pub target: TargetSelection,
719 crates: Vec<String>,
721 force_recompile: bool,
723}
724
725impl StdLink {
726 pub fn from_std(std: Std, host_compiler: Compiler) -> Self {
727 Self {
728 compiler: host_compiler,
729 target_compiler: std.build_compiler,
730 target: std.target,
731 crates: std.crates,
732 force_recompile: std.force_recompile,
733 }
734 }
735}
736
737impl Step for StdLink {
738 type Output = ();
739
740 fn run(self, builder: &Builder<'_>) {
749 let compiler = self.compiler;
750 let target_compiler = self.target_compiler;
751 let target = self.target;
752
753 let (libdir, hostdir) = if !self.force_recompile && builder.download_rustc() {
755 let lib = builder.sysroot_libdir_relative(self.compiler);
757 let sysroot = builder.ensure(crate::core::build_steps::compile::Sysroot {
758 compiler: self.compiler,
759 force_recompile: self.force_recompile,
760 });
761 let libdir = sysroot.join(lib).join("rustlib").join(target).join("lib");
762 let hostdir = sysroot.join(lib).join("rustlib").join(compiler.host).join("lib");
763 (libdir, hostdir)
764 } else {
765 let libdir = builder.sysroot_target_libdir(target_compiler, target);
766 let hostdir = builder.sysroot_target_libdir(target_compiler, compiler.host);
767 (libdir, hostdir)
768 };
769
770 let is_downloaded_beta_stage0 = builder
771 .sess
772 .initial_rustc
773 .starts_with(builder.out.join(compiler.host).join("stage0/bin"));
774
775 if compiler.stage == 0 && is_downloaded_beta_stage0 {
779 let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
781
782 let host = compiler.host;
783 let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
784 let sysroot_bin_dir = sysroot.join("bin");
785 t!(fs::create_dir_all(&sysroot_bin_dir));
786 builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
787
788 let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
789 t!(fs::create_dir_all(sysroot.join("lib")));
790 builder.cp_link_r(&stage0_lib_dir, &sysroot.join("lib"));
791
792 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
794 t!(fs::create_dir_all(&sysroot_codegen_backends));
795 let stage0_codegen_backends = builder
796 .out
797 .join(host)
798 .join("stage0/lib/rustlib")
799 .join(host)
800 .join("codegen-backends");
801 if stage0_codegen_backends.exists() {
802 builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
803 }
804 } else if compiler.stage == 0 {
805 let sysroot = builder.out.join(compiler.host.triple).join("stage0-sysroot");
806
807 if builder.local_rebuild {
808 let _ = fs::remove_dir_all(sysroot.join("lib/rustlib/src/rust"));
812 }
813
814 builder.cp_link_r(&builder.initial_sysroot.join("lib"), &sysroot.join("lib"));
815 } else {
816 if builder.download_rustc() {
817 let _ = fs::remove_dir_all(&libdir);
819 let _ = fs::remove_dir_all(&hostdir);
820 }
821
822 add_to_sysroot(
823 builder,
824 &libdir,
825 &hostdir,
826 &build_stamp::libstd_stamp(builder, compiler, target),
827 );
828 }
829 }
830}
831
832fn copy_sanitizers(
834 builder: &Builder<'_>,
835 compiler: &Compiler,
836 target: TargetSelection,
837) -> Vec<PathBuf> {
838 let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
839
840 if builder.config.dry_run() {
841 return Vec::new();
842 }
843
844 let mut target_deps = Vec::new();
845 let libdir = builder.sysroot_target_libdir(*compiler, target);
846
847 for runtime in &runtimes {
848 let dst = libdir.join(&runtime.name);
849 builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
850
851 if target == "x86_64-apple-darwin"
855 || target == "aarch64-apple-darwin"
856 || target == "aarch64-apple-ios"
857 || target == "aarch64-apple-ios-sim"
858 || target == "x86_64-apple-ios"
859 {
860 apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
862 apple_darwin_sign_file(builder, &dst);
865 }
866
867 target_deps.push(dst);
868 }
869
870 target_deps
871}
872
873fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
874 command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
875}
876
877fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
878 command("codesign")
879 .arg("-f") .arg("-s")
881 .arg("-")
882 .arg(file_path)
883 .run(builder);
884}
885
886#[derive(Debug, Clone, PartialEq, Eq, Hash)]
887pub struct StartupObjects {
888 pub compiler: Compiler,
889 pub target: TargetSelection,
890}
891
892impl CommandLineStep for StartupObjects {
893 type Output = Vec<(PathBuf, DependencyType)>;
894
895 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
896 run.path("library/rtstartup")
897 }
898
899 fn make_run(run: RunConfig<'_>) {
900 run.builder.ensure(StartupObjects {
901 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
902 target: run.target,
903 });
904 }
905
906 fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
913 let for_compiler = self.compiler;
914 let target = self.target;
915 if !target.is_windows_gnu() {
918 return vec![];
919 }
920
921 let mut target_deps = vec![];
922
923 let src_dir = &builder.src.join("library").join("rtstartup");
924 let dst_dir = &builder.native_dir(target).join("rtstartup");
925 let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
926 t!(fs::create_dir_all(dst_dir));
927
928 for file in &["rsbegin", "rsend"] {
929 let src_file = &src_dir.join(file.to_string() + ".rs");
930 let dst_file = &dst_dir.join(file.to_string() + ".o");
931 if !up_to_date(src_file, dst_file) {
932 let mut cmd = command(&builder.initial_rustc);
933 cmd.env("RUSTC_BOOTSTRAP", "1");
934 if !builder.local_rebuild {
935 cmd.arg("--cfg").arg("bootstrap");
937 }
938 cmd.arg("--target")
939 .arg(target.rustc_target_arg())
940 .arg("--emit=obj")
941 .arg("-o")
942 .arg(dst_file)
943 .arg(src_file)
944 .run(builder);
945 }
946
947 let obj = sysroot_dir.join((*file).to_string() + ".o");
948 builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
949 target_deps.push((obj, DependencyType::Target));
950 }
951
952 target_deps
953 }
954}
955
956fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
957 let ci_rustc_dir = builder.config.ci_rustc_dir();
958
959 for file in contents {
960 let src = ci_rustc_dir.join(&file);
961 let dst = sysroot.join(file);
962 if src.is_dir() {
963 t!(fs::create_dir_all(dst));
964 } else {
965 builder.copy_link(&src, &dst, FileType::Regular);
966 }
967 }
968}
969
970#[derive(Clone, Debug)]
972pub struct BuiltRustc {
973 pub build_compiler: Compiler,
977}
978
979#[derive(Debug, Clone, PartialEq, Eq, Hash)]
986pub struct Rustc {
987 pub target: TargetSelection,
989 pub build_compiler: Compiler,
991 crates: Vec<String>,
997}
998
999impl Rustc {
1000 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
1001 Self { target, build_compiler, crates: Default::default() }
1002 }
1003}
1004
1005impl CommandLineStep for Rustc {
1006 type Output = BuiltRustc;
1007 const IS_HOST: bool = true;
1008
1009 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1010 run.crate_or_deps_filtered("rustc-main", |krate| {
1011 krate.name != "rustc-main"
1014 })
1015 }
1016
1017 fn is_default_step(_builder: &Builder<'_>) -> bool {
1018 false
1019 }
1020
1021 fn make_run(run: RunConfig<'_>) {
1022 if run.builder.paths == vec![PathBuf::from("compiler")] {
1025 return;
1026 }
1027
1028 let crates = run.cargo_crates_in_set();
1029 run.builder.ensure(Rustc {
1030 build_compiler: run
1031 .builder
1032 .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1033 target: run.target,
1034 crates,
1035 });
1036 }
1037
1038 fn run(self, builder: &Builder<'_>) -> Self::Output {
1044 let build_compiler = self.build_compiler;
1045 let target = self.target;
1046
1047 if builder.download_rustc() && build_compiler.stage != 0 {
1050 trace!(stage = build_compiler.stage, "`download_rustc` requested");
1051
1052 let sysroot =
1053 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
1054 cp_rustc_component_to_ci_sysroot(
1055 builder,
1056 &sysroot,
1057 builder.config.ci_rustc_dev_contents(),
1058 );
1059 return BuiltRustc { build_compiler };
1060 }
1061
1062 builder.std(build_compiler, target);
1065
1066 if builder.config.keep_stage.contains(&build_compiler.stage) {
1067 trace!(stage = build_compiler.stage, "`keep-stage` requested");
1068
1069 builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1070 builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1071 builder.ensure(RustcLink::from_rustc(self));
1072
1073 return BuiltRustc { build_compiler };
1074 }
1075
1076 let stage = build_compiler.stage + 1;
1078
1079 if build_compiler.stage >= 2
1084 && !builder.config.full_bootstrap
1085 && target == builder.host_target
1086 {
1087 let uplift_build_compiler = builder.compiler(1, build_compiler.host);
1091
1092 let msg = format!("Uplifting rustc from stage2 to stage{stage})");
1093 builder.info(&msg);
1094
1095 builder.ensure(RustcLink::from_build_compiler_and_sysroot(
1099 uplift_build_compiler,
1101 build_compiler,
1103 target,
1104 self.crates,
1105 ));
1106
1107 return BuiltRustc { build_compiler: uplift_build_compiler };
1110 }
1111
1112 builder.std(
1118 builder.compiler(self.build_compiler.stage, builder.config.host_target),
1119 builder.config.host_target,
1120 );
1121
1122 let mut cargo = builder::Cargo::new(
1123 builder,
1124 build_compiler,
1125 Mode::Rustc,
1126 SourceType::InTree,
1127 target,
1128 Kind::Build,
1129 );
1130
1131 rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
1132
1133 for krate in &*self.crates {
1137 cargo.arg("-p").arg(krate);
1138 }
1139
1140 if builder.sess.config.enable_bolt_settings && build_compiler.stage == 1 {
1141 cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1143 }
1144
1145 let _guard = builder.msg(
1146 Kind::Build,
1147 format_args!("compiler artifacts{}", crate_description(&self.crates)),
1148 Mode::Rustc,
1149 build_compiler,
1150 target,
1151 );
1152 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
1153
1154 run_cargo(
1155 builder,
1156 cargo,
1157 vec![],
1158 &stamp,
1159 vec![],
1160 ArtifactKeepMode::Custom(Box::new(|filename| {
1161 if filename.contains("jemalloc_sys")
1162 || filename.contains("rustc_public_bridge")
1163 || filename.contains("rustc_public")
1164 {
1165 if filename.ends_with(".rlib") {
1168 return true;
1169 }
1170 }
1171
1172 filename.ends_with(".rmeta")
1176 })),
1177 );
1178
1179 let target_root_dir = stamp.path().parent().unwrap();
1180 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1186 && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1187 {
1188 let rustc_driver = target_root_dir.join("librustc_driver.so");
1189 strip_debug(builder, target, &rustc_driver);
1190 }
1191
1192 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1193 strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1196 }
1197
1198 builder.ensure(RustcLink::from_rustc(self));
1199 BuiltRustc { build_compiler }
1200 }
1201
1202 fn metadata(&self) -> Option<StepMetadata> {
1203 Some(StepMetadata::build("rustc", self.target).built_by(self.build_compiler))
1204 }
1205}
1206
1207pub fn rustc_cargo(
1208 builder: &Builder<'_>,
1209 cargo: &mut Cargo,
1210 target: TargetSelection,
1211 build_compiler: &Compiler,
1212 crates: &[String],
1213) {
1214 let kind = cargo.kind();
1215 cargo
1216 .arg("--features")
1217 .arg(builder.rustc_features(kind, target, crates))
1218 .arg("--manifest-path")
1219 .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1220
1221 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1222
1223 cargo.rustflag("-Zon-broken-pipe=kill");
1237
1238 if target.is_msvc() {
1243 cargo.rustflag("-Clink-arg=/Brepro");
1244 }
1245
1246 if builder.sess.config.bootstrap_override_lld.is_used() {
1251 cargo.rustflag("-Zdefault-visibility=protected");
1252 }
1253
1254 apply_dylib_lto(builder, build_compiler, cargo);
1255
1256 if builder.config.bootstrap_override_lld.is_used() && !build_compiler.host.is_msvc() {
1264 cargo.rustflag("-Clink-args=-Wl,--icf=all");
1265 }
1266
1267 apply_pgo(builder, cargo, *build_compiler, &builder.config.rust_pgo);
1268
1269 if let Some(ref ccache) = builder.config.ccache
1277 && build_compiler.stage == 0
1278 && !cfg!(windows)
1279 && !builder.config.incremental
1280 {
1281 cargo.env("RUSTC_WRAPPER", ccache);
1282 }
1283
1284 rustc_cargo_env(builder, cargo, target);
1285}
1286
1287fn apply_dylib_lto(builder: &Builder<'_>, build_compiler: &Compiler, cargo: &mut Cargo) {
1288 if is_lto_stage(build_compiler) {
1289 match builder.config.rust_lto {
1290 RustcLto::Thin | RustcLto::Fat => {
1291 cargo.rustflag("-Zdylib-lto");
1294 let lto_type = match builder.config.rust_lto {
1298 RustcLto::Thin => "thin",
1299 RustcLto::Fat => "fat",
1300 _ => unreachable!(),
1301 };
1302 cargo.rustflag(&format!("-Clto={lto_type}"));
1303 cargo.rustflag("-Cembed-bitcode=yes");
1304 }
1305 RustcLto::ThinLocal => { }
1306 RustcLto::Off => {
1307 cargo.rustflag("-Clto=off");
1308 }
1309 }
1310 } else if builder.config.rust_lto == RustcLto::Off {
1311 cargo.rustflag("-Clto=off");
1312 }
1313}
1314
1315fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1316 cargo
1319 .env("CFG_RELEASE", builder.rust_release())
1320 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1321 .env("CFG_VERSION", builder.rust_version());
1322
1323 if builder.config.omit_git_hash {
1327 cargo.env("CFG_OMIT_GIT_HASH", "1");
1328 }
1329
1330 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", builder.config.default_codegen_backend(target).name());
1331
1332 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1333 let target_config = builder.config.target_config.get(&target);
1334
1335 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1336
1337 if let Some(ref ver_date) = builder.rust_info().commit_date() {
1338 cargo.env("CFG_VER_DATE", ver_date);
1339 }
1340 if let Some(ref ver_hash) = builder.rust_info().sha() {
1341 cargo.env("CFG_VER_HASH", ver_hash);
1342 }
1343 if !builder.unstable_features() {
1344 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1345 }
1346
1347 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1350 cargo.env("CFG_DEFAULT_LINKER", s);
1351 } else if let Some(ref s) = builder.config.rustc_default_linker {
1352 cargo.env("CFG_DEFAULT_LINKER", s);
1353 }
1354
1355 if let Some(linker) = target_config.map(|c| c.default_linker_linux_override) {
1357 match linker {
1358 DefaultLinuxLinkerOverride::Off => {}
1359 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1360 cargo.env("CFG_DEFAULT_LINKER_SELF_CONTAINED_LLD_CC", "1");
1361 }
1362 }
1363 }
1364
1365 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1367
1368 if builder.config.rust_verify_llvm_ir {
1369 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1370 }
1371
1372 let nightly = builder.config.channel == "nightly" || builder.config.channel == "dev";
1373 if nightly {
1374 cargo.env("CFG_DEFAULT_POLONIUS_NEXT", "1");
1376 cargo.env("CFG_DEFAULT_NEXT_SOLVER_GLOBALLY", "1");
1377 }
1378
1379 if builder.config.llvm_enabled(target) {
1400 let building_llvm_is_expensive = prebuilt_llvm_output(builder, target).is_none();
1401
1402 let skip_llvm = cargo.kind().is_check_like() && building_llvm_is_expensive;
1403 if skip_llvm {
1404 cargo.env("RUST_CHECK", "1");
1405 } else {
1406 rustc_llvm_env(builder, cargo, target);
1407 }
1408 }
1409
1410 if builder.config.allocator(target) == Allocator::Jemalloc
1412 && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none()
1413 {
1414 if target.starts_with("aarch64") {
1417 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1418 }
1419 else if target.starts_with("loongarch") {
1421 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "14");
1422 }
1423 }
1424}
1425
1426fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1432 let llvm_output = builder.ensure(llvm::Llvm { target });
1433 if builder.config.is_rust_llvm(&llvm_output, target) {
1434 cargo.env("LLVM_RUSTLLVM", "1");
1435 }
1436 if builder.config.llvm_enzyme {
1437 cargo.env("LLVM_ENZYME", "1");
1438 }
1439 if builder.config.llvm_offload {
1440 builder.ensure(llvm::OmpOffload { target });
1441 cargo.env("LLVM_OFFLOAD", "1");
1442 }
1443
1444 cargo.env("LLVM_CONFIG", builder.host_llvm_config());
1446
1447 let mut llvm_linker_flags = String::new();
1457 if builder.config.llvm_pgo.generate_profile.is_some()
1458 && target.is_msvc()
1459 && let Some(ref clang_cl_path) = builder.config.llvm_clang_cl
1460 {
1461 let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1463 llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
1464 }
1465
1466 if let Some(ref s) = builder.config.llvm_ldflags {
1468 if !llvm_linker_flags.is_empty() {
1469 llvm_linker_flags.push(' ');
1470 }
1471 llvm_linker_flags.push_str(s);
1472 }
1473
1474 if !llvm_linker_flags.is_empty() {
1476 cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
1477 }
1478
1479 if builder.config.llvm_static_stdcpp
1482 && !target.contains("freebsd")
1483 && !target.is_msvc()
1484 && !target.contains("apple")
1485 && !target.contains("solaris")
1486 {
1487 let libstdcxx_name =
1488 if target.contains("windows-gnullvm") { "libc++.a" } else { "libstdc++.a" };
1489 let file = compiler_file(
1490 builder,
1491 &builder.cxx(target).unwrap(),
1492 target,
1493 CLang::Cxx,
1494 libstdcxx_name,
1495 );
1496 cargo.env("LLVM_STATIC_STDCPP", file);
1497 }
1498 if llvm_output.link_shared() {
1499 cargo.env("LLVM_LINK_SHARED", "1");
1500 }
1501 if builder.config.llvm_use_libcxx {
1502 cargo.env("LLVM_USE_LIBCXX", "1");
1503 }
1504 if builder.config.llvm_assertions {
1505 cargo.env("LLVM_ASSERTIONS", "1");
1506 }
1507 if builder.cxx_tool(target).is_like_gnu() || builder.cc_tool(target).is_like_gnu() {
1508 cargo.env("LLVM_COMPILER_IS_GNU_LIKE", "1");
1509 }
1510}
1511
1512#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1525struct RustcLink {
1526 build_compiler: Compiler,
1528 sysroot_compiler: Compiler,
1531 target: TargetSelection,
1532 crates: Vec<String>,
1534}
1535
1536impl RustcLink {
1537 fn from_rustc(rustc: Rustc) -> Self {
1540 Self {
1541 build_compiler: rustc.build_compiler,
1542 sysroot_compiler: rustc.build_compiler,
1543 target: rustc.target,
1544 crates: rustc.crates,
1545 }
1546 }
1547
1548 fn from_build_compiler_and_sysroot(
1550 build_compiler: Compiler,
1551 sysroot_compiler: Compiler,
1552 target: TargetSelection,
1553 crates: Vec<String>,
1554 ) -> Self {
1555 Self { build_compiler, sysroot_compiler, target, crates }
1556 }
1557}
1558
1559impl Step for RustcLink {
1560 type Output = ();
1561
1562 fn run(self, builder: &Builder<'_>) {
1564 let build_compiler = self.build_compiler;
1565 let sysroot_compiler = self.sysroot_compiler;
1566 let target = self.target;
1567 add_to_sysroot(
1568 builder,
1569 &builder.sysroot_target_libdir(sysroot_compiler, target),
1570 &builder.sysroot_target_libdir(sysroot_compiler, sysroot_compiler.host),
1571 &build_stamp::librustc_stamp(builder, build_compiler, target),
1572 );
1573 }
1574}
1575
1576#[derive(Clone)]
1582pub struct GccDylibSet {
1583 dylibs: BTreeMap<GccTargetPair, GccOutput>,
1584}
1585
1586impl GccDylibSet {
1587 pub fn build(
1590 builder: &Builder<'_>,
1591 host: TargetSelection,
1592 targets: Vec<TargetSelection>,
1593 ) -> Self {
1594 let dylibs = targets
1595 .iter()
1596 .map(|t| GccTargetPair::for_target_pair(host, *t))
1597 .map(|target_pair| (target_pair, builder.ensure(Gcc { target_pair })))
1598 .collect();
1599 Self { dylibs }
1600 }
1601
1602 pub fn install_to(&self, builder: &Builder<'_>, compiler: Compiler) {
1606 if builder.config.dry_run() {
1607 return;
1608 }
1609
1610 let cg_sysroot = builder.sysroot_codegen_backends(compiler);
1612
1613 for (target_pair, libgccjit) in &self.dylibs {
1614 assert_eq!(
1615 target_pair.host(),
1616 compiler.host,
1617 "Trying to install libgccjit ({target_pair}) to a compiler with a different host ({})",
1618 compiler.host
1619 );
1620 let libgccjit_path = libgccjit.libgccjit();
1621
1622 let libgccjit_path = t!(
1626 libgccjit_path.canonicalize(),
1627 format!("Cannot find libgccjit at {}", libgccjit_path.display())
1628 );
1629
1630 let dst = cg_sysroot.join(libgccjit_path_relative_to_cg_dir(target_pair, libgccjit));
1631 t!(std::fs::create_dir_all(dst.parent().unwrap()));
1632 builder.copy_link(&libgccjit_path, &dst, FileType::NativeLibrary);
1633 }
1634 }
1635}
1636
1637pub fn libgccjit_path_relative_to_cg_dir(
1640 target_pair: &GccTargetPair,
1641 libgccjit: &GccOutput,
1642) -> PathBuf {
1643 let target_filename = libgccjit.libgccjit().file_name().unwrap().to_str().unwrap();
1644
1645 Path::new("lib").join(target_pair.target()).join(target_filename)
1647}
1648
1649#[derive(Clone)]
1653pub struct GccCodegenBackendOutput {
1654 stamp: BuildStamp,
1655}
1656
1657impl GccCodegenBackendOutput {
1658 pub fn stamp(&self) -> &BuildStamp {
1659 &self.stamp
1660 }
1661}
1662
1663#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1670pub struct GccCodegenBackend {
1671 compilers: RustcPrivateCompilers,
1672 target: TargetSelection,
1673}
1674
1675impl GccCodegenBackend {
1676 pub fn for_target(compilers: RustcPrivateCompilers, target: TargetSelection) -> Self {
1678 Self { compilers, target }
1679 }
1680}
1681
1682impl CommandLineStep for GccCodegenBackend {
1683 type Output = GccCodegenBackendOutput;
1684
1685 const IS_HOST: bool = true;
1686
1687 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1688 run.alias("rustc_codegen_gcc").alias("cg_gcc")
1689 }
1690
1691 fn make_run(run: RunConfig<'_>) {
1692 let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target);
1693 run.builder.ensure(GccCodegenBackend::for_target(compilers, run.target));
1694 }
1695
1696 fn run(self, builder: &Builder<'_>) -> Self::Output {
1697 let host = self.compilers.target();
1698 let build_compiler = self.compilers.build_compiler();
1699
1700 let stamp = build_stamp::codegen_backend_stamp(
1701 builder,
1702 build_compiler,
1703 host,
1704 &CodegenBackendKind::Gcc,
1705 );
1706
1707 if builder.config.keep_stage.contains(&build_compiler.stage) && stamp.path().exists() {
1708 trace!("`keep-stage` requested");
1709 builder.info(
1710 "WARNING: Using a potentially old codegen backend. \
1711 This may not behave well.",
1712 );
1713 return GccCodegenBackendOutput { stamp };
1716 }
1717
1718 let mut cargo = builder::Cargo::new(
1719 builder,
1720 build_compiler,
1721 Mode::Codegen,
1722 SourceType::InTree,
1723 host,
1724 Kind::Build,
1725 );
1726 cargo.arg("--manifest-path").arg(builder.src.join("compiler/rustc_codegen_gcc/Cargo.toml"));
1727 apply_dylib_lto(builder, &build_compiler, &mut cargo);
1728
1729 let _guard =
1730 builder.msg(Kind::Build, "codegen backend gcc", Mode::Codegen, build_compiler, host);
1731 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyDylib);
1732
1733 GccCodegenBackendOutput {
1734 stamp: write_codegen_backend_stamp(stamp, files, builder.config.dry_run()),
1735 }
1736 }
1737
1738 fn metadata(&self) -> Option<StepMetadata> {
1739 Some(
1740 StepMetadata::build("rustc_codegen_gcc", self.compilers.target())
1741 .built_by(self.compilers.build_compiler()),
1742 )
1743 }
1744}
1745
1746#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1747pub struct CraneliftCodegenBackend {
1748 pub compilers: RustcPrivateCompilers,
1749}
1750
1751impl CommandLineStep for CraneliftCodegenBackend {
1752 type Output = BuildStamp;
1753 const IS_HOST: bool = true;
1754
1755 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1756 run.alias("rustc_codegen_cranelift").alias("cg_clif")
1757 }
1758
1759 fn make_run(run: RunConfig<'_>) {
1760 run.builder.ensure(CraneliftCodegenBackend {
1761 compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1762 });
1763 }
1764
1765 fn run(self, builder: &Builder<'_>) -> Self::Output {
1766 let target = self.compilers.target();
1767 let build_compiler = self.compilers.build_compiler();
1768
1769 let stamp = build_stamp::codegen_backend_stamp(
1770 builder,
1771 build_compiler,
1772 target,
1773 &CodegenBackendKind::Cranelift,
1774 );
1775
1776 if builder.config.keep_stage.contains(&build_compiler.stage) {
1777 trace!("`keep-stage` requested");
1778 builder.info(
1779 "WARNING: Using a potentially old codegen backend. \
1780 This may not behave well.",
1781 );
1782 return stamp;
1785 }
1786
1787 let mut cargo = builder::Cargo::new(
1788 builder,
1789 build_compiler,
1790 Mode::Codegen,
1791 SourceType::InTree,
1792 target,
1793 Kind::Build,
1794 );
1795 cargo
1796 .arg("--manifest-path")
1797 .arg(builder.src.join("compiler/rustc_codegen_cranelift/Cargo.toml"));
1798 apply_dylib_lto(builder, &build_compiler, &mut cargo);
1799 apply_pgo(builder, &mut cargo, build_compiler, &builder.config.cranelift_pgo);
1800
1801 let _guard = builder.msg(
1802 Kind::Build,
1803 "codegen backend cranelift",
1804 Mode::Codegen,
1805 build_compiler,
1806 target,
1807 );
1808 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyDylib);
1809 write_codegen_backend_stamp(stamp, files, builder.config.dry_run())
1810 }
1811
1812 fn metadata(&self) -> Option<StepMetadata> {
1813 Some(
1814 StepMetadata::build("rustc_codegen_cranelift", self.compilers.target())
1815 .built_by(self.compilers.build_compiler()),
1816 )
1817 }
1818}
1819
1820fn write_codegen_backend_stamp(
1822 mut stamp: BuildStamp,
1823 files: Vec<PathBuf>,
1824 dry_run: bool,
1825) -> BuildStamp {
1826 if dry_run {
1827 return stamp;
1828 }
1829
1830 let mut files = files.into_iter().filter(|f| looks_like_codegen_backend(Path::new(f)));
1831 let codegen_backend = match files.next() {
1832 Some(f) => f,
1833 None => panic!("no dylibs built for codegen backend?"),
1834 };
1835 if let Some(f) = files.next() {
1836 panic!("codegen backend built two dylibs:\n{}\n{}", codegen_backend.display(), f.display());
1837 }
1838
1839 let codegen_backend = codegen_backend.to_str().unwrap();
1840 stamp = stamp.add_stamp(codegen_backend);
1841 t!(stamp.write());
1842 stamp
1843}
1844
1845pub fn looks_like_codegen_backend(path: &Path) -> bool {
1846 is_dylib(path)
1847 && path.file_name().and_then(|p| p.to_str()).is_some_and(|n| n.contains("rustc_codegen_"))
1848}
1849
1850fn copy_codegen_backends_to_sysroot(
1857 builder: &Builder<'_>,
1858 stamp: BuildStamp,
1859 target_compiler: Compiler,
1860) {
1861 let dst = builder.sysroot_codegen_backends(target_compiler);
1870 t!(fs::create_dir_all(&dst), dst);
1871
1872 if builder.config.dry_run() {
1873 return;
1874 }
1875
1876 if stamp.path().exists() {
1877 let file = get_codegen_backend_file(&stamp);
1878 builder.copy_link(
1879 &file,
1880 &dst.join(normalize_codegen_backend_name(builder, &file)),
1881 FileType::NativeLibrary,
1882 );
1883 }
1884}
1885
1886pub fn get_codegen_backend_file(stamp: &BuildStamp) -> PathBuf {
1888 PathBuf::from(t!(fs::read_to_string(stamp.path())))
1889}
1890
1891pub fn normalize_codegen_backend_name(builder: &Builder<'_>, path: &Path) -> String {
1893 let filename = path.file_name().unwrap().to_str().unwrap();
1894 let dash = filename.find('-').unwrap();
1897 let dot = filename.find('.').unwrap();
1898 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1899}
1900
1901pub fn compiler_file(
1902 builder: &Builder<'_>,
1903 compiler: &Path,
1904 target: TargetSelection,
1905 c: CLang,
1906 file: &str,
1907) -> PathBuf {
1908 if builder.config.dry_run() {
1909 return PathBuf::new();
1910 }
1911 let mut cmd = command(compiler);
1912 cmd.args(builder.cc_handled_cflags(target, c));
1913 cmd.args(builder.cc_unhandled_cflags(target, c));
1914 cmd.arg(format!("-print-file-name={file}"));
1915 let out = cmd.run_capture_stdout(builder).stdout();
1916 PathBuf::from(out.trim())
1917}
1918
1919#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1920pub struct Sysroot {
1921 pub compiler: Compiler,
1922 force_recompile: bool,
1924}
1925
1926impl Sysroot {
1927 pub(crate) fn new(compiler: Compiler) -> Self {
1928 Sysroot { compiler, force_recompile: false }
1929 }
1930}
1931
1932impl Step for Sysroot {
1933 type Output = PathBuf;
1934
1935 fn run(self, builder: &Builder<'_>) -> PathBuf {
1939 let compiler = self.compiler;
1940 let host_dir = builder.out.join(compiler.host);
1941
1942 let sysroot_dir = |stage| {
1943 if stage == 0 {
1944 host_dir.join("stage0-sysroot")
1945 } else if self.force_recompile && stage == compiler.stage {
1946 host_dir.join(format!("stage{stage}-test-sysroot"))
1947 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1948 host_dir.join("ci-rustc-sysroot")
1949 } else {
1950 host_dir.join(format!("stage{stage}"))
1951 }
1952 };
1953 let sysroot = sysroot_dir(compiler.stage);
1954 trace!(stage = ?compiler.stage, ?sysroot);
1955
1956 builder.do_if_verbose(|| {
1957 println!("Removing sysroot {} to avoid caching bugs", sysroot.display())
1958 });
1959 let _ = fs::remove_dir_all(&sysroot);
1960 t!(fs::create_dir_all(&sysroot));
1961
1962 if compiler.stage == 0 {
1969 dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1970 }
1971
1972 if builder.download_rustc() && compiler.stage != 0 {
1974 assert_eq!(
1975 builder.config.host_target, compiler.host,
1976 "Cross-compiling is not yet supported with `download-rustc`",
1977 );
1978
1979 for stage in 0..=2 {
1981 if stage != compiler.stage {
1982 let dir = sysroot_dir(stage);
1983 if !dir.ends_with("ci-rustc-sysroot") {
1984 let _ = fs::remove_dir_all(dir);
1985 }
1986 }
1987 }
1988
1989 let mut filtered_files = Vec::new();
2003 let mut add_filtered_files = |suffix, contents| {
2004 for path in contents {
2005 let path = Path::new(&path);
2006 if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
2007 filtered_files.push(path.file_name().unwrap().to_owned());
2008 }
2009 }
2010 };
2011 let suffix = format!("lib/rustlib/{}/lib", compiler.host);
2012 add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
2013 add_filtered_files("lib", builder.config.ci_rust_std_contents());
2016
2017 let filtered_extensions = [
2018 OsStr::new("rmeta"),
2019 OsStr::new("rlib"),
2020 OsStr::new(std::env::consts::DLL_EXTENSION),
2022 ];
2023 let ci_rustc_dir = builder.config.ci_rustc_dir();
2024 builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
2025 if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
2026 return true;
2027 }
2028 if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
2029 return true;
2030 }
2031 filtered_files.iter().all(|f| f != path.file_name().unwrap())
2032 });
2033 }
2034
2035 if compiler.stage != 0 {
2041 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
2042 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
2043 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
2044 if let Err(e) =
2045 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust)
2046 {
2047 eprintln!(
2048 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2049 sysroot_lib_rustlib_src_rust.display(),
2050 builder.src.display(),
2051 e,
2052 );
2053 if builder.config.rust_remap_debuginfo {
2054 eprintln!(
2055 "ERROR: some `tests/ui` tests will fail when lacking `{}`",
2056 sysroot_lib_rustlib_src_rust.display(),
2057 );
2058 }
2059 helpers::exit_process(1);
2060 }
2061 }
2062
2063 if !builder.download_rustc() {
2065 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
2066 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
2067 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
2068 if let Err(e) =
2069 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
2070 {
2071 eprintln!(
2072 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2073 sysroot_lib_rustlib_rustcsrc_rust.display(),
2074 builder.src.display(),
2075 e,
2076 );
2077 helpers::exit_process(1);
2078 }
2079 }
2080
2081 sysroot
2082 }
2083}
2084
2085#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2092pub struct Assemble {
2093 pub target_compiler: Compiler,
2098}
2099
2100impl CommandLineStep for Assemble {
2101 type Output = Compiler;
2102 const IS_HOST: bool = true;
2103
2104 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2105 run.path("compiler/rustc").path("compiler")
2106 }
2107
2108 fn make_run(run: RunConfig<'_>) {
2109 run.builder.ensure(Assemble {
2110 target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2111 });
2112 }
2113
2114 fn run(self, builder: &Builder<'_>) -> Compiler {
2115 let target_compiler = self.target_compiler;
2116
2117 if target_compiler.stage == 0 {
2118 trace!("stage 0 build compiler is always available, simply returning");
2119 assert_eq!(
2120 builder.config.host_target, target_compiler.host,
2121 "Cannot obtain compiler for non-native build triple at stage 0"
2122 );
2123 return target_compiler;
2125 }
2126
2127 let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2130 let libdir_bin = libdir.parent().unwrap().join("bin");
2131 t!(fs::create_dir_all(&libdir_bin));
2132
2133 if builder.config.llvm_enabled(target_compiler.host) {
2134 trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
2135
2136 let target = target_compiler.host;
2137 let llvm_output = builder.ensure(llvm::Llvm { target });
2138 if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
2139 trace!("LLVM tools enabled");
2140
2141 let host_llvm = builder.ensure(llvm::Llvm { target: builder.host_target });
2142 let host_llvm_bin_dir = command(host_llvm.llvm_config())
2143 .arg("--bindir")
2144 .cached()
2145 .run_capture_stdout(builder)
2146 .stdout()
2147 .trim()
2148 .to_string();
2149
2150 let llvm_bin_dir = if target == builder.host_target {
2151 PathBuf::from(host_llvm_bin_dir)
2152 } else {
2153 let external_llvm_config = builder
2156 .config
2157 .target_config
2158 .get(&target)
2159 .and_then(|t| t.llvm_config.clone());
2160 if let Some(external_llvm_config) = external_llvm_config {
2161 external_llvm_config.parent().unwrap().to_path_buf()
2164 } else {
2165 let host_llvm_out = host_llvm.root_dir();
2169 let target_llvm_out = llvm_output.root_dir();
2170 if let Ok(relative_path) =
2171 Path::new(&host_llvm_bin_dir).strip_prefix(host_llvm_out)
2172 {
2173 target_llvm_out.join(relative_path)
2174 } else {
2175 PathBuf::from(
2178 host_llvm_bin_dir
2179 .replace(&*builder.host_target.triple, &target.triple),
2180 )
2181 }
2182 }
2183 };
2184
2185 #[cfg(feature = "tracing")]
2192 let _llvm_tools_span =
2193 span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
2194 .entered();
2195 for tool in dist::LLVM_TOOLS {
2196 trace!("installing `{tool}`");
2197 let tool_exe = exe(tool, target_compiler.host);
2198 let src_path = llvm_bin_dir.join(&tool_exe);
2199
2200 if !src_path.exists() {
2201 if llvm_output.kind() == LlvmKind::DownloadedFromCi {
2203 eprintln!("{} does not exist; skipping copy", src_path.display());
2204 continue;
2205 }
2206 if *tool == "llubi" {
2209 continue;
2210 }
2211 }
2212
2213 builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2220 }
2221 }
2222 }
2223
2224 let maybe_install_llvm_bitcode_linker = || {
2225 if builder.config.llvm_bitcode_linker_enabled {
2226 trace!("llvm-bitcode-linker enabled, installing");
2227 let llvm_bitcode_linker = builder.ensure(
2228 crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler(
2229 builder,
2230 target_compiler,
2231 ),
2232 );
2233
2234 let bindir_self_contained = builder
2236 .sysroot(target_compiler)
2237 .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host));
2238 let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2239
2240 t!(fs::create_dir_all(&bindir_self_contained));
2241 builder.copy_link(
2242 &llvm_bitcode_linker.tool_path,
2243 &bindir_self_contained.join(tool_exe),
2244 FileType::Executable,
2245 );
2246 }
2247 };
2248
2249 if builder.download_rustc() {
2251 trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2252
2253 builder.std(target_compiler, target_compiler.host);
2254 let sysroot =
2255 builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2256 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2259 if target_compiler.stage == builder.top_stage {
2261 builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage));
2262 }
2263
2264 maybe_install_llvm_bitcode_linker();
2267
2268 return target_compiler;
2269 }
2270
2271 debug!(
2285 "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2286 target_compiler.stage - 1,
2287 builder.config.host_target,
2288 );
2289 let build_compiler =
2290 builder.compiler(target_compiler.stage - 1, builder.config.host_target);
2291
2292 if builder.config.llvm_enzyme {
2294 debug!("`llvm_enzyme` requested");
2295 let enzyme = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2296 let target_libdir =
2297 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2298 let target_dst_lib = target_libdir.join(enzyme.enzyme_filename());
2299 builder.copy_link(&enzyme.enzyme_path(), &target_dst_lib, FileType::NativeLibrary);
2300 }
2301
2302 if builder.config.llvm_offload && !builder.config.dry_run() {
2303 debug!("`llvm_offload` requested");
2304 if builder.is_llvm_enabled_for(builder.config.host_target) {
2305 let rust_offload =
2306 builder.ensure(llvm::RustOffload { target: build_compiler.host });
2307 let target_libdir =
2308 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2309 let rust_offload_dst_lib = target_libdir.join(rust_offload.rust_offload_filename());
2310 builder.copy_link(
2311 &rust_offload.rust_offload_path(),
2312 &rust_offload_dst_lib,
2313 FileType::NativeLibrary,
2314 );
2315
2316 let omp_offload = builder.ensure(llvm::OmpOffload { target: build_compiler.host });
2317 for p in omp_offload.artifact_paths_with_symlink_targets() {
2318 let libname = p.file_name().unwrap();
2319 let dst_lib = target_libdir.join(libname);
2320 builder.resolve_symlink_and_copy(&p, &dst_lib);
2321 }
2322 }
2323 }
2324
2325 debug!(
2328 ?build_compiler,
2329 "target_compiler.host" = ?target_compiler.host,
2330 "building compiler libraries to link to"
2331 );
2332
2333 let BuiltRustc { build_compiler } =
2335 builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2336
2337 let stage = target_compiler.stage;
2338 let host = target_compiler.host;
2339 let (host_info, dir_name) = if build_compiler.host == host {
2340 ("".into(), "host".into())
2341 } else {
2342 (format!(" ({host})"), host.to_string())
2343 };
2344 let msg = format!(
2349 "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2350 );
2351 builder.info(&msg);
2352
2353 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2355 let proc_macros = builder
2356 .read_stamp_file(&stamp)
2357 .into_iter()
2358 .filter_map(|(path, dependency_type)| {
2359 if dependency_type == DependencyType::Host {
2360 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2361 } else {
2362 None
2363 }
2364 })
2365 .collect::<HashSet<_>>();
2366
2367 let sysroot = builder.sysroot(target_compiler);
2368 let rustc_libdir = builder.rustc_libdir(target_compiler);
2369 t!(fs::create_dir_all(&rustc_libdir));
2370 let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2371 for f in builder.read_dir(&src_libdir) {
2372 let filename = f.file_name().into_string().unwrap();
2373
2374 let is_proc_macro = proc_macros.contains(&filename);
2375 let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2376
2377 let can_be_rustc_dynamic_dep =
2379 !(filename.starts_with("std-") || filename.starts_with("libstd-"));
2380
2381 if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2382 builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2383 }
2384 }
2385
2386 {
2387 #[cfg(feature = "tracing")]
2388 let _codegen_backend_span =
2389 span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2390
2391 for backend in builder.config.enabled_codegen_backends(target_compiler.host) {
2392 if builder.kind == Kind::Check && builder.top_stage == 1 {
2409 continue;
2410 }
2411
2412 let prepare_compilers = || {
2413 RustcPrivateCompilers::from_build_and_target_compiler(
2414 build_compiler,
2415 target_compiler,
2416 )
2417 };
2418
2419 match backend {
2420 CodegenBackendKind::Cranelift => {
2421 let stamp = builder
2422 .ensure(CraneliftCodegenBackend { compilers: prepare_compilers() });
2423 copy_codegen_backends_to_sysroot(builder, stamp, target_compiler);
2424 }
2425 CodegenBackendKind::Gcc => {
2426 let compilers = prepare_compilers();
2459 let cg_gcc = builder
2460 .ensure(GccCodegenBackend::for_target(compilers, target_compiler.host));
2461 copy_codegen_backends_to_sysroot(builder, cg_gcc.stamp, target_compiler);
2462
2463 let mut targets = HashSet::new();
2470 for target in &builder.hosts {
2473 targets.insert(*target);
2474 }
2475 for target in &builder.targets {
2477 targets.insert(*target);
2478 }
2479 targets.insert(compilers.target_compiler().host);
2482
2483 let dylib_set = GccDylibSet::build(
2485 builder,
2486 compilers.target_compiler().host,
2487 targets.into_iter().collect(),
2488 );
2489
2490 dylib_set.install_to(builder, target_compiler);
2493 }
2494 CodegenBackendKind::Llvm | CodegenBackendKind::Custom(_) => continue,
2495 }
2496 }
2497 }
2498
2499 if builder.config.lld_enabled {
2500 let lld_wrapper =
2501 builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler(
2502 builder,
2503 target_compiler,
2504 ));
2505 copy_lld_artifacts(builder, lld_wrapper, target_compiler);
2506 }
2507
2508 if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2509 debug!(
2510 "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2511 workaround faulty homebrew `strip`s"
2512 );
2513
2514 let src_exe = exe("llvm-objcopy", target_compiler.host);
2521 let dst_exe = exe("rust-objcopy", target_compiler.host);
2522 builder.copy_link(
2523 &libdir_bin.join(src_exe),
2524 &libdir_bin.join(dst_exe),
2525 FileType::Executable,
2526 );
2527 }
2528
2529 if builder.tool_enabled("wasm-component-ld") {
2533 let wasm_component = builder.ensure(
2534 crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler(
2535 builder,
2536 target_compiler,
2537 ),
2538 );
2539 builder.copy_link(
2540 &wasm_component.tool_path,
2541 &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2542 FileType::Executable,
2543 );
2544 }
2545
2546 maybe_install_llvm_bitcode_linker();
2547
2548 debug!(
2551 "target_compiler.host" = ?target_compiler.host,
2552 ?sysroot,
2553 "ensuring availability of `libLLVM.so` in compiler directory"
2554 );
2555 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2556 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2557
2558 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2560 let rustc = out_dir.join(exe("rustc-main", host));
2561 let bindir = sysroot.join("bin");
2562 t!(fs::create_dir_all(bindir));
2563 let compiler = builder.rustc(target_compiler);
2564 debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2565 builder.copy_link(&rustc, &compiler, FileType::Executable);
2566
2567 target_compiler
2568 }
2569}
2570
2571#[track_caller]
2576pub fn add_to_sysroot(
2577 builder: &Builder<'_>,
2578 sysroot_dst: &Path,
2579 sysroot_host_dst: &Path,
2580 stamp: &BuildStamp,
2581) {
2582 let self_contained_dst = &sysroot_dst.join("self-contained");
2583 t!(fs::create_dir_all(sysroot_dst));
2584 t!(fs::create_dir_all(sysroot_host_dst));
2585 t!(fs::create_dir_all(self_contained_dst));
2586
2587 let mut crates = HashMap::new();
2588 for (path, dependency_type) in builder.read_stamp_file(stamp) {
2589 let filename = path.file_name().unwrap().to_str().unwrap();
2590 let dst = match dependency_type {
2591 DependencyType::Host => {
2592 if sysroot_dst == sysroot_host_dst {
2593 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2596 }
2597
2598 sysroot_host_dst
2599 }
2600 DependencyType::Target => {
2601 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2604
2605 sysroot_dst
2606 }
2607 DependencyType::TargetSelfContained => self_contained_dst,
2608 };
2609 builder.copy_link(&path, &dst.join(filename), FileType::Regular);
2610 }
2611
2612 let mut seen_crates = HashMap::new();
2618 for (filestem, path) in crates {
2619 if !filestem.contains("rustc_") || filestem.contains("rustc_hash") {
2620 continue;
2621 }
2622 if let Some(other_path) =
2623 seen_crates.insert(filestem.split_once('-').unwrap().0.to_owned(), path.clone())
2624 {
2625 panic!(
2626 "duplicate rustc crate {}\n- first copy at {}\n- second copy at {}",
2627 filestem.split_once('-').unwrap().0.to_owned(),
2628 other_path.display(),
2629 path.display(),
2630 );
2631 }
2632 }
2633}
2634
2635pub enum ArtifactKeepMode {
2639 OnlyDylib,
2641 OnlyRmeta,
2643 BothRlibAndRmeta,
2645 Custom(Box<dyn Fn(&str) -> bool>),
2648}
2649
2650pub fn run_cargo(
2651 builder: &Builder<'_>,
2652 cargo: Cargo,
2653 tail_args: Vec<String>,
2654 stamp: &BuildStamp,
2655 additional_target_deps: Vec<(PathBuf, DependencyType)>,
2656 artifact_keep_mode: ArtifactKeepMode,
2657) -> Vec<PathBuf> {
2658 let target_root_dir = stamp.path().parent().unwrap();
2660 let target_build_dir = target_root_dir.join("build");
2662 let host_root_dir = target_root_dir
2664 .parent()
2665 .unwrap() .parent()
2667 .unwrap() .join(target_root_dir.file_name().unwrap());
2669
2670 let mut deps = Vec::new();
2674 let mut toplevel = Vec::new();
2675 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2676 let (filenames_vec, crate_types) = match msg {
2677 CargoMessage::CompilerArtifact {
2678 filenames,
2679 target: CargoTarget { crate_types, .. },
2680 ..
2681 } => {
2682 let mut f: Vec<String> = filenames.into_iter().map(|s| s.into_owned()).collect();
2683 f.sort(); (f, crate_types)
2685 }
2686 _ => return,
2687 };
2688 for filename in filenames_vec {
2689 let keep = if filename.ends_with(".lib")
2691 || filename.ends_with(".a")
2692 || is_debug_info(&filename)
2693 || is_dylib(Path::new(&*filename))
2694 {
2695 true
2697 } else {
2698 match &artifact_keep_mode {
2699 ArtifactKeepMode::OnlyDylib => false,
2700 ArtifactKeepMode::OnlyRmeta => filename.ends_with(".rmeta"),
2701 ArtifactKeepMode::BothRlibAndRmeta => {
2702 filename.ends_with(".rmeta") || filename.ends_with(".rlib")
2703 }
2704 ArtifactKeepMode::Custom(func) => func(&filename),
2705 }
2706 };
2707
2708 if !keep {
2709 continue;
2710 }
2711
2712 let filename = Path::new(&*filename);
2713
2714 if filename.starts_with(&host_root_dir) {
2717 if crate_types.iter().any(|t| t == "proc-macro") {
2719 if filename.file_name().unwrap().to_str().unwrap().contains("-") {
2724 deps.push((filename.to_path_buf(), DependencyType::Host));
2725 }
2726 }
2727 continue;
2728 }
2729
2730 if filename.starts_with(&target_build_dir) {
2733 deps.push((filename.to_path_buf(), DependencyType::Target));
2734 continue;
2735 }
2736
2737 let expected_len = t!(filename.metadata()).len();
2748 let filename = filename.file_name().unwrap().to_str().unwrap();
2749 let mut parts = filename.splitn(2, '.');
2750 let file_stem = parts.next().unwrap().to_owned();
2751 let extension = parts.next().unwrap().to_owned();
2752
2753 toplevel.push((file_stem, extension, expected_len));
2754 }
2755 });
2756
2757 if !ok {
2758 helpers::exit_process(1);
2759 }
2760
2761 if builder.config.dry_run() {
2762 return Vec::new();
2763 }
2764
2765 let read_dir = |path: &Path| path.read_dir().ok().into_iter().flatten().filter_map(Result::ok);
2772 let contents = target_build_dir
2773 .read_dir()
2774 .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_build_dir.display(), e))
2775 .map(|e| e.unwrap())
2776 .flat_map(|e| read_dir(&e.path()))
2777 .flat_map(|e| read_dir(&e.path()))
2778 .flat_map(|e| read_dir(&e.path()))
2779 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2780 .collect::<Vec<_>>();
2781 for (prefix, extension, expected_len) in toplevel {
2782 let candidates = contents.iter().filter(|&(_, filename, meta)| {
2783 meta.len() == expected_len
2784 && filename
2785 .strip_prefix(&prefix[..])
2786 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2787 .unwrap_or(false)
2788 });
2789 let max = candidates.max_by_key(|&(_, _, metadata)| {
2790 metadata.modified().expect("mtime should be available on all relevant OSes")
2791 });
2792 let path_to_add = match max {
2793 Some(triple) => triple.0.to_str().unwrap(),
2794 None => panic!("no output generated for {prefix:?} {extension:?}"),
2795 };
2796 if is_dylib(Path::new(path_to_add)) {
2797 let candidate = format!("{path_to_add}.lib");
2798 let candidate = PathBuf::from(candidate);
2799 if candidate.exists() {
2800 deps.push((candidate, DependencyType::Target));
2801 }
2802 }
2803 deps.push((path_to_add.into(), DependencyType::Target));
2804 }
2805
2806 deps.extend(additional_target_deps);
2807 deps.sort();
2808 let mut new_contents = Vec::new();
2809 for (dep, dependency_type) in deps.iter() {
2810 new_contents.extend(match *dependency_type {
2811 DependencyType::Host => b"h",
2812 DependencyType::Target => b"t",
2813 DependencyType::TargetSelfContained => b"s",
2814 });
2815 new_contents.extend(dep.to_str().unwrap().as_bytes());
2816 new_contents.extend(b"\0");
2817 }
2818 t!(fs::write(stamp.path(), &new_contents));
2819 deps.into_iter().map(|(d, _)| d).collect()
2820}
2821
2822pub fn stream_cargo(
2823 builder: &Builder<'_>,
2824 cargo: Cargo,
2825 tail_args: Vec<String>,
2826 cb: &mut dyn FnMut(CargoMessage<'_>),
2827) -> bool {
2828 let mut cmd = cargo.into_cmd();
2829
2830 let mut message_format = if builder.config.json_output {
2833 String::from("json")
2834 } else {
2835 String::from("json-render-diagnostics")
2836 };
2837 if let Some(s) = &builder.config.rustc_error_format {
2838 message_format.push_str(",json-diagnostic-");
2839 message_format.push_str(s);
2840 }
2841 cmd.arg("--message-format").arg(message_format);
2842
2843 for arg in tail_args {
2844 cmd.arg(arg);
2845 }
2846
2847 builder.do_if_verbose(|| println!("running: {cmd:?}"));
2848
2849 let streaming_command = cmd.stream_capture_stdout(&builder.config.exec_ctx);
2850
2851 let Some(mut streaming_command) = streaming_command else {
2852 return true;
2853 };
2854
2855 let stdout = BufReader::new(streaming_command.stdout.take().unwrap());
2859 for line in stdout.lines() {
2860 let line = t!(line);
2861 match serde_json::from_str::<CargoMessage<'_>>(&line) {
2862 Ok(msg) => {
2863 if builder.config.json_output {
2864 println!("{line}");
2866 }
2867 cb(msg)
2868 }
2869 Err(_) => println!("{line}"),
2871 }
2872 }
2873
2874 let status = t!(streaming_command.wait(&builder.config.exec_ctx));
2876 if builder.is_verbose() && !status.success() {
2877 eprintln!(
2878 "command did not execute successfully: {cmd:?}\n\
2879 expected success, got: {status}"
2880 );
2881 }
2882
2883 status.success()
2884}
2885
2886#[derive(Deserialize, Debug)]
2887pub struct CargoTarget<'a> {
2888 pub crate_types: Vec<Cow<'a, str>>,
2889 #[serde(default)]
2890 pub doc: bool,
2891}
2892
2893#[derive(Deserialize, Debug)]
2894#[serde(tag = "reason", rename_all = "kebab-case")]
2895pub enum CargoMessage<'a> {
2896 CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2897 BuildScriptExecuted,
2898 BuildFinished,
2899}
2900
2901pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2902 if target != "x86_64-unknown-linux-gnu"
2906 || !builder.config.is_host_target(target)
2907 || !path.exists()
2908 {
2909 return;
2910 }
2911
2912 let previous_mtime = t!(t!(path.metadata()).modified());
2913 let stamp = BuildStamp::new(path.parent().unwrap())
2914 .with_prefix(path.file_name().unwrap().to_str().unwrap())
2915 .with_prefix("strip")
2916 .add_stamp(previous_mtime.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos());
2917
2918 if !stamp.is_up_to_date() {
2921 command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2922 }
2923 t!(stamp.write());
2924
2925 let file = t!(fs::File::open(path));
2926
2927 t!(file.set_modified(previous_mtime));
2940}
2941
2942pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2944 build_compiler.stage != 0
2945}