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::build_steps::gcc::{Gcc, GccOutput, GccTargetPair};
23use crate::core::build_steps::tool::{RustcPrivateCompilers, SourceType, copy_lld_artifacts};
24use crate::core::build_steps::{dist, llvm};
25use crate::core::builder;
26use crate::core::builder::{
27 Builder, Cargo, Kind, RunConfig, ShouldRun, Step, StepMetadata, crate_description,
28};
29use crate::core::config::toml::target::DefaultLinuxLinkerOverride;
30use crate::core::config::{
31 CompilerBuiltins, DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection,
32};
33use crate::utils::build_stamp;
34use crate::utils::build_stamp::BuildStamp;
35use crate::utils::exec::command;
36use crate::utils::helpers::{
37 exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date,
38};
39use crate::{
40 CLang, CodegenBackendKind, Compiler, DependencyType, FileType, GitRepo, LLVM_TOOLS, Mode,
41 debug, trace,
42};
43
44#[derive(Debug, Clone, PartialEq, Eq, Hash)]
46pub struct Std {
47 pub target: TargetSelection,
48 pub build_compiler: Compiler,
50 crates: Vec<String>,
54 force_recompile: bool,
57 extra_rust_args: &'static [&'static str],
58 is_for_mir_opt_tests: bool,
59}
60
61impl Std {
62 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
63 Self {
64 target,
65 build_compiler,
66 crates: Default::default(),
67 force_recompile: false,
68 extra_rust_args: &[],
69 is_for_mir_opt_tests: false,
70 }
71 }
72
73 pub fn force_recompile(mut self, force_recompile: bool) -> Self {
74 self.force_recompile = force_recompile;
75 self
76 }
77
78 #[expect(clippy::wrong_self_convention)]
79 pub fn is_for_mir_opt_tests(mut self, is_for_mir_opt_tests: bool) -> Self {
80 self.is_for_mir_opt_tests = is_for_mir_opt_tests;
81 self
82 }
83
84 pub fn extra_rust_args(mut self, extra_rust_args: &'static [&'static str]) -> Self {
85 self.extra_rust_args = extra_rust_args;
86 self
87 }
88
89 fn copy_extra_objects(
90 &self,
91 builder: &Builder<'_>,
92 compiler: &Compiler,
93 target: TargetSelection,
94 ) -> Vec<(PathBuf, DependencyType)> {
95 let mut deps = Vec::new();
96 if !self.is_for_mir_opt_tests {
97 deps.extend(copy_third_party_objects(builder, compiler, target));
98 deps.extend(copy_self_contained_objects(builder, compiler, target));
99 }
100 deps
101 }
102
103 pub fn should_be_uplifted_from_stage_1(builder: &Builder<'_>, stage: u32) -> bool {
108 stage > 1 && !builder.config.full_bootstrap
109 }
110}
111
112impl Step for Std {
113 type Output = Option<BuildStamp>;
115
116 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
117 run.crate_or_deps("sysroot").path("library")
118 }
119
120 fn is_default_step(_builder: &Builder<'_>) -> bool {
121 true
122 }
123
124 fn make_run(run: RunConfig<'_>) {
125 let crates = std_crates_for_run_make(&run);
126 let builder = run.builder;
127
128 let force_recompile = builder.rust_info().is_managed_git_subrepository()
132 && builder.download_rustc()
133 && builder.config.has_changes_from_upstream(&["library"]);
134
135 trace!("is managed git repo: {}", builder.rust_info().is_managed_git_subrepository());
136 trace!("download_rustc: {}", builder.download_rustc());
137 trace!(force_recompile);
138
139 run.builder.ensure(Std {
140 build_compiler: run.builder.compiler(run.builder.top_stage, builder.host_target),
143 target: run.target,
144 crates,
145 force_recompile,
146 extra_rust_args: &[],
147 is_for_mir_opt_tests: false,
148 });
149 }
150
151 fn run(self, builder: &Builder<'_>) -> Self::Output {
157 let target = self.target;
158
159 if self.build_compiler.stage == 0
164 && !(builder.local_rebuild && target != builder.host_target)
165 {
166 let compiler = self.build_compiler;
167 builder.ensure(StdLink::from_std(self, compiler));
168
169 return None;
170 }
171
172 let build_compiler = if builder.download_rustc() && self.force_recompile {
173 builder
176 .compiler(self.build_compiler.stage.saturating_sub(1), builder.config.host_target)
177 } else {
178 self.build_compiler
179 };
180
181 if builder.download_rustc()
184 && builder.config.is_host_target(target)
185 && !self.force_recompile
186 {
187 let sysroot =
188 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
189 cp_rustc_component_to_ci_sysroot(
190 builder,
191 &sysroot,
192 builder.config.ci_rust_std_contents(),
193 );
194 return None;
195 }
196
197 if builder.config.keep_stage.contains(&build_compiler.stage)
198 || builder.config.keep_stage_std.contains(&build_compiler.stage)
199 {
200 trace!(keep_stage = ?builder.config.keep_stage);
201 trace!(keep_stage_std = ?builder.config.keep_stage_std);
202
203 builder.info("WARNING: Using a potentially old libstd. This may not behave well.");
204
205 builder.ensure(StartupObjects { compiler: build_compiler, target });
206
207 self.copy_extra_objects(builder, &build_compiler, target);
208
209 builder.ensure(StdLink::from_std(self, build_compiler));
210 return Some(build_stamp::libstd_stamp(builder, build_compiler, target));
211 }
212
213 let mut target_deps = builder.ensure(StartupObjects { compiler: build_compiler, target });
214
215 let stage = build_compiler.stage;
217
218 if Self::should_be_uplifted_from_stage_1(builder, build_compiler.stage) {
219 let build_compiler_for_std_to_uplift = builder.compiler(1, builder.host_target);
220 let stage_1_stamp = builder.std(build_compiler_for_std_to_uplift, target);
221
222 let msg = if build_compiler_for_std_to_uplift.host == target {
223 format!(
224 "Uplifting library (stage{} -> stage{stage})",
225 build_compiler_for_std_to_uplift.stage
226 )
227 } else {
228 format!(
229 "Uplifting library (stage{}:{} -> stage{stage}:{target})",
230 build_compiler_for_std_to_uplift.stage, build_compiler_for_std_to_uplift.host,
231 )
232 };
233
234 builder.info(&msg);
235
236 self.copy_extra_objects(builder, &build_compiler, target);
239
240 builder.ensure(StdLink::from_std(self, build_compiler_for_std_to_uplift));
241 return stage_1_stamp;
242 }
243
244 target_deps.extend(self.copy_extra_objects(builder, &build_compiler, target));
245
246 let mut cargo = if self.is_for_mir_opt_tests {
250 trace!("building special sysroot for mir-opt tests");
251 let mut cargo = builder::Cargo::new_for_mir_opt_tests(
252 builder,
253 build_compiler,
254 Mode::Std,
255 SourceType::InTree,
256 target,
257 Kind::Check,
258 );
259 cargo.rustflag("-Zalways-encode-mir");
260 cargo.arg("--manifest-path").arg(builder.src.join("library/sysroot/Cargo.toml"));
261 cargo
262 } else {
263 trace!("building regular sysroot");
264 let mut cargo = builder::Cargo::new(
265 builder,
266 build_compiler,
267 Mode::Std,
268 SourceType::InTree,
269 target,
270 Kind::Build,
271 );
272 std_cargo(builder, target, &mut cargo, &self.crates);
273 cargo
274 };
275
276 if target.is_synthetic() {
278 cargo.env("RUSTC_BOOTSTRAP_SYNTHETIC_TARGET", "1");
279 }
280 for rustflag in self.extra_rust_args.iter() {
281 cargo.rustflag(rustflag);
282 }
283
284 let _guard = builder.msg(
285 Kind::Build,
286 format_args!("library artifacts{}", crate_description(&self.crates)),
287 Mode::Std,
288 build_compiler,
289 target,
290 );
291
292 let stamp = build_stamp::libstd_stamp(builder, build_compiler, target);
293 run_cargo(
294 builder,
295 cargo,
296 vec![],
297 &stamp,
298 target_deps,
299 if self.is_for_mir_opt_tests {
300 ArtifactKeepMode::OnlyRmeta
301 } else {
302 ArtifactKeepMode::BothRlibAndRmeta
304 },
305 );
306
307 builder.ensure(StdLink::from_std(
308 self,
309 builder.compiler(build_compiler.stage, builder.config.host_target),
310 ));
311 Some(stamp)
312 }
313
314 fn metadata(&self) -> Option<StepMetadata> {
315 Some(StepMetadata::build("std", self.target).built_by(self.build_compiler))
316 }
317}
318
319fn copy_and_stamp(
320 builder: &Builder<'_>,
321 libdir: &Path,
322 sourcedir: &Path,
323 name: &str,
324 target_deps: &mut Vec<(PathBuf, DependencyType)>,
325 dependency_type: DependencyType,
326) {
327 let target = libdir.join(name);
328 builder.copy_link(&sourcedir.join(name), &target, FileType::Regular);
329
330 target_deps.push((target, dependency_type));
331}
332
333fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
334 let libunwind_path = builder.ensure(llvm::Libunwind { target });
335 let libunwind_source = libunwind_path.join("libunwind.a");
336 let libunwind_target = libdir.join("libunwind.a");
337 builder.copy_link(&libunwind_source, &libunwind_target, FileType::NativeLibrary);
338 libunwind_target
339}
340
341fn copy_third_party_objects(
343 builder: &Builder<'_>,
344 compiler: &Compiler,
345 target: TargetSelection,
346) -> Vec<(PathBuf, DependencyType)> {
347 let mut target_deps = vec![];
348
349 if builder.config.needs_sanitizer_runtime_built(target) && compiler.stage != 0 {
350 target_deps.extend(
353 copy_sanitizers(builder, compiler, target)
354 .into_iter()
355 .map(|d| (d, DependencyType::Target)),
356 );
357 }
358
359 if target == "x86_64-fortanix-unknown-sgx"
360 || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
361 && (target.contains("linux")
362 || target.contains("fuchsia")
363 || target.contains("aix")
364 || target.contains("hexagon"))
365 {
366 let libunwind_path =
367 copy_llvm_libunwind(builder, target, &builder.sysroot_target_libdir(*compiler, target));
368 target_deps.push((libunwind_path, DependencyType::Target));
369 }
370
371 target_deps
372}
373
374fn copy_self_contained_objects(
376 builder: &Builder<'_>,
377 compiler: &Compiler,
378 target: TargetSelection,
379) -> Vec<(PathBuf, DependencyType)> {
380 let libdir_self_contained =
381 builder.sysroot_target_libdir(*compiler, target).join("self-contained");
382 t!(fs::create_dir_all(&libdir_self_contained));
383 let mut target_deps = vec![];
384
385 if target.needs_crt_begin_end() {
393 let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
394 panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
395 });
396 if !target.starts_with("wasm32") {
397 for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
398 copy_and_stamp(
399 builder,
400 &libdir_self_contained,
401 &srcdir,
402 obj,
403 &mut target_deps,
404 DependencyType::TargetSelfContained,
405 );
406 }
407 let crt_path = builder.ensure(llvm::CrtBeginEnd { target });
408 for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
409 let src = crt_path.join(obj);
410 let target = libdir_self_contained.join(obj);
411 builder.copy_link(&src, &target, FileType::NativeLibrary);
412 target_deps.push((target, DependencyType::TargetSelfContained));
413 }
414 } else {
415 for &obj in &["libc.a", "crt1-command.o"] {
418 copy_and_stamp(
419 builder,
420 &libdir_self_contained,
421 &srcdir,
422 obj,
423 &mut target_deps,
424 DependencyType::TargetSelfContained,
425 );
426 }
427 }
428 if !target.starts_with("s390x") {
429 let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
430 target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
431 }
432 } else if target.contains("-wasi") {
433 let srcdir = builder.wasi_libdir(target).unwrap_or_else(|| {
434 panic!(
435 "Target {:?} does not have a \"wasi-root\" key in bootstrap.toml \
436 or `$WASI_SDK_PATH` set",
437 target.triple
438 )
439 });
440
441 let srcdir = if target == "wasm32-wasip3" {
445 assert!(!srcdir.exists(), "wasip3 support is in wasi-libc, this should be updated now");
446 builder.wasi_libdir(TargetSelection::from_user("wasm32-wasip2")).unwrap()
447 } else {
448 srcdir
449 };
450 for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
451 copy_and_stamp(
452 builder,
453 &libdir_self_contained,
454 &srcdir,
455 obj,
456 &mut target_deps,
457 DependencyType::TargetSelfContained,
458 );
459 }
460 } else if target.is_windows_gnu() || target.is_windows_gnullvm() {
461 for obj in ["crt2.o", "dllcrt2.o"].iter() {
462 let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
463 let dst = libdir_self_contained.join(obj);
464 builder.copy_link(&src, &dst, FileType::NativeLibrary);
465 target_deps.push((dst, DependencyType::TargetSelfContained));
466 }
467 }
468
469 target_deps
470}
471
472pub fn std_crates_for_run_make(run: &RunConfig<'_>) -> Vec<String> {
475 let mut crates = run.make_run_crates(builder::Alias::Library);
476
477 let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
486 if target_is_no_std {
487 crates.retain(|c| c == "core" || c == "alloc");
488 }
489 crates
490}
491
492fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
498 if builder.config.llvm_from_ci {
500 builder.config.maybe_download_ci_llvm();
502 let ci_llvm_compiler_rt = builder.config.ci_llvm_root().join("compiler-rt");
503 if ci_llvm_compiler_rt.exists() {
504 return ci_llvm_compiler_rt;
505 }
506 }
507
508 builder.require_submodule("src/llvm-project", {
510 Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
511 });
512 builder.src.join("src/llvm-project/compiler-rt")
513}
514
515pub fn std_cargo(
518 builder: &Builder<'_>,
519 target: TargetSelection,
520 cargo: &mut Cargo,
521 crates: &[String],
522) {
523 if target.contains("apple") && !builder.config.dry_run() {
541 let mut cmd = builder.rustc_cmd(cargo.compiler());
545 cmd.arg("--target").arg(target.rustc_target_arg());
546 cmd.arg("--print=deployment-target");
547 let output = cmd.run_capture_stdout(builder).stdout();
548
549 let (env_var, value) = output.split_once('=').unwrap();
550 cargo.env(env_var.trim(), value.trim());
553
554 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
564 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
565 }
566 }
567
568 if let Some(path) = builder.config.profiler_path(target) {
570 cargo.env("LLVM_PROFILER_RT_LIB", path);
571 } else if builder.config.profiler_enabled(target) {
572 let compiler_rt = compiler_rt_for_profiler(builder);
573 cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
577 }
578
579 let compiler_builtins_c_feature = match builder.config.optimized_compiler_builtins(target) {
593 CompilerBuiltins::LinkLLVMBuiltinsLib(path) => {
594 cargo.env("LLVM_COMPILER_RT_LIB", path);
595 " compiler-builtins-c"
596 }
597 CompilerBuiltins::BuildLLVMFuncs => {
598 builder.require_submodule(
608 "src/llvm-project",
609 Some(
610 "The `build.optimized-compiler-builtins` config option \
611 requires `compiler-rt` sources from LLVM.",
612 ),
613 );
614 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
615 if !builder.config.dry_run() {
616 assert!(compiler_builtins_root.exists());
619 }
620
621 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
624 " compiler-builtins-c"
625 }
626 CompilerBuiltins::BuildRustOnly => "",
627 };
628
629 for krate in crates {
630 cargo.args(["-p", krate]);
631 }
632
633 let mut features = String::new();
634
635 if builder.no_std(target) == Some(true) {
636 features += " compiler-builtins-mem";
637 if !target.starts_with("bpf") {
638 features.push_str(compiler_builtins_c_feature);
639 }
640
641 if crates.is_empty() {
643 cargo.args(["-p", "alloc"]);
644 }
645 cargo
646 .arg("--manifest-path")
647 .arg(builder.src.join("library/alloc/Cargo.toml"))
648 .arg("--features")
649 .arg(features);
650 } else {
651 features += &builder.std_features(target);
652 features.push_str(compiler_builtins_c_feature);
653
654 cargo
655 .arg("--features")
656 .arg(features)
657 .arg("--manifest-path")
658 .arg(builder.src.join("library/sysroot/Cargo.toml"));
659
660 if target.contains("musl")
663 && let Some(p) = builder.musl_libdir(target)
664 {
665 let root = format!("native={}", p.to_str().unwrap());
666 cargo.rustflag("-L").rustflag(&root);
667 }
668
669 if target.contains("-wasi")
670 && let Some(dir) = builder.wasi_libdir(target)
671 {
672 let root = format!("native={}", dir.to_str().unwrap());
673 cargo.rustflag("-L").rustflag(&root);
674 }
675 }
676
677 if builder.config.rust_lto == RustcLto::Off {
678 cargo.rustflag("-Clto=off");
679 }
680
681 if target.contains("riscv") {
688 cargo.rustflag("-Cforce-unwind-tables=yes");
689 }
690
691 let html_root =
692 format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
693 cargo.rustflag(&html_root);
694 cargo.rustdocflag(&html_root);
695
696 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
697}
698
699#[derive(Debug, Clone, PartialEq, Eq, Hash)]
708pub struct StdLink {
709 pub compiler: Compiler,
710 pub target_compiler: Compiler,
711 pub target: TargetSelection,
712 crates: Vec<String>,
714 force_recompile: bool,
716}
717
718impl StdLink {
719 pub fn from_std(std: Std, host_compiler: Compiler) -> Self {
720 Self {
721 compiler: host_compiler,
722 target_compiler: std.build_compiler,
723 target: std.target,
724 crates: std.crates,
725 force_recompile: std.force_recompile,
726 }
727 }
728}
729
730impl Step for StdLink {
731 type Output = ();
732
733 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
734 run.never()
735 }
736
737 fn run(self, builder: &Builder<'_>) {
746 let compiler = self.compiler;
747 let target_compiler = self.target_compiler;
748 let target = self.target;
749
750 let (libdir, hostdir) = if !self.force_recompile && builder.download_rustc() {
752 let lib = builder.sysroot_libdir_relative(self.compiler);
754 let sysroot = builder.ensure(crate::core::build_steps::compile::Sysroot {
755 compiler: self.compiler,
756 force_recompile: self.force_recompile,
757 });
758 let libdir = sysroot.join(lib).join("rustlib").join(target).join("lib");
759 let hostdir = sysroot.join(lib).join("rustlib").join(compiler.host).join("lib");
760 (libdir, hostdir)
761 } else {
762 let libdir = builder.sysroot_target_libdir(target_compiler, target);
763 let hostdir = builder.sysroot_target_libdir(target_compiler, compiler.host);
764 (libdir, hostdir)
765 };
766
767 let is_downloaded_beta_stage0 = builder
768 .build
769 .config
770 .initial_rustc
771 .starts_with(builder.out.join(compiler.host).join("stage0/bin"));
772
773 if compiler.stage == 0 && is_downloaded_beta_stage0 {
777 let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
779
780 let host = compiler.host;
781 let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
782 let sysroot_bin_dir = sysroot.join("bin");
783 t!(fs::create_dir_all(&sysroot_bin_dir));
784 builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
785
786 let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
787 t!(fs::create_dir_all(sysroot.join("lib")));
788 builder.cp_link_r(&stage0_lib_dir, &sysroot.join("lib"));
789
790 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
792 t!(fs::create_dir_all(&sysroot_codegen_backends));
793 let stage0_codegen_backends = builder
794 .out
795 .join(host)
796 .join("stage0/lib/rustlib")
797 .join(host)
798 .join("codegen-backends");
799 if stage0_codegen_backends.exists() {
800 builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
801 }
802 } else if compiler.stage == 0 {
803 let sysroot = builder.out.join(compiler.host.triple).join("stage0-sysroot");
804
805 if builder.local_rebuild {
806 let _ = fs::remove_dir_all(sysroot.join("lib/rustlib/src/rust"));
810 }
811
812 builder.cp_link_r(&builder.initial_sysroot.join("lib"), &sysroot.join("lib"));
813 } else {
814 if builder.download_rustc() {
815 let _ = fs::remove_dir_all(&libdir);
817 let _ = fs::remove_dir_all(&hostdir);
818 }
819
820 add_to_sysroot(
821 builder,
822 &libdir,
823 &hostdir,
824 &build_stamp::libstd_stamp(builder, compiler, target),
825 );
826 }
827 }
828}
829
830fn copy_sanitizers(
832 builder: &Builder<'_>,
833 compiler: &Compiler,
834 target: TargetSelection,
835) -> Vec<PathBuf> {
836 let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
837
838 if builder.config.dry_run() {
839 return Vec::new();
840 }
841
842 let mut target_deps = Vec::new();
843 let libdir = builder.sysroot_target_libdir(*compiler, target);
844
845 for runtime in &runtimes {
846 let dst = libdir.join(&runtime.name);
847 builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
848
849 if target == "x86_64-apple-darwin"
853 || target == "aarch64-apple-darwin"
854 || target == "aarch64-apple-ios"
855 || target == "aarch64-apple-ios-sim"
856 || target == "x86_64-apple-ios"
857 {
858 apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
860 apple_darwin_sign_file(builder, &dst);
863 }
864
865 target_deps.push(dst);
866 }
867
868 target_deps
869}
870
871fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
872 command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
873}
874
875fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
876 command("codesign")
877 .arg("-f") .arg("-s")
879 .arg("-")
880 .arg(file_path)
881 .run(builder);
882}
883
884#[derive(Debug, Clone, PartialEq, Eq, Hash)]
885pub struct StartupObjects {
886 pub compiler: Compiler,
887 pub target: TargetSelection,
888}
889
890impl Step for StartupObjects {
891 type Output = Vec<(PathBuf, DependencyType)>;
892
893 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
894 run.path("library/rtstartup")
895 }
896
897 fn make_run(run: RunConfig<'_>) {
898 run.builder.ensure(StartupObjects {
899 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
900 target: run.target,
901 });
902 }
903
904 fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
911 let for_compiler = self.compiler;
912 let target = self.target;
913 if !target.is_windows_gnu() {
916 return vec![];
917 }
918
919 let mut target_deps = vec![];
920
921 let src_dir = &builder.src.join("library").join("rtstartup");
922 let dst_dir = &builder.native_dir(target).join("rtstartup");
923 let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
924 t!(fs::create_dir_all(dst_dir));
925
926 for file in &["rsbegin", "rsend"] {
927 let src_file = &src_dir.join(file.to_string() + ".rs");
928 let dst_file = &dst_dir.join(file.to_string() + ".o");
929 if !up_to_date(src_file, dst_file) {
930 let mut cmd = command(&builder.initial_rustc);
931 cmd.env("RUSTC_BOOTSTRAP", "1");
932 if !builder.local_rebuild {
933 cmd.arg("--cfg").arg("bootstrap");
935 }
936 cmd.arg("--target")
937 .arg(target.rustc_target_arg())
938 .arg("--emit=obj")
939 .arg("-o")
940 .arg(dst_file)
941 .arg(src_file)
942 .run(builder);
943 }
944
945 let obj = sysroot_dir.join((*file).to_string() + ".o");
946 builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
947 target_deps.push((obj, DependencyType::Target));
948 }
949
950 target_deps
951 }
952}
953
954fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
955 let ci_rustc_dir = builder.config.ci_rustc_dir();
956
957 for file in contents {
958 let src = ci_rustc_dir.join(&file);
959 let dst = sysroot.join(file);
960 if src.is_dir() {
961 t!(fs::create_dir_all(dst));
962 } else {
963 builder.copy_link(&src, &dst, FileType::Regular);
964 }
965 }
966}
967
968#[derive(Clone, Debug)]
970pub struct BuiltRustc {
971 pub build_compiler: Compiler,
975}
976
977#[derive(Debug, Clone, PartialEq, Eq, Hash)]
984pub struct Rustc {
985 pub target: TargetSelection,
987 pub build_compiler: Compiler,
989 crates: Vec<String>,
995}
996
997impl Rustc {
998 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
999 Self { target, build_compiler, crates: Default::default() }
1000 }
1001}
1002
1003impl Step for Rustc {
1004 type Output = BuiltRustc;
1005 const IS_HOST: bool = true;
1006
1007 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1008 let mut crates = run.builder.in_tree_crates("rustc-main", None);
1009 for (i, krate) in crates.iter().enumerate() {
1010 if krate.name == "rustc-main" {
1013 crates.swap_remove(i);
1014 break;
1015 }
1016 }
1017 run.crates(crates)
1018 }
1019
1020 fn is_default_step(_builder: &Builder<'_>) -> bool {
1021 false
1022 }
1023
1024 fn make_run(run: RunConfig<'_>) {
1025 if run.builder.paths == vec![PathBuf::from("compiler")] {
1028 return;
1029 }
1030
1031 let crates = run.cargo_crates_in_set();
1032 run.builder.ensure(Rustc {
1033 build_compiler: run
1034 .builder
1035 .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1036 target: run.target,
1037 crates,
1038 });
1039 }
1040
1041 fn run(self, builder: &Builder<'_>) -> Self::Output {
1047 let build_compiler = self.build_compiler;
1048 let target = self.target;
1049
1050 if builder.download_rustc() && build_compiler.stage != 0 {
1053 trace!(stage = build_compiler.stage, "`download_rustc` requested");
1054
1055 let sysroot =
1056 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
1057 cp_rustc_component_to_ci_sysroot(
1058 builder,
1059 &sysroot,
1060 builder.config.ci_rustc_dev_contents(),
1061 );
1062 return BuiltRustc { build_compiler };
1063 }
1064
1065 builder.std(build_compiler, target);
1068
1069 if builder.config.keep_stage.contains(&build_compiler.stage) {
1070 trace!(stage = build_compiler.stage, "`keep-stage` requested");
1071
1072 builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1073 builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1074 builder.ensure(RustcLink::from_rustc(self));
1075
1076 return BuiltRustc { build_compiler };
1077 }
1078
1079 let stage = build_compiler.stage + 1;
1081
1082 if build_compiler.stage >= 2
1087 && !builder.config.full_bootstrap
1088 && target == builder.host_target
1089 {
1090 let uplift_build_compiler = builder.compiler(1, build_compiler.host);
1094
1095 let msg = format!("Uplifting rustc from stage2 to stage{stage})");
1096 builder.info(&msg);
1097
1098 builder.ensure(RustcLink::from_build_compiler_and_sysroot(
1102 uplift_build_compiler,
1104 build_compiler,
1106 target,
1107 self.crates,
1108 ));
1109
1110 return BuiltRustc { build_compiler: uplift_build_compiler };
1113 }
1114
1115 builder.std(
1121 builder.compiler(self.build_compiler.stage, builder.config.host_target),
1122 builder.config.host_target,
1123 );
1124
1125 let mut cargo = builder::Cargo::new(
1126 builder,
1127 build_compiler,
1128 Mode::Rustc,
1129 SourceType::InTree,
1130 target,
1131 Kind::Build,
1132 );
1133
1134 rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
1135
1136 for krate in &*self.crates {
1140 cargo.arg("-p").arg(krate);
1141 }
1142
1143 if builder.build.config.enable_bolt_settings && build_compiler.stage == 1 {
1144 cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1146 }
1147
1148 let _guard = builder.msg(
1149 Kind::Build,
1150 format_args!("compiler artifacts{}", crate_description(&self.crates)),
1151 Mode::Rustc,
1152 build_compiler,
1153 target,
1154 );
1155 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
1156
1157 run_cargo(
1158 builder,
1159 cargo,
1160 vec![],
1161 &stamp,
1162 vec![],
1163 ArtifactKeepMode::Custom(Box::new(|filename| {
1164 if filename.contains("jemalloc_sys")
1165 || filename.contains("rustc_public_bridge")
1166 || filename.contains("rustc_public")
1167 {
1168 filename.ends_with(".rlib")
1171 } else {
1172 filename.ends_with(".rmeta")
1176 }
1177 })),
1178 );
1179
1180 let target_root_dir = stamp.path().parent().unwrap();
1181 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1187 && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1188 {
1189 let rustc_driver = target_root_dir.join("librustc_driver.so");
1190 strip_debug(builder, target, &rustc_driver);
1191 }
1192
1193 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1194 strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1197 }
1198
1199 builder.ensure(RustcLink::from_rustc(self));
1200 BuiltRustc { build_compiler }
1201 }
1202
1203 fn metadata(&self) -> Option<StepMetadata> {
1204 Some(StepMetadata::build("rustc", self.target).built_by(self.build_compiler))
1205 }
1206}
1207
1208pub fn rustc_cargo(
1209 builder: &Builder<'_>,
1210 cargo: &mut Cargo,
1211 target: TargetSelection,
1212 build_compiler: &Compiler,
1213 crates: &[String],
1214) {
1215 cargo
1216 .arg("--features")
1217 .arg(builder.rustc_features(builder.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 builder.build.config.bootstrap_override_lld.is_used() {
1243 cargo.rustflag("-Zdefault-visibility=protected");
1244 }
1245
1246 if is_lto_stage(build_compiler) {
1247 match builder.config.rust_lto {
1248 RustcLto::Thin | RustcLto::Fat => {
1249 cargo.rustflag("-Zdylib-lto");
1252 let lto_type = match builder.config.rust_lto {
1256 RustcLto::Thin => "thin",
1257 RustcLto::Fat => "fat",
1258 _ => unreachable!(),
1259 };
1260 cargo.rustflag(&format!("-Clto={lto_type}"));
1261 cargo.rustflag("-Cembed-bitcode=yes");
1262 }
1263 RustcLto::ThinLocal => { }
1264 RustcLto::Off => {
1265 cargo.rustflag("-Clto=off");
1266 }
1267 }
1268 } else if builder.config.rust_lto == RustcLto::Off {
1269 cargo.rustflag("-Clto=off");
1270 }
1271
1272 if builder.config.bootstrap_override_lld.is_used() && !build_compiler.host.is_msvc() {
1280 cargo.rustflag("-Clink-args=-Wl,--icf=all");
1281 }
1282
1283 if builder.config.rust_profile_use.is_some() && builder.config.rust_profile_generate.is_some() {
1284 panic!("Cannot use and generate PGO profiles at the same time");
1285 }
1286 let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
1287 if build_compiler.stage == 1 {
1288 cargo.rustflag(&format!("-Cprofile-generate={path}"));
1289 cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
1292 true
1293 } else {
1294 false
1295 }
1296 } else if let Some(path) = &builder.config.rust_profile_use {
1297 if build_compiler.stage == 1 {
1298 cargo.rustflag(&format!("-Cprofile-use={path}"));
1299 if builder.is_verbose() {
1300 cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
1301 }
1302 true
1303 } else {
1304 false
1305 }
1306 } else {
1307 false
1308 };
1309 if is_collecting {
1310 cargo.rustflag(&format!(
1312 "-Cllvm-args=-static-func-strip-dirname-prefix={}",
1313 builder.config.src.components().count()
1314 ));
1315 }
1316
1317 if let Some(ref ccache) = builder.config.ccache
1322 && build_compiler.stage == 0
1323 && !builder.config.incremental
1324 {
1325 cargo.env("RUSTC_WRAPPER", ccache);
1326 }
1327
1328 rustc_cargo_env(builder, cargo, target);
1329}
1330
1331pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1332 cargo
1335 .env("CFG_RELEASE", builder.rust_release())
1336 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1337 .env("CFG_VERSION", builder.rust_version());
1338
1339 if builder.config.omit_git_hash {
1343 cargo.env("CFG_OMIT_GIT_HASH", "1");
1344 }
1345
1346 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", builder.config.default_codegen_backend(target).name());
1347
1348 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1349 let target_config = builder.config.target_config.get(&target);
1350
1351 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1352
1353 if let Some(ref ver_date) = builder.rust_info().commit_date() {
1354 cargo.env("CFG_VER_DATE", ver_date);
1355 }
1356 if let Some(ref ver_hash) = builder.rust_info().sha() {
1357 cargo.env("CFG_VER_HASH", ver_hash);
1358 }
1359 if !builder.unstable_features() {
1360 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1361 }
1362
1363 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1366 cargo.env("CFG_DEFAULT_LINKER", s);
1367 } else if let Some(ref s) = builder.config.rustc_default_linker {
1368 cargo.env("CFG_DEFAULT_LINKER", s);
1369 }
1370
1371 if let Some(linker) = target_config.map(|c| c.default_linker_linux_override) {
1373 match linker {
1374 DefaultLinuxLinkerOverride::Off => {}
1375 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1376 cargo.env("CFG_DEFAULT_LINKER_SELF_CONTAINED_LLD_CC", "1");
1377 }
1378 }
1379 }
1380
1381 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1383
1384 if builder.config.rust_verify_llvm_ir {
1385 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1386 }
1387
1388 if builder.config.llvm_enabled(target) {
1400 let building_llvm_is_expensive =
1401 crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false)
1402 .should_build();
1403
1404 let skip_llvm = (builder.kind == Kind::Check) && building_llvm_is_expensive;
1405 if !skip_llvm {
1406 rustc_llvm_env(builder, cargo, target)
1407 }
1408 }
1409
1410 if builder.config.jemalloc(target) && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none() {
1412 if target.starts_with("aarch64") {
1415 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1416 }
1417 else if target.starts_with("loongarch") {
1419 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "14");
1420 }
1421 }
1422}
1423
1424fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1430 if builder.config.is_rust_llvm(target) {
1431 cargo.env("LLVM_RUSTLLVM", "1");
1432 }
1433 if builder.config.llvm_enzyme {
1434 cargo.env("LLVM_ENZYME", "1");
1435 }
1436 let llvm::LlvmResult { host_llvm_config, .. } = builder.ensure(llvm::Llvm { target });
1437 if builder.config.llvm_offload {
1438 builder.ensure(llvm::OmpOffload { target });
1439 cargo.env("LLVM_OFFLOAD", "1");
1440 }
1441
1442 cargo.env("LLVM_CONFIG", &host_llvm_config);
1443
1444 let mut llvm_linker_flags = String::new();
1454 if builder.config.llvm_profile_generate
1455 && target.is_msvc()
1456 && let Some(ref clang_cl_path) = builder.config.llvm_clang_cl
1457 {
1458 let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1460 llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
1461 }
1462
1463 if let Some(ref s) = builder.config.llvm_ldflags {
1465 if !llvm_linker_flags.is_empty() {
1466 llvm_linker_flags.push(' ');
1467 }
1468 llvm_linker_flags.push_str(s);
1469 }
1470
1471 if !llvm_linker_flags.is_empty() {
1473 cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
1474 }
1475
1476 if builder.config.llvm_static_stdcpp
1479 && !target.contains("freebsd")
1480 && !target.is_msvc()
1481 && !target.contains("apple")
1482 && !target.contains("solaris")
1483 {
1484 let libstdcxx_name =
1485 if target.contains("windows-gnullvm") { "libc++.a" } else { "libstdc++.a" };
1486 let file = compiler_file(
1487 builder,
1488 &builder.cxx(target).unwrap(),
1489 target,
1490 CLang::Cxx,
1491 libstdcxx_name,
1492 );
1493 cargo.env("LLVM_STATIC_STDCPP", file);
1494 }
1495 if builder.llvm_link_shared() {
1496 cargo.env("LLVM_LINK_SHARED", "1");
1497 }
1498 if builder.config.llvm_use_libcxx {
1499 cargo.env("LLVM_USE_LIBCXX", "1");
1500 }
1501 if builder.config.llvm_assertions {
1502 cargo.env("LLVM_ASSERTIONS", "1");
1503 }
1504}
1505
1506#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1519struct RustcLink {
1520 build_compiler: Compiler,
1522 sysroot_compiler: Compiler,
1525 target: TargetSelection,
1526 crates: Vec<String>,
1528}
1529
1530impl RustcLink {
1531 fn from_rustc(rustc: Rustc) -> Self {
1534 Self {
1535 build_compiler: rustc.build_compiler,
1536 sysroot_compiler: rustc.build_compiler,
1537 target: rustc.target,
1538 crates: rustc.crates,
1539 }
1540 }
1541
1542 fn from_build_compiler_and_sysroot(
1544 build_compiler: Compiler,
1545 sysroot_compiler: Compiler,
1546 target: TargetSelection,
1547 crates: Vec<String>,
1548 ) -> Self {
1549 Self { build_compiler, sysroot_compiler, target, crates }
1550 }
1551}
1552
1553impl Step for RustcLink {
1554 type Output = ();
1555
1556 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1557 run.never()
1558 }
1559
1560 fn run(self, builder: &Builder<'_>) {
1562 let build_compiler = self.build_compiler;
1563 let sysroot_compiler = self.sysroot_compiler;
1564 let target = self.target;
1565 add_to_sysroot(
1566 builder,
1567 &builder.sysroot_target_libdir(sysroot_compiler, target),
1568 &builder.sysroot_target_libdir(sysroot_compiler, sysroot_compiler.host),
1569 &build_stamp::librustc_stamp(builder, build_compiler, target),
1570 );
1571 }
1572}
1573
1574#[derive(Clone)]
1580pub struct GccDylibSet {
1581 dylibs: BTreeMap<GccTargetPair, GccOutput>,
1582}
1583
1584impl GccDylibSet {
1585 pub fn build(
1588 builder: &Builder<'_>,
1589 host: TargetSelection,
1590 targets: Vec<TargetSelection>,
1591 ) -> Self {
1592 let dylibs = targets
1593 .iter()
1594 .map(|t| GccTargetPair::for_target_pair(host, *t))
1595 .map(|target_pair| (target_pair, builder.ensure(Gcc { target_pair })))
1596 .collect();
1597 Self { dylibs }
1598 }
1599
1600 pub fn install_to(&self, builder: &Builder<'_>, compiler: Compiler) {
1604 if builder.config.dry_run() {
1605 return;
1606 }
1607
1608 let cg_sysroot = builder.sysroot_codegen_backends(compiler);
1610
1611 for (target_pair, libgccjit) in &self.dylibs {
1612 assert_eq!(
1613 target_pair.host(),
1614 compiler.host,
1615 "Trying to install libgccjit ({target_pair}) to a compiler with a different host ({})",
1616 compiler.host
1617 );
1618 let libgccjit_path = libgccjit.libgccjit();
1619
1620 let libgccjit_path = t!(
1624 libgccjit_path.canonicalize(),
1625 format!("Cannot find libgccjit at {}", libgccjit_path.display())
1626 );
1627
1628 let dst = cg_sysroot.join(libgccjit_path_relative_to_cg_dir(target_pair, libgccjit));
1629 t!(std::fs::create_dir_all(dst.parent().unwrap()));
1630 builder.copy_link(&libgccjit_path, &dst, FileType::NativeLibrary);
1631 }
1632 }
1633}
1634
1635pub fn libgccjit_path_relative_to_cg_dir(
1638 target_pair: &GccTargetPair,
1639 libgccjit: &GccOutput,
1640) -> PathBuf {
1641 let target_filename = libgccjit.libgccjit().file_name().unwrap().to_str().unwrap();
1642
1643 Path::new("lib").join(target_pair.target()).join(target_filename)
1645}
1646
1647#[derive(Clone)]
1651pub struct GccCodegenBackendOutput {
1652 stamp: BuildStamp,
1653}
1654
1655impl GccCodegenBackendOutput {
1656 pub fn stamp(&self) -> &BuildStamp {
1657 &self.stamp
1658 }
1659}
1660
1661#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1668pub struct GccCodegenBackend {
1669 compilers: RustcPrivateCompilers,
1670 target: TargetSelection,
1671}
1672
1673impl GccCodegenBackend {
1674 pub fn for_target(compilers: RustcPrivateCompilers, target: TargetSelection) -> Self {
1676 Self { compilers, target }
1677 }
1678}
1679
1680impl Step for GccCodegenBackend {
1681 type Output = GccCodegenBackendOutput;
1682
1683 const IS_HOST: bool = true;
1684
1685 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1686 run.alias("rustc_codegen_gcc").alias("cg_gcc")
1687 }
1688
1689 fn make_run(run: RunConfig<'_>) {
1690 let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target);
1691 run.builder.ensure(GccCodegenBackend::for_target(compilers, run.target));
1692 }
1693
1694 fn run(self, builder: &Builder<'_>) -> Self::Output {
1695 let host = self.compilers.target();
1696 let build_compiler = self.compilers.build_compiler();
1697
1698 let stamp = build_stamp::codegen_backend_stamp(
1699 builder,
1700 build_compiler,
1701 host,
1702 &CodegenBackendKind::Gcc,
1703 );
1704
1705 if builder.config.keep_stage.contains(&build_compiler.stage) && stamp.path().exists() {
1706 trace!("`keep-stage` requested");
1707 builder.info(
1708 "WARNING: Using a potentially old codegen backend. \
1709 This may not behave well.",
1710 );
1711 return GccCodegenBackendOutput { stamp };
1714 }
1715
1716 let mut cargo = builder::Cargo::new(
1717 builder,
1718 build_compiler,
1719 Mode::Codegen,
1720 SourceType::InTree,
1721 host,
1722 Kind::Build,
1723 );
1724 cargo.arg("--manifest-path").arg(builder.src.join("compiler/rustc_codegen_gcc/Cargo.toml"));
1725 rustc_cargo_env(builder, &mut cargo, host);
1726
1727 let _guard =
1728 builder.msg(Kind::Build, "codegen backend gcc", Mode::Codegen, build_compiler, host);
1729 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyRlib);
1730
1731 GccCodegenBackendOutput {
1732 stamp: write_codegen_backend_stamp(stamp, files, builder.config.dry_run()),
1733 }
1734 }
1735
1736 fn metadata(&self) -> Option<StepMetadata> {
1737 Some(
1738 StepMetadata::build("rustc_codegen_gcc", self.compilers.target())
1739 .built_by(self.compilers.build_compiler()),
1740 )
1741 }
1742}
1743
1744#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1745pub struct CraneliftCodegenBackend {
1746 pub compilers: RustcPrivateCompilers,
1747}
1748
1749impl Step for CraneliftCodegenBackend {
1750 type Output = BuildStamp;
1751 const IS_HOST: bool = true;
1752
1753 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1754 run.alias("rustc_codegen_cranelift").alias("cg_clif")
1755 }
1756
1757 fn make_run(run: RunConfig<'_>) {
1758 run.builder.ensure(CraneliftCodegenBackend {
1759 compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1760 });
1761 }
1762
1763 fn run(self, builder: &Builder<'_>) -> Self::Output {
1764 let target = self.compilers.target();
1765 let build_compiler = self.compilers.build_compiler();
1766
1767 let stamp = build_stamp::codegen_backend_stamp(
1768 builder,
1769 build_compiler,
1770 target,
1771 &CodegenBackendKind::Cranelift,
1772 );
1773
1774 if builder.config.keep_stage.contains(&build_compiler.stage) {
1775 trace!("`keep-stage` requested");
1776 builder.info(
1777 "WARNING: Using a potentially old codegen backend. \
1778 This may not behave well.",
1779 );
1780 return stamp;
1783 }
1784
1785 let mut cargo = builder::Cargo::new(
1786 builder,
1787 build_compiler,
1788 Mode::Codegen,
1789 SourceType::InTree,
1790 target,
1791 Kind::Build,
1792 );
1793 cargo
1794 .arg("--manifest-path")
1795 .arg(builder.src.join("compiler/rustc_codegen_cranelift/Cargo.toml"));
1796 rustc_cargo_env(builder, &mut cargo, target);
1797
1798 let _guard = builder.msg(
1799 Kind::Build,
1800 "codegen backend cranelift",
1801 Mode::Codegen,
1802 build_compiler,
1803 target,
1804 );
1805 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyRlib);
1806 write_codegen_backend_stamp(stamp, files, builder.config.dry_run())
1807 }
1808
1809 fn metadata(&self) -> Option<StepMetadata> {
1810 Some(
1811 StepMetadata::build("rustc_codegen_cranelift", self.compilers.target())
1812 .built_by(self.compilers.build_compiler()),
1813 )
1814 }
1815}
1816
1817fn write_codegen_backend_stamp(
1819 mut stamp: BuildStamp,
1820 files: Vec<PathBuf>,
1821 dry_run: bool,
1822) -> BuildStamp {
1823 if dry_run {
1824 return stamp;
1825 }
1826
1827 let mut files = files.into_iter().filter(|f| {
1828 let filename = f.file_name().unwrap().to_str().unwrap();
1829 is_dylib(f) && filename.contains("rustc_codegen_")
1830 });
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
1845fn copy_codegen_backends_to_sysroot(
1852 builder: &Builder<'_>,
1853 stamp: BuildStamp,
1854 target_compiler: Compiler,
1855) {
1856 let dst = builder.sysroot_codegen_backends(target_compiler);
1865 t!(fs::create_dir_all(&dst), dst);
1866
1867 if builder.config.dry_run() {
1868 return;
1869 }
1870
1871 if stamp.path().exists() {
1872 let file = get_codegen_backend_file(&stamp);
1873 builder.copy_link(
1874 &file,
1875 &dst.join(normalize_codegen_backend_name(builder, &file)),
1876 FileType::NativeLibrary,
1877 );
1878 }
1879}
1880
1881pub fn get_codegen_backend_file(stamp: &BuildStamp) -> PathBuf {
1883 PathBuf::from(t!(fs::read_to_string(stamp.path())))
1884}
1885
1886pub fn normalize_codegen_backend_name(builder: &Builder<'_>, path: &Path) -> String {
1888 let filename = path.file_name().unwrap().to_str().unwrap();
1889 let dash = filename.find('-').unwrap();
1892 let dot = filename.find('.').unwrap();
1893 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1894}
1895
1896pub fn compiler_file(
1897 builder: &Builder<'_>,
1898 compiler: &Path,
1899 target: TargetSelection,
1900 c: CLang,
1901 file: &str,
1902) -> PathBuf {
1903 if builder.config.dry_run() {
1904 return PathBuf::new();
1905 }
1906 let mut cmd = command(compiler);
1907 cmd.args(builder.cc_handled_clags(target, c));
1908 cmd.args(builder.cc_unhandled_cflags(target, GitRepo::Rustc, c));
1909 cmd.arg(format!("-print-file-name={file}"));
1910 let out = cmd.run_capture_stdout(builder).stdout();
1911 PathBuf::from(out.trim())
1912}
1913
1914#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1915pub struct Sysroot {
1916 pub compiler: Compiler,
1917 force_recompile: bool,
1919}
1920
1921impl Sysroot {
1922 pub(crate) fn new(compiler: Compiler) -> Self {
1923 Sysroot { compiler, force_recompile: false }
1924 }
1925}
1926
1927impl Step for Sysroot {
1928 type Output = PathBuf;
1929
1930 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1931 run.never()
1932 }
1933
1934 fn run(self, builder: &Builder<'_>) -> PathBuf {
1938 let compiler = self.compiler;
1939 let host_dir = builder.out.join(compiler.host);
1940
1941 let sysroot_dir = |stage| {
1942 if stage == 0 {
1943 host_dir.join("stage0-sysroot")
1944 } else if self.force_recompile && stage == compiler.stage {
1945 host_dir.join(format!("stage{stage}-test-sysroot"))
1946 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1947 host_dir.join("ci-rustc-sysroot")
1948 } else {
1949 host_dir.join(format!("stage{stage}"))
1950 }
1951 };
1952 let sysroot = sysroot_dir(compiler.stage);
1953 trace!(stage = ?compiler.stage, ?sysroot);
1954
1955 builder.do_if_verbose(|| {
1956 println!("Removing sysroot {} to avoid caching bugs", sysroot.display())
1957 });
1958 let _ = fs::remove_dir_all(&sysroot);
1959 t!(fs::create_dir_all(&sysroot));
1960
1961 if compiler.stage == 0 {
1968 dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1969 }
1970
1971 if builder.download_rustc() && compiler.stage != 0 {
1973 assert_eq!(
1974 builder.config.host_target, compiler.host,
1975 "Cross-compiling is not yet supported with `download-rustc`",
1976 );
1977
1978 for stage in 0..=2 {
1980 if stage != compiler.stage {
1981 let dir = sysroot_dir(stage);
1982 if !dir.ends_with("ci-rustc-sysroot") {
1983 let _ = fs::remove_dir_all(dir);
1984 }
1985 }
1986 }
1987
1988 let mut filtered_files = Vec::new();
1998 let mut add_filtered_files = |suffix, contents| {
1999 for path in contents {
2000 let path = Path::new(&path);
2001 if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
2002 filtered_files.push(path.file_name().unwrap().to_owned());
2003 }
2004 }
2005 };
2006 let suffix = format!("lib/rustlib/{}/lib", compiler.host);
2007 add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
2008 add_filtered_files("lib", builder.config.ci_rust_std_contents());
2011
2012 let filtered_extensions = [
2013 OsStr::new("rmeta"),
2014 OsStr::new("rlib"),
2015 OsStr::new(std::env::consts::DLL_EXTENSION),
2017 ];
2018 let ci_rustc_dir = builder.config.ci_rustc_dir();
2019 builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
2020 if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
2021 return true;
2022 }
2023 if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
2024 return true;
2025 }
2026 filtered_files.iter().all(|f| f != path.file_name().unwrap())
2027 });
2028 }
2029
2030 if compiler.stage != 0 {
2036 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
2037 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
2038 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
2039 if let Err(e) =
2040 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust)
2041 {
2042 eprintln!(
2043 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2044 sysroot_lib_rustlib_src_rust.display(),
2045 builder.src.display(),
2046 e,
2047 );
2048 if builder.config.rust_remap_debuginfo {
2049 eprintln!(
2050 "ERROR: some `tests/ui` tests will fail when lacking `{}`",
2051 sysroot_lib_rustlib_src_rust.display(),
2052 );
2053 }
2054 build_helper::exit!(1);
2055 }
2056 }
2057
2058 if !builder.download_rustc() {
2060 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
2061 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
2062 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
2063 if let Err(e) =
2064 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
2065 {
2066 eprintln!(
2067 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2068 sysroot_lib_rustlib_rustcsrc_rust.display(),
2069 builder.src.display(),
2070 e,
2071 );
2072 build_helper::exit!(1);
2073 }
2074 }
2075
2076 sysroot
2077 }
2078}
2079
2080#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2087pub struct Assemble {
2088 pub target_compiler: Compiler,
2093}
2094
2095impl Step for Assemble {
2096 type Output = Compiler;
2097 const IS_HOST: bool = true;
2098
2099 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2100 run.path("compiler/rustc").path("compiler")
2101 }
2102
2103 fn make_run(run: RunConfig<'_>) {
2104 run.builder.ensure(Assemble {
2105 target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2106 });
2107 }
2108
2109 fn run(self, builder: &Builder<'_>) -> Compiler {
2110 let target_compiler = self.target_compiler;
2111
2112 if target_compiler.stage == 0 {
2113 trace!("stage 0 build compiler is always available, simply returning");
2114 assert_eq!(
2115 builder.config.host_target, target_compiler.host,
2116 "Cannot obtain compiler for non-native build triple at stage 0"
2117 );
2118 return target_compiler;
2120 }
2121
2122 let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2125 let libdir_bin = libdir.parent().unwrap().join("bin");
2126 t!(fs::create_dir_all(&libdir_bin));
2127
2128 if builder.config.llvm_enabled(target_compiler.host) {
2129 trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
2130
2131 let target = target_compiler.host;
2132 let llvm::LlvmResult { host_llvm_config, .. } = builder.ensure(llvm::Llvm { target });
2133 if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
2134 trace!("LLVM tools enabled");
2135
2136 let host_llvm_bin_dir = command(&host_llvm_config)
2137 .arg("--bindir")
2138 .cached()
2139 .run_capture_stdout(builder)
2140 .stdout()
2141 .trim()
2142 .to_string();
2143
2144 let llvm_bin_dir = if target == builder.host_target {
2145 PathBuf::from(host_llvm_bin_dir)
2146 } else {
2147 let external_llvm_config = builder
2150 .config
2151 .target_config
2152 .get(&target)
2153 .and_then(|t| t.llvm_config.clone());
2154 if let Some(external_llvm_config) = external_llvm_config {
2155 external_llvm_config.parent().unwrap().to_path_buf()
2158 } else {
2159 let host_llvm_out = builder.llvm_out(builder.host_target);
2163 let target_llvm_out = builder.llvm_out(target);
2164 if let Ok(relative_path) =
2165 Path::new(&host_llvm_bin_dir).strip_prefix(host_llvm_out)
2166 {
2167 target_llvm_out.join(relative_path)
2168 } else {
2169 PathBuf::from(
2172 host_llvm_bin_dir
2173 .replace(&*builder.host_target.triple, &target.triple),
2174 )
2175 }
2176 }
2177 };
2178
2179 #[cfg(feature = "tracing")]
2186 let _llvm_tools_span =
2187 span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
2188 .entered();
2189 for tool in LLVM_TOOLS {
2190 trace!("installing `{tool}`");
2191 let tool_exe = exe(tool, target_compiler.host);
2192 let src_path = llvm_bin_dir.join(&tool_exe);
2193
2194 if !src_path.exists() && builder.config.llvm_from_ci {
2196 eprintln!("{} does not exist; skipping copy", src_path.display());
2197 continue;
2198 }
2199
2200 builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2207 }
2208 }
2209 }
2210
2211 let maybe_install_llvm_bitcode_linker = || {
2212 if builder.config.llvm_bitcode_linker_enabled {
2213 trace!("llvm-bitcode-linker enabled, installing");
2214 let llvm_bitcode_linker = builder.ensure(
2215 crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler(
2216 builder,
2217 target_compiler,
2218 ),
2219 );
2220
2221 let bindir_self_contained = builder
2223 .sysroot(target_compiler)
2224 .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host));
2225 let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2226
2227 t!(fs::create_dir_all(&bindir_self_contained));
2228 builder.copy_link(
2229 &llvm_bitcode_linker.tool_path,
2230 &bindir_self_contained.join(tool_exe),
2231 FileType::Executable,
2232 );
2233 }
2234 };
2235
2236 if builder.download_rustc() {
2238 trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2239
2240 builder.std(target_compiler, target_compiler.host);
2241 let sysroot =
2242 builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2243 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2246 if target_compiler.stage == builder.top_stage {
2248 builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage));
2249 }
2250
2251 maybe_install_llvm_bitcode_linker();
2254
2255 return target_compiler;
2256 }
2257
2258 debug!(
2272 "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2273 target_compiler.stage - 1,
2274 builder.config.host_target,
2275 );
2276 let build_compiler =
2277 builder.compiler(target_compiler.stage - 1, builder.config.host_target);
2278
2279 if builder.config.llvm_enzyme {
2281 debug!("`llvm_enzyme` requested");
2282 let enzyme = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2283 let target_libdir =
2284 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2285 let target_dst_lib = target_libdir.join(enzyme.enzyme_filename());
2286 builder.copy_link(&enzyme.enzyme_path(), &target_dst_lib, FileType::NativeLibrary);
2287 }
2288
2289 if builder.config.llvm_offload && !builder.config.dry_run() {
2290 debug!("`llvm_offload` requested");
2291 let offload_install = builder.ensure(llvm::OmpOffload { target: build_compiler.host });
2292 if let Some(_llvm_config) = builder.llvm_config(builder.config.host_target) {
2293 let target_libdir =
2294 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2295 for p in offload_install.offload_paths() {
2296 let libname = p.file_name().unwrap();
2297 let dst_lib = target_libdir.join(libname);
2298 builder.resolve_symlink_and_copy(&p, &dst_lib);
2299 }
2300 }
2305 }
2306
2307 debug!(
2310 ?build_compiler,
2311 "target_compiler.host" = ?target_compiler.host,
2312 "building compiler libraries to link to"
2313 );
2314
2315 let BuiltRustc { build_compiler } =
2317 builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2318
2319 let stage = target_compiler.stage;
2320 let host = target_compiler.host;
2321 let (host_info, dir_name) = if build_compiler.host == host {
2322 ("".into(), "host".into())
2323 } else {
2324 (format!(" ({host})"), host.to_string())
2325 };
2326 let msg = format!(
2331 "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2332 );
2333 builder.info(&msg);
2334
2335 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2337 let proc_macros = builder
2338 .read_stamp_file(&stamp)
2339 .into_iter()
2340 .filter_map(|(path, dependency_type)| {
2341 if dependency_type == DependencyType::Host {
2342 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2343 } else {
2344 None
2345 }
2346 })
2347 .collect::<HashSet<_>>();
2348
2349 let sysroot = builder.sysroot(target_compiler);
2350 let rustc_libdir = builder.rustc_libdir(target_compiler);
2351 t!(fs::create_dir_all(&rustc_libdir));
2352 let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2353 for f in builder.read_dir(&src_libdir) {
2354 let filename = f.file_name().into_string().unwrap();
2355
2356 let is_proc_macro = proc_macros.contains(&filename);
2357 let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2358
2359 let can_be_rustc_dynamic_dep = if builder
2363 .link_std_into_rustc_driver(target_compiler.host)
2364 && !target_compiler.host.is_windows()
2365 {
2366 let is_std = filename.starts_with("std-") || filename.starts_with("libstd-");
2367 !is_std
2368 } else {
2369 true
2370 };
2371
2372 if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2373 builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2374 }
2375 }
2376
2377 {
2378 #[cfg(feature = "tracing")]
2379 let _codegen_backend_span =
2380 span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2381
2382 for backend in builder.config.enabled_codegen_backends(target_compiler.host) {
2383 if builder.kind == Kind::Check && builder.top_stage == 1 {
2400 continue;
2401 }
2402
2403 let prepare_compilers = || {
2404 RustcPrivateCompilers::from_build_and_target_compiler(
2405 build_compiler,
2406 target_compiler,
2407 )
2408 };
2409
2410 match backend {
2411 CodegenBackendKind::Cranelift => {
2412 let stamp = builder
2413 .ensure(CraneliftCodegenBackend { compilers: prepare_compilers() });
2414 copy_codegen_backends_to_sysroot(builder, stamp, target_compiler);
2415 }
2416 CodegenBackendKind::Gcc => {
2417 let compilers = prepare_compilers();
2450 let cg_gcc = builder
2451 .ensure(GccCodegenBackend::for_target(compilers, target_compiler.host));
2452 copy_codegen_backends_to_sysroot(builder, cg_gcc.stamp, target_compiler);
2453
2454 let mut targets = HashSet::new();
2461 for target in &builder.hosts {
2464 targets.insert(*target);
2465 }
2466 for target in &builder.targets {
2468 targets.insert(*target);
2469 }
2470 targets.insert(compilers.target_compiler().host);
2473
2474 let dylib_set = GccDylibSet::build(
2476 builder,
2477 compilers.target_compiler().host,
2478 targets.into_iter().collect(),
2479 );
2480
2481 dylib_set.install_to(builder, target_compiler);
2484 }
2485 CodegenBackendKind::Llvm | CodegenBackendKind::Custom(_) => continue,
2486 }
2487 }
2488 }
2489
2490 if builder.config.lld_enabled {
2491 let lld_wrapper =
2492 builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler(
2493 builder,
2494 target_compiler,
2495 ));
2496 copy_lld_artifacts(builder, lld_wrapper, target_compiler);
2497 }
2498
2499 if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2500 debug!(
2501 "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2502 workaround faulty homebrew `strip`s"
2503 );
2504
2505 let src_exe = exe("llvm-objcopy", target_compiler.host);
2512 let dst_exe = exe("rust-objcopy", target_compiler.host);
2513 builder.copy_link(
2514 &libdir_bin.join(src_exe),
2515 &libdir_bin.join(dst_exe),
2516 FileType::Executable,
2517 );
2518 }
2519
2520 if builder.tool_enabled("wasm-component-ld") {
2523 let wasm_component = builder.ensure(
2524 crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler(
2525 builder,
2526 target_compiler,
2527 ),
2528 );
2529 builder.copy_link(
2530 &wasm_component.tool_path,
2531 &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2532 FileType::Executable,
2533 );
2534 }
2535
2536 maybe_install_llvm_bitcode_linker();
2537
2538 debug!(
2541 "target_compiler.host" = ?target_compiler.host,
2542 ?sysroot,
2543 "ensuring availability of `libLLVM.so` in compiler directory"
2544 );
2545 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2546 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2547
2548 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2550 let rustc = out_dir.join(exe("rustc-main", host));
2551 let bindir = sysroot.join("bin");
2552 t!(fs::create_dir_all(bindir));
2553 let compiler = builder.rustc(target_compiler);
2554 debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2555 builder.copy_link(&rustc, &compiler, FileType::Executable);
2556
2557 target_compiler
2558 }
2559}
2560
2561#[track_caller]
2566pub fn add_to_sysroot(
2567 builder: &Builder<'_>,
2568 sysroot_dst: &Path,
2569 sysroot_host_dst: &Path,
2570 stamp: &BuildStamp,
2571) {
2572 let self_contained_dst = &sysroot_dst.join("self-contained");
2573 t!(fs::create_dir_all(sysroot_dst));
2574 t!(fs::create_dir_all(sysroot_host_dst));
2575 t!(fs::create_dir_all(self_contained_dst));
2576
2577 let mut crates = HashMap::new();
2578 for (path, dependency_type) in builder.read_stamp_file(stamp) {
2579 let filename = path.file_name().unwrap().to_str().unwrap();
2580 let dst = match dependency_type {
2581 DependencyType::Host => {
2582 if sysroot_dst == sysroot_host_dst {
2583 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2586 }
2587
2588 sysroot_host_dst
2589 }
2590 DependencyType::Target => {
2591 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2594
2595 sysroot_dst
2596 }
2597 DependencyType::TargetSelfContained => self_contained_dst,
2598 };
2599 builder.copy_link(&path, &dst.join(filename), FileType::Regular);
2600 }
2601
2602 let mut seen_crates = HashMap::new();
2608 for (filestem, path) in crates {
2609 if !filestem.contains("rustc_") || filestem.contains("rustc_hash") {
2610 continue;
2611 }
2612 if let Some(other_path) =
2613 seen_crates.insert(filestem.split_once('-').unwrap().0.to_owned(), path.clone())
2614 {
2615 panic!(
2616 "duplicate rustc crate {}\n- first copy at {}\n- second copy at {}",
2617 filestem.split_once('-').unwrap().0.to_owned(),
2618 other_path.display(),
2619 path.display(),
2620 );
2621 }
2622 }
2623}
2624
2625pub enum ArtifactKeepMode {
2629 OnlyRlib,
2631 OnlyRmeta,
2633 BothRlibAndRmeta,
2637 Custom(Box<dyn Fn(&str) -> bool>),
2640}
2641
2642pub fn run_cargo(
2643 builder: &Builder<'_>,
2644 cargo: Cargo,
2645 tail_args: Vec<String>,
2646 stamp: &BuildStamp,
2647 additional_target_deps: Vec<(PathBuf, DependencyType)>,
2648 artifact_keep_mode: ArtifactKeepMode,
2649) -> Vec<PathBuf> {
2650 let target_root_dir = stamp.path().parent().unwrap();
2652 let target_deps_dir = target_root_dir.join("deps");
2654 let host_root_dir = target_root_dir
2656 .parent()
2657 .unwrap() .parent()
2659 .unwrap() .join(target_root_dir.file_name().unwrap());
2661
2662 let mut deps = Vec::new();
2666 let mut toplevel = Vec::new();
2667 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2668 let (filenames_vec, crate_types) = match msg {
2669 CargoMessage::CompilerArtifact {
2670 filenames,
2671 target: CargoTarget { crate_types },
2672 ..
2673 } => {
2674 let mut f: Vec<String> = filenames.into_iter().map(|s| s.into_owned()).collect();
2675 f.sort(); (f, crate_types)
2677 }
2678 _ => return,
2679 };
2680 for filename in filenames_vec {
2681 let keep = if filename.ends_with(".lib")
2683 || filename.ends_with(".a")
2684 || is_debug_info(&filename)
2685 || is_dylib(Path::new(&*filename))
2686 {
2687 true
2689 } else {
2690 match &artifact_keep_mode {
2691 ArtifactKeepMode::OnlyRlib => filename.ends_with(".rlib"),
2692 ArtifactKeepMode::OnlyRmeta => filename.ends_with(".rmeta"),
2693 ArtifactKeepMode::BothRlibAndRmeta => {
2694 filename.ends_with(".rmeta") || filename.ends_with(".rlib")
2695 }
2696 ArtifactKeepMode::Custom(func) => func(&filename),
2697 }
2698 };
2699
2700 if !keep {
2701 continue;
2702 }
2703
2704 let filename = Path::new(&*filename);
2705
2706 if filename.starts_with(&host_root_dir) {
2709 if crate_types.iter().any(|t| t == "proc-macro") {
2711 if filename.file_name().unwrap().to_str().unwrap().contains("-") {
2716 deps.push((filename.to_path_buf(), DependencyType::Host));
2717 }
2718 }
2719 continue;
2720 }
2721
2722 if filename.starts_with(&target_deps_dir) {
2725 deps.push((filename.to_path_buf(), DependencyType::Target));
2726 continue;
2727 }
2728
2729 let expected_len = t!(filename.metadata()).len();
2740 let filename = filename.file_name().unwrap().to_str().unwrap();
2741 let mut parts = filename.splitn(2, '.');
2742 let file_stem = parts.next().unwrap().to_owned();
2743 let extension = parts.next().unwrap().to_owned();
2744
2745 toplevel.push((file_stem, extension, expected_len));
2746 }
2747 });
2748
2749 if !ok {
2750 crate::exit!(1);
2751 }
2752
2753 if builder.config.dry_run() {
2754 return Vec::new();
2755 }
2756
2757 let contents = target_deps_dir
2761 .read_dir()
2762 .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_deps_dir.display(), e))
2763 .map(|e| t!(e))
2764 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2765 .collect::<Vec<_>>();
2766 for (prefix, extension, expected_len) in toplevel {
2767 let candidates = contents.iter().filter(|&(_, filename, meta)| {
2768 meta.len() == expected_len
2769 && filename
2770 .strip_prefix(&prefix[..])
2771 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2772 .unwrap_or(false)
2773 });
2774 let max = candidates.max_by_key(|&(_, _, metadata)| {
2775 metadata.modified().expect("mtime should be available on all relevant OSes")
2776 });
2777 let path_to_add = match max {
2778 Some(triple) => triple.0.to_str().unwrap(),
2779 None => panic!("no output generated for {prefix:?} {extension:?}"),
2780 };
2781 if is_dylib(Path::new(path_to_add)) {
2782 let candidate = format!("{path_to_add}.lib");
2783 let candidate = PathBuf::from(candidate);
2784 if candidate.exists() {
2785 deps.push((candidate, DependencyType::Target));
2786 }
2787 }
2788 deps.push((path_to_add.into(), DependencyType::Target));
2789 }
2790
2791 deps.extend(additional_target_deps);
2792 deps.sort();
2793 let mut new_contents = Vec::new();
2794 for (dep, dependency_type) in deps.iter() {
2795 new_contents.extend(match *dependency_type {
2796 DependencyType::Host => b"h",
2797 DependencyType::Target => b"t",
2798 DependencyType::TargetSelfContained => b"s",
2799 });
2800 new_contents.extend(dep.to_str().unwrap().as_bytes());
2801 new_contents.extend(b"\0");
2802 }
2803 t!(fs::write(stamp.path(), &new_contents));
2804 deps.into_iter().map(|(d, _)| d).collect()
2805}
2806
2807pub fn stream_cargo(
2808 builder: &Builder<'_>,
2809 cargo: Cargo,
2810 tail_args: Vec<String>,
2811 cb: &mut dyn FnMut(CargoMessage<'_>),
2812) -> bool {
2813 let mut cmd = cargo.into_cmd();
2814
2815 let mut message_format = if builder.config.json_output {
2818 String::from("json")
2819 } else {
2820 String::from("json-render-diagnostics")
2821 };
2822 if let Some(s) = &builder.config.rustc_error_format {
2823 message_format.push_str(",json-diagnostic-");
2824 message_format.push_str(s);
2825 }
2826 cmd.arg("--message-format").arg(message_format);
2827
2828 for arg in tail_args {
2829 cmd.arg(arg);
2830 }
2831
2832 builder.do_if_verbose(|| println!("running: {cmd:?}"));
2833
2834 let streaming_command = cmd.stream_capture_stdout(&builder.config.exec_ctx);
2835
2836 let Some(mut streaming_command) = streaming_command else {
2837 return true;
2838 };
2839
2840 let stdout = BufReader::new(streaming_command.stdout.take().unwrap());
2844 for line in stdout.lines() {
2845 let line = t!(line);
2846 match serde_json::from_str::<CargoMessage<'_>>(&line) {
2847 Ok(msg) => {
2848 if builder.config.json_output {
2849 println!("{line}");
2851 }
2852 cb(msg)
2853 }
2854 Err(_) => println!("{line}"),
2856 }
2857 }
2858
2859 let status = t!(streaming_command.wait(&builder.config.exec_ctx));
2861 if builder.is_verbose() && !status.success() {
2862 eprintln!(
2863 "command did not execute successfully: {cmd:?}\n\
2864 expected success, got: {status}"
2865 );
2866 }
2867
2868 status.success()
2869}
2870
2871#[derive(Deserialize)]
2872pub struct CargoTarget<'a> {
2873 crate_types: Vec<Cow<'a, str>>,
2874}
2875
2876#[derive(Deserialize)]
2877#[serde(tag = "reason", rename_all = "kebab-case")]
2878pub enum CargoMessage<'a> {
2879 CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2880 BuildScriptExecuted,
2881 BuildFinished,
2882}
2883
2884pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2885 if target != "x86_64-unknown-linux-gnu"
2889 || !builder.config.is_host_target(target)
2890 || !path.exists()
2891 {
2892 return;
2893 }
2894
2895 let previous_mtime = t!(t!(path.metadata()).modified());
2896 let stamp = BuildStamp::new(path.parent().unwrap())
2897 .with_prefix(path.file_name().unwrap().to_str().unwrap())
2898 .with_prefix("strip")
2899 .add_stamp(previous_mtime.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos());
2900
2901 if !stamp.is_up_to_date() {
2904 command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2905 }
2906 t!(stamp.write());
2907
2908 let file = t!(fs::File::open(path));
2909
2910 t!(file.set_modified(previous_mtime));
2923}
2924
2925pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2927 build_compiler.stage != 0
2928}