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("-Zunstable-options").env("RUSTC_BOOTSTRAP", "1");
549 cmd.arg("--print=deployment-target");
550 let output = cmd.run_capture_stdout(builder).stdout();
551
552 let (env_var, value) = output.split_once('=').unwrap();
553 cargo.env(env_var.trim(), value.trim());
556
557 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
567 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
568 }
569 }
570
571 if let Some(path) = builder.config.profiler_path(target) {
573 cargo.env("LLVM_PROFILER_RT_LIB", path);
574 } else if builder.config.profiler_enabled(target) {
575 let compiler_rt = compiler_rt_for_profiler(builder);
576 cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
580 }
581
582 let compiler_builtins_c_feature = match builder.config.optimized_compiler_builtins(target) {
596 CompilerBuiltins::LinkLLVMBuiltinsLib(path) => {
597 cargo.env("LLVM_COMPILER_RT_LIB", path);
598 " compiler-builtins-c"
599 }
600 CompilerBuiltins::BuildLLVMFuncs => {
601 builder.require_submodule(
611 "src/llvm-project",
612 Some(
613 "The `build.optimized-compiler-builtins` config option \
614 requires `compiler-rt` sources from LLVM.",
615 ),
616 );
617 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
618 if !builder.config.dry_run() {
619 assert!(compiler_builtins_root.exists());
622 }
623
624 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
627 " compiler-builtins-c"
628 }
629 CompilerBuiltins::BuildRustOnly => "",
630 };
631
632 for krate in crates {
633 cargo.args(["-p", krate]);
634 }
635
636 let mut features = String::new();
637
638 if builder.no_std(target) == Some(true) {
639 features += " compiler-builtins-mem";
640 if !target.starts_with("bpf") {
641 features.push_str(compiler_builtins_c_feature);
642 }
643
644 if crates.is_empty() {
646 cargo.args(["-p", "alloc"]);
647 }
648 cargo
649 .arg("--manifest-path")
650 .arg(builder.src.join("library/alloc/Cargo.toml"))
651 .arg("--features")
652 .arg(features);
653 } else {
654 features += &builder.std_features(target);
655 features.push_str(compiler_builtins_c_feature);
656
657 cargo
658 .arg("--features")
659 .arg(features)
660 .arg("--manifest-path")
661 .arg(builder.src.join("library/sysroot/Cargo.toml"));
662
663 if target.contains("musl")
666 && let Some(p) = builder.musl_libdir(target)
667 {
668 let root = format!("native={}", p.to_str().unwrap());
669 cargo.rustflag("-L").rustflag(&root);
670 }
671
672 if target.contains("-wasi")
673 && let Some(dir) = builder.wasi_libdir(target)
674 {
675 let root = format!("native={}", dir.to_str().unwrap());
676 cargo.rustflag("-L").rustflag(&root);
677 }
678 }
679
680 if builder.config.rust_lto == RustcLto::Off {
681 cargo.rustflag("-Clto=off");
682 }
683
684 if target.contains("riscv") {
691 cargo.rustflag("-Cforce-unwind-tables=yes");
692 }
693
694 let html_root =
695 format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
696 cargo.rustflag(&html_root);
697 cargo.rustdocflag(&html_root);
698
699 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
700}
701
702#[derive(Debug, Clone, PartialEq, Eq, Hash)]
711pub struct StdLink {
712 pub compiler: Compiler,
713 pub target_compiler: Compiler,
714 pub target: TargetSelection,
715 crates: Vec<String>,
717 force_recompile: bool,
719}
720
721impl StdLink {
722 pub fn from_std(std: Std, host_compiler: Compiler) -> Self {
723 Self {
724 compiler: host_compiler,
725 target_compiler: std.build_compiler,
726 target: std.target,
727 crates: std.crates,
728 force_recompile: std.force_recompile,
729 }
730 }
731}
732
733impl Step for StdLink {
734 type Output = ();
735
736 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
737 run.never()
738 }
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 .build
772 .config
773 .initial_rustc
774 .starts_with(builder.out.join(compiler.host).join("stage0/bin"));
775
776 if compiler.stage == 0 && is_downloaded_beta_stage0 {
780 let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
782
783 let host = compiler.host;
784 let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
785 let sysroot_bin_dir = sysroot.join("bin");
786 t!(fs::create_dir_all(&sysroot_bin_dir));
787 builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
788
789 let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
790 t!(fs::create_dir_all(sysroot.join("lib")));
791 builder.cp_link_r(&stage0_lib_dir, &sysroot.join("lib"));
792
793 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
795 t!(fs::create_dir_all(&sysroot_codegen_backends));
796 let stage0_codegen_backends = builder
797 .out
798 .join(host)
799 .join("stage0/lib/rustlib")
800 .join(host)
801 .join("codegen-backends");
802 if stage0_codegen_backends.exists() {
803 builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
804 }
805 } else if compiler.stage == 0 {
806 let sysroot = builder.out.join(compiler.host.triple).join("stage0-sysroot");
807
808 if builder.local_rebuild {
809 let _ = fs::remove_dir_all(sysroot.join("lib/rustlib/src/rust"));
813 }
814
815 builder.cp_link_r(&builder.initial_sysroot.join("lib"), &sysroot.join("lib"));
816 } else {
817 if builder.download_rustc() {
818 let _ = fs::remove_dir_all(&libdir);
820 let _ = fs::remove_dir_all(&hostdir);
821 }
822
823 add_to_sysroot(
824 builder,
825 &libdir,
826 &hostdir,
827 &build_stamp::libstd_stamp(builder, compiler, target),
828 );
829 }
830 }
831}
832
833fn copy_sanitizers(
835 builder: &Builder<'_>,
836 compiler: &Compiler,
837 target: TargetSelection,
838) -> Vec<PathBuf> {
839 let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
840
841 if builder.config.dry_run() {
842 return Vec::new();
843 }
844
845 let mut target_deps = Vec::new();
846 let libdir = builder.sysroot_target_libdir(*compiler, target);
847
848 for runtime in &runtimes {
849 let dst = libdir.join(&runtime.name);
850 builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
851
852 if target == "x86_64-apple-darwin"
856 || target == "aarch64-apple-darwin"
857 || target == "aarch64-apple-ios"
858 || target == "aarch64-apple-ios-sim"
859 || target == "x86_64-apple-ios"
860 {
861 apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
863 apple_darwin_sign_file(builder, &dst);
866 }
867
868 target_deps.push(dst);
869 }
870
871 target_deps
872}
873
874fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
875 command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
876}
877
878fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
879 command("codesign")
880 .arg("-f") .arg("-s")
882 .arg("-")
883 .arg(file_path)
884 .run(builder);
885}
886
887#[derive(Debug, Clone, PartialEq, Eq, Hash)]
888pub struct StartupObjects {
889 pub compiler: Compiler,
890 pub target: TargetSelection,
891}
892
893impl Step for StartupObjects {
894 type Output = Vec<(PathBuf, DependencyType)>;
895
896 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
897 run.path("library/rtstartup")
898 }
899
900 fn make_run(run: RunConfig<'_>) {
901 run.builder.ensure(StartupObjects {
902 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
903 target: run.target,
904 });
905 }
906
907 fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
914 let for_compiler = self.compiler;
915 let target = self.target;
916 if !target.is_windows_gnu() {
919 return vec![];
920 }
921
922 let mut target_deps = vec![];
923
924 let src_dir = &builder.src.join("library").join("rtstartup");
925 let dst_dir = &builder.native_dir(target).join("rtstartup");
926 let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
927 t!(fs::create_dir_all(dst_dir));
928
929 for file in &["rsbegin", "rsend"] {
930 let src_file = &src_dir.join(file.to_string() + ".rs");
931 let dst_file = &dst_dir.join(file.to_string() + ".o");
932 if !up_to_date(src_file, dst_file) {
933 let mut cmd = command(&builder.initial_rustc);
934 cmd.env("RUSTC_BOOTSTRAP", "1");
935 if !builder.local_rebuild {
936 cmd.arg("--cfg").arg("bootstrap");
938 }
939 cmd.arg("--target")
940 .arg(target.rustc_target_arg())
941 .arg("--emit=obj")
942 .arg("-o")
943 .arg(dst_file)
944 .arg(src_file)
945 .run(builder);
946 }
947
948 let obj = sysroot_dir.join((*file).to_string() + ".o");
949 builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
950 target_deps.push((obj, DependencyType::Target));
951 }
952
953 target_deps
954 }
955}
956
957fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
958 let ci_rustc_dir = builder.config.ci_rustc_dir();
959
960 for file in contents {
961 let src = ci_rustc_dir.join(&file);
962 let dst = sysroot.join(file);
963 if src.is_dir() {
964 t!(fs::create_dir_all(dst));
965 } else {
966 builder.copy_link(&src, &dst, FileType::Regular);
967 }
968 }
969}
970
971#[derive(Clone, Debug)]
973pub struct BuiltRustc {
974 pub build_compiler: Compiler,
978}
979
980#[derive(Debug, Clone, PartialEq, Eq, Hash)]
987pub struct Rustc {
988 pub target: TargetSelection,
990 pub build_compiler: Compiler,
992 crates: Vec<String>,
998}
999
1000impl Rustc {
1001 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
1002 Self { target, build_compiler, crates: Default::default() }
1003 }
1004}
1005
1006impl Step for Rustc {
1007 type Output = BuiltRustc;
1008 const IS_HOST: bool = true;
1009
1010 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1011 let mut crates = run.builder.in_tree_crates("rustc-main", None);
1012 for (i, krate) in crates.iter().enumerate() {
1013 if krate.name == "rustc-main" {
1016 crates.swap_remove(i);
1017 break;
1018 }
1019 }
1020 run.crates(crates)
1021 }
1022
1023 fn is_default_step(_builder: &Builder<'_>) -> bool {
1024 false
1025 }
1026
1027 fn make_run(run: RunConfig<'_>) {
1028 if run.builder.paths == vec![PathBuf::from("compiler")] {
1031 return;
1032 }
1033
1034 let crates = run.cargo_crates_in_set();
1035 run.builder.ensure(Rustc {
1036 build_compiler: run
1037 .builder
1038 .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1039 target: run.target,
1040 crates,
1041 });
1042 }
1043
1044 fn run(self, builder: &Builder<'_>) -> Self::Output {
1050 let build_compiler = self.build_compiler;
1051 let target = self.target;
1052
1053 if builder.download_rustc() && build_compiler.stage != 0 {
1056 trace!(stage = build_compiler.stage, "`download_rustc` requested");
1057
1058 let sysroot =
1059 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
1060 cp_rustc_component_to_ci_sysroot(
1061 builder,
1062 &sysroot,
1063 builder.config.ci_rustc_dev_contents(),
1064 );
1065 return BuiltRustc { build_compiler };
1066 }
1067
1068 builder.std(build_compiler, target);
1071
1072 if builder.config.keep_stage.contains(&build_compiler.stage) {
1073 trace!(stage = build_compiler.stage, "`keep-stage` requested");
1074
1075 builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1076 builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1077 builder.ensure(RustcLink::from_rustc(self));
1078
1079 return BuiltRustc { build_compiler };
1080 }
1081
1082 let stage = build_compiler.stage + 1;
1084
1085 if build_compiler.stage >= 2
1090 && !builder.config.full_bootstrap
1091 && target == builder.host_target
1092 {
1093 let uplift_build_compiler = builder.compiler(1, build_compiler.host);
1097
1098 let msg = format!("Uplifting rustc from stage2 to stage{stage})");
1099 builder.info(&msg);
1100
1101 builder.ensure(RustcLink::from_build_compiler_and_sysroot(
1105 uplift_build_compiler,
1107 build_compiler,
1109 target,
1110 self.crates,
1111 ));
1112
1113 return BuiltRustc { build_compiler: uplift_build_compiler };
1116 }
1117
1118 builder.std(
1124 builder.compiler(self.build_compiler.stage, builder.config.host_target),
1125 builder.config.host_target,
1126 );
1127
1128 let mut cargo = builder::Cargo::new(
1129 builder,
1130 build_compiler,
1131 Mode::Rustc,
1132 SourceType::InTree,
1133 target,
1134 Kind::Build,
1135 );
1136
1137 rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
1138
1139 for krate in &*self.crates {
1143 cargo.arg("-p").arg(krate);
1144 }
1145
1146 if builder.build.config.enable_bolt_settings && build_compiler.stage == 1 {
1147 cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1149 }
1150
1151 let _guard = builder.msg(
1152 Kind::Build,
1153 format_args!("compiler artifacts{}", crate_description(&self.crates)),
1154 Mode::Rustc,
1155 build_compiler,
1156 target,
1157 );
1158 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
1159
1160 run_cargo(
1161 builder,
1162 cargo,
1163 vec![],
1164 &stamp,
1165 vec![],
1166 ArtifactKeepMode::Custom(Box::new(|filename| {
1167 if filename.contains("jemalloc_sys")
1168 || filename.contains("rustc_public_bridge")
1169 || filename.contains("rustc_public")
1170 {
1171 filename.ends_with(".rlib")
1174 } else {
1175 filename.ends_with(".rmeta")
1179 }
1180 })),
1181 );
1182
1183 let target_root_dir = stamp.path().parent().unwrap();
1184 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1190 && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1191 {
1192 let rustc_driver = target_root_dir.join("librustc_driver.so");
1193 strip_debug(builder, target, &rustc_driver);
1194 }
1195
1196 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1197 strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1200 }
1201
1202 builder.ensure(RustcLink::from_rustc(self));
1203 BuiltRustc { build_compiler }
1204 }
1205
1206 fn metadata(&self) -> Option<StepMetadata> {
1207 Some(StepMetadata::build("rustc", self.target).built_by(self.build_compiler))
1208 }
1209}
1210
1211pub fn rustc_cargo(
1212 builder: &Builder<'_>,
1213 cargo: &mut Cargo,
1214 target: TargetSelection,
1215 build_compiler: &Compiler,
1216 crates: &[String],
1217) {
1218 cargo
1219 .arg("--features")
1220 .arg(builder.rustc_features(builder.kind, target, crates))
1221 .arg("--manifest-path")
1222 .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1223
1224 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1225
1226 cargo.rustflag("-Zon-broken-pipe=kill");
1240
1241 if builder.build.config.bootstrap_override_lld.is_used() {
1246 cargo.rustflag("-Zdefault-visibility=protected");
1247 }
1248
1249 if is_lto_stage(build_compiler) {
1250 match builder.config.rust_lto {
1251 RustcLto::Thin | RustcLto::Fat => {
1252 cargo.rustflag("-Zdylib-lto");
1255 let lto_type = match builder.config.rust_lto {
1259 RustcLto::Thin => "thin",
1260 RustcLto::Fat => "fat",
1261 _ => unreachable!(),
1262 };
1263 cargo.rustflag(&format!("-Clto={lto_type}"));
1264 cargo.rustflag("-Cembed-bitcode=yes");
1265 }
1266 RustcLto::ThinLocal => { }
1267 RustcLto::Off => {
1268 cargo.rustflag("-Clto=off");
1269 }
1270 }
1271 } else if builder.config.rust_lto == RustcLto::Off {
1272 cargo.rustflag("-Clto=off");
1273 }
1274
1275 if builder.config.bootstrap_override_lld.is_used() && !build_compiler.host.is_msvc() {
1283 cargo.rustflag("-Clink-args=-Wl,--icf=all");
1284 }
1285
1286 if builder.config.rust_profile_use.is_some() && builder.config.rust_profile_generate.is_some() {
1287 panic!("Cannot use and generate PGO profiles at the same time");
1288 }
1289 let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
1290 if build_compiler.stage == 1 {
1291 cargo.rustflag(&format!("-Cprofile-generate={path}"));
1292 cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
1295 true
1296 } else {
1297 false
1298 }
1299 } else if let Some(path) = &builder.config.rust_profile_use {
1300 if build_compiler.stage == 1 {
1301 cargo.rustflag(&format!("-Cprofile-use={path}"));
1302 if builder.is_verbose() {
1303 cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
1304 }
1305 true
1306 } else {
1307 false
1308 }
1309 } else {
1310 false
1311 };
1312 if is_collecting {
1313 cargo.rustflag(&format!(
1315 "-Cllvm-args=-static-func-strip-dirname-prefix={}",
1316 builder.config.src.components().count()
1317 ));
1318 }
1319
1320 if let Some(ref ccache) = builder.config.ccache
1325 && build_compiler.stage == 0
1326 && !builder.config.incremental
1327 {
1328 cargo.env("RUSTC_WRAPPER", ccache);
1329 }
1330
1331 rustc_cargo_env(builder, cargo, target);
1332}
1333
1334pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1335 cargo
1338 .env("CFG_RELEASE", builder.rust_release())
1339 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1340 .env("CFG_VERSION", builder.rust_version());
1341
1342 if builder.config.omit_git_hash {
1346 cargo.env("CFG_OMIT_GIT_HASH", "1");
1347 }
1348
1349 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", builder.config.default_codegen_backend(target).name());
1350
1351 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1352 let target_config = builder.config.target_config.get(&target);
1353
1354 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1355
1356 if let Some(ref ver_date) = builder.rust_info().commit_date() {
1357 cargo.env("CFG_VER_DATE", ver_date);
1358 }
1359 if let Some(ref ver_hash) = builder.rust_info().sha() {
1360 cargo.env("CFG_VER_HASH", ver_hash);
1361 }
1362 if !builder.unstable_features() {
1363 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1364 }
1365
1366 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1369 cargo.env("CFG_DEFAULT_LINKER", s);
1370 } else if let Some(ref s) = builder.config.rustc_default_linker {
1371 cargo.env("CFG_DEFAULT_LINKER", s);
1372 }
1373
1374 if let Some(linker) = target_config.map(|c| c.default_linker_linux_override) {
1376 match linker {
1377 DefaultLinuxLinkerOverride::Off => {}
1378 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1379 cargo.env("CFG_DEFAULT_LINKER_SELF_CONTAINED_LLD_CC", "1");
1380 }
1381 }
1382 }
1383
1384 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1386
1387 if builder.config.rust_verify_llvm_ir {
1388 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1389 }
1390
1391 if builder.config.llvm_enabled(target) {
1403 let building_llvm_is_expensive =
1404 crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false)
1405 .should_build();
1406
1407 let skip_llvm = (builder.kind == Kind::Check) && building_llvm_is_expensive;
1408 if !skip_llvm {
1409 rustc_llvm_env(builder, cargo, target)
1410 }
1411 }
1412
1413 if builder.config.jemalloc(target) && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none() {
1415 if target.starts_with("aarch64") {
1418 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1419 }
1420 else if target.starts_with("loongarch") {
1422 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "14");
1423 }
1424 }
1425}
1426
1427fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1433 if builder.config.is_rust_llvm(target) {
1434 cargo.env("LLVM_RUSTLLVM", "1");
1435 }
1436 if builder.config.llvm_enzyme {
1437 cargo.env("LLVM_ENZYME", "1");
1438 }
1439 let llvm::LlvmResult { host_llvm_config, .. } = builder.ensure(llvm::Llvm { target });
1440 if builder.config.llvm_offload {
1441 builder.ensure(llvm::OmpOffload { target });
1442 cargo.env("LLVM_OFFLOAD", "1");
1443 }
1444
1445 cargo.env("LLVM_CONFIG", &host_llvm_config);
1446
1447 let mut llvm_linker_flags = String::new();
1457 if builder.config.llvm_profile_generate
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 builder.llvm_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}
1508
1509#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1522struct RustcLink {
1523 build_compiler: Compiler,
1525 sysroot_compiler: Compiler,
1528 target: TargetSelection,
1529 crates: Vec<String>,
1531}
1532
1533impl RustcLink {
1534 fn from_rustc(rustc: Rustc) -> Self {
1537 Self {
1538 build_compiler: rustc.build_compiler,
1539 sysroot_compiler: rustc.build_compiler,
1540 target: rustc.target,
1541 crates: rustc.crates,
1542 }
1543 }
1544
1545 fn from_build_compiler_and_sysroot(
1547 build_compiler: Compiler,
1548 sysroot_compiler: Compiler,
1549 target: TargetSelection,
1550 crates: Vec<String>,
1551 ) -> Self {
1552 Self { build_compiler, sysroot_compiler, target, crates }
1553 }
1554}
1555
1556impl Step for RustcLink {
1557 type Output = ();
1558
1559 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1560 run.never()
1561 }
1562
1563 fn run(self, builder: &Builder<'_>) {
1565 let build_compiler = self.build_compiler;
1566 let sysroot_compiler = self.sysroot_compiler;
1567 let target = self.target;
1568 add_to_sysroot(
1569 builder,
1570 &builder.sysroot_target_libdir(sysroot_compiler, target),
1571 &builder.sysroot_target_libdir(sysroot_compiler, sysroot_compiler.host),
1572 &build_stamp::librustc_stamp(builder, build_compiler, target),
1573 );
1574 }
1575}
1576
1577#[derive(Clone)]
1583pub struct GccDylibSet {
1584 dylibs: BTreeMap<GccTargetPair, GccOutput>,
1585}
1586
1587impl GccDylibSet {
1588 pub fn build(
1591 builder: &Builder<'_>,
1592 host: TargetSelection,
1593 targets: Vec<TargetSelection>,
1594 ) -> Self {
1595 let dylibs = targets
1596 .iter()
1597 .map(|t| GccTargetPair::for_target_pair(host, *t))
1598 .map(|target_pair| (target_pair, builder.ensure(Gcc { target_pair })))
1599 .collect();
1600 Self { dylibs }
1601 }
1602
1603 pub fn install_to(&self, builder: &Builder<'_>, compiler: Compiler) {
1607 if builder.config.dry_run() {
1608 return;
1609 }
1610
1611 let cg_sysroot = builder.sysroot_codegen_backends(compiler);
1613
1614 for (target_pair, libgccjit) in &self.dylibs {
1615 assert_eq!(
1616 target_pair.host(),
1617 compiler.host,
1618 "Trying to install libgccjit ({target_pair}) to a compiler with a different host ({})",
1619 compiler.host
1620 );
1621 let libgccjit_path = libgccjit.libgccjit();
1622
1623 let libgccjit_path = t!(
1627 libgccjit_path.canonicalize(),
1628 format!("Cannot find libgccjit at {}", libgccjit_path.display())
1629 );
1630
1631 let dst = cg_sysroot.join(libgccjit_path_relative_to_cg_dir(target_pair, libgccjit));
1632 t!(std::fs::create_dir_all(dst.parent().unwrap()));
1633 builder.copy_link(&libgccjit_path, &dst, FileType::NativeLibrary);
1634 }
1635 }
1636}
1637
1638pub fn libgccjit_path_relative_to_cg_dir(
1641 target_pair: &GccTargetPair,
1642 libgccjit: &GccOutput,
1643) -> PathBuf {
1644 let target_filename = libgccjit.libgccjit().file_name().unwrap().to_str().unwrap();
1645
1646 Path::new("lib").join(target_pair.target()).join(target_filename)
1648}
1649
1650#[derive(Clone)]
1654pub struct GccCodegenBackendOutput {
1655 stamp: BuildStamp,
1656}
1657
1658impl GccCodegenBackendOutput {
1659 pub fn stamp(&self) -> &BuildStamp {
1660 &self.stamp
1661 }
1662}
1663
1664#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1671pub struct GccCodegenBackend {
1672 compilers: RustcPrivateCompilers,
1673 target: TargetSelection,
1674}
1675
1676impl GccCodegenBackend {
1677 pub fn for_target(compilers: RustcPrivateCompilers, target: TargetSelection) -> Self {
1679 Self { compilers, target }
1680 }
1681}
1682
1683impl Step for GccCodegenBackend {
1684 type Output = GccCodegenBackendOutput;
1685
1686 const IS_HOST: bool = true;
1687
1688 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1689 run.alias("rustc_codegen_gcc").alias("cg_gcc")
1690 }
1691
1692 fn make_run(run: RunConfig<'_>) {
1693 let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target);
1694 run.builder.ensure(GccCodegenBackend::for_target(compilers, run.target));
1695 }
1696
1697 fn run(self, builder: &Builder<'_>) -> Self::Output {
1698 let host = self.compilers.target();
1699 let build_compiler = self.compilers.build_compiler();
1700
1701 let stamp = build_stamp::codegen_backend_stamp(
1702 builder,
1703 build_compiler,
1704 host,
1705 &CodegenBackendKind::Gcc,
1706 );
1707
1708 if builder.config.keep_stage.contains(&build_compiler.stage) && stamp.path().exists() {
1709 trace!("`keep-stage` requested");
1710 builder.info(
1711 "WARNING: Using a potentially old codegen backend. \
1712 This may not behave well.",
1713 );
1714 return GccCodegenBackendOutput { stamp };
1717 }
1718
1719 let mut cargo = builder::Cargo::new(
1720 builder,
1721 build_compiler,
1722 Mode::Codegen,
1723 SourceType::InTree,
1724 host,
1725 Kind::Build,
1726 );
1727 cargo.arg("--manifest-path").arg(builder.src.join("compiler/rustc_codegen_gcc/Cargo.toml"));
1728 rustc_cargo_env(builder, &mut cargo, host);
1729
1730 let _guard =
1731 builder.msg(Kind::Build, "codegen backend gcc", Mode::Codegen, build_compiler, host);
1732 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyRlib);
1733
1734 GccCodegenBackendOutput {
1735 stamp: write_codegen_backend_stamp(stamp, files, builder.config.dry_run()),
1736 }
1737 }
1738
1739 fn metadata(&self) -> Option<StepMetadata> {
1740 Some(
1741 StepMetadata::build("rustc_codegen_gcc", self.compilers.target())
1742 .built_by(self.compilers.build_compiler()),
1743 )
1744 }
1745}
1746
1747#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1748pub struct CraneliftCodegenBackend {
1749 pub compilers: RustcPrivateCompilers,
1750}
1751
1752impl Step for CraneliftCodegenBackend {
1753 type Output = BuildStamp;
1754 const IS_HOST: bool = true;
1755
1756 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1757 run.alias("rustc_codegen_cranelift").alias("cg_clif")
1758 }
1759
1760 fn make_run(run: RunConfig<'_>) {
1761 run.builder.ensure(CraneliftCodegenBackend {
1762 compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1763 });
1764 }
1765
1766 fn run(self, builder: &Builder<'_>) -> Self::Output {
1767 let target = self.compilers.target();
1768 let build_compiler = self.compilers.build_compiler();
1769
1770 let stamp = build_stamp::codegen_backend_stamp(
1771 builder,
1772 build_compiler,
1773 target,
1774 &CodegenBackendKind::Cranelift,
1775 );
1776
1777 if builder.config.keep_stage.contains(&build_compiler.stage) {
1778 trace!("`keep-stage` requested");
1779 builder.info(
1780 "WARNING: Using a potentially old codegen backend. \
1781 This may not behave well.",
1782 );
1783 return stamp;
1786 }
1787
1788 let mut cargo = builder::Cargo::new(
1789 builder,
1790 build_compiler,
1791 Mode::Codegen,
1792 SourceType::InTree,
1793 target,
1794 Kind::Build,
1795 );
1796 cargo
1797 .arg("--manifest-path")
1798 .arg(builder.src.join("compiler/rustc_codegen_cranelift/Cargo.toml"));
1799 rustc_cargo_env(builder, &mut cargo, target);
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::OnlyRlib);
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| {
1831 let filename = f.file_name().unwrap().to_str().unwrap();
1832 is_dylib(f) && filename.contains("rustc_codegen_")
1833 });
1834 let codegen_backend = match files.next() {
1835 Some(f) => f,
1836 None => panic!("no dylibs built for codegen backend?"),
1837 };
1838 if let Some(f) = files.next() {
1839 panic!("codegen backend built two dylibs:\n{}\n{}", codegen_backend.display(), f.display());
1840 }
1841
1842 let codegen_backend = codegen_backend.to_str().unwrap();
1843 stamp = stamp.add_stamp(codegen_backend);
1844 t!(stamp.write());
1845 stamp
1846}
1847
1848fn copy_codegen_backends_to_sysroot(
1855 builder: &Builder<'_>,
1856 stamp: BuildStamp,
1857 target_compiler: Compiler,
1858) {
1859 let dst = builder.sysroot_codegen_backends(target_compiler);
1868 t!(fs::create_dir_all(&dst), dst);
1869
1870 if builder.config.dry_run() {
1871 return;
1872 }
1873
1874 if stamp.path().exists() {
1875 let file = get_codegen_backend_file(&stamp);
1876 builder.copy_link(
1877 &file,
1878 &dst.join(normalize_codegen_backend_name(builder, &file)),
1879 FileType::NativeLibrary,
1880 );
1881 }
1882}
1883
1884pub fn get_codegen_backend_file(stamp: &BuildStamp) -> PathBuf {
1886 PathBuf::from(t!(fs::read_to_string(stamp.path())))
1887}
1888
1889pub fn normalize_codegen_backend_name(builder: &Builder<'_>, path: &Path) -> String {
1891 let filename = path.file_name().unwrap().to_str().unwrap();
1892 let dash = filename.find('-').unwrap();
1895 let dot = filename.find('.').unwrap();
1896 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1897}
1898
1899pub fn compiler_file(
1900 builder: &Builder<'_>,
1901 compiler: &Path,
1902 target: TargetSelection,
1903 c: CLang,
1904 file: &str,
1905) -> PathBuf {
1906 if builder.config.dry_run() {
1907 return PathBuf::new();
1908 }
1909 let mut cmd = command(compiler);
1910 cmd.args(builder.cc_handled_clags(target, c));
1911 cmd.args(builder.cc_unhandled_cflags(target, GitRepo::Rustc, c));
1912 cmd.arg(format!("-print-file-name={file}"));
1913 let out = cmd.run_capture_stdout(builder).stdout();
1914 PathBuf::from(out.trim())
1915}
1916
1917#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1918pub struct Sysroot {
1919 pub compiler: Compiler,
1920 force_recompile: bool,
1922}
1923
1924impl Sysroot {
1925 pub(crate) fn new(compiler: Compiler) -> Self {
1926 Sysroot { compiler, force_recompile: false }
1927 }
1928}
1929
1930impl Step for Sysroot {
1931 type Output = PathBuf;
1932
1933 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1934 run.never()
1935 }
1936
1937 fn run(self, builder: &Builder<'_>) -> PathBuf {
1941 let compiler = self.compiler;
1942 let host_dir = builder.out.join(compiler.host);
1943
1944 let sysroot_dir = |stage| {
1945 if stage == 0 {
1946 host_dir.join("stage0-sysroot")
1947 } else if self.force_recompile && stage == compiler.stage {
1948 host_dir.join(format!("stage{stage}-test-sysroot"))
1949 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1950 host_dir.join("ci-rustc-sysroot")
1951 } else {
1952 host_dir.join(format!("stage{stage}"))
1953 }
1954 };
1955 let sysroot = sysroot_dir(compiler.stage);
1956 trace!(stage = ?compiler.stage, ?sysroot);
1957
1958 builder.do_if_verbose(|| {
1959 println!("Removing sysroot {} to avoid caching bugs", sysroot.display())
1960 });
1961 let _ = fs::remove_dir_all(&sysroot);
1962 t!(fs::create_dir_all(&sysroot));
1963
1964 if compiler.stage == 0 {
1971 dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1972 }
1973
1974 if builder.download_rustc() && compiler.stage != 0 {
1976 assert_eq!(
1977 builder.config.host_target, compiler.host,
1978 "Cross-compiling is not yet supported with `download-rustc`",
1979 );
1980
1981 for stage in 0..=2 {
1983 if stage != compiler.stage {
1984 let dir = sysroot_dir(stage);
1985 if !dir.ends_with("ci-rustc-sysroot") {
1986 let _ = fs::remove_dir_all(dir);
1987 }
1988 }
1989 }
1990
1991 let mut filtered_files = Vec::new();
2001 let mut add_filtered_files = |suffix, contents| {
2002 for path in contents {
2003 let path = Path::new(&path);
2004 if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
2005 filtered_files.push(path.file_name().unwrap().to_owned());
2006 }
2007 }
2008 };
2009 let suffix = format!("lib/rustlib/{}/lib", compiler.host);
2010 add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
2011 add_filtered_files("lib", builder.config.ci_rust_std_contents());
2014
2015 let filtered_extensions = [
2016 OsStr::new("rmeta"),
2017 OsStr::new("rlib"),
2018 OsStr::new(std::env::consts::DLL_EXTENSION),
2020 ];
2021 let ci_rustc_dir = builder.config.ci_rustc_dir();
2022 builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
2023 if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
2024 return true;
2025 }
2026 if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
2027 return true;
2028 }
2029 filtered_files.iter().all(|f| f != path.file_name().unwrap())
2030 });
2031 }
2032
2033 if compiler.stage != 0 {
2039 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
2040 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
2041 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
2042 if let Err(e) =
2043 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust)
2044 {
2045 eprintln!(
2046 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2047 sysroot_lib_rustlib_src_rust.display(),
2048 builder.src.display(),
2049 e,
2050 );
2051 if builder.config.rust_remap_debuginfo {
2052 eprintln!(
2053 "ERROR: some `tests/ui` tests will fail when lacking `{}`",
2054 sysroot_lib_rustlib_src_rust.display(),
2055 );
2056 }
2057 build_helper::exit!(1);
2058 }
2059 }
2060
2061 if !builder.download_rustc() {
2063 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
2064 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
2065 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
2066 if let Err(e) =
2067 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
2068 {
2069 eprintln!(
2070 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2071 sysroot_lib_rustlib_rustcsrc_rust.display(),
2072 builder.src.display(),
2073 e,
2074 );
2075 build_helper::exit!(1);
2076 }
2077 }
2078
2079 sysroot
2080 }
2081}
2082
2083#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2090pub struct Assemble {
2091 pub target_compiler: Compiler,
2096}
2097
2098impl Step for Assemble {
2099 type Output = Compiler;
2100 const IS_HOST: bool = true;
2101
2102 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2103 run.path("compiler/rustc").path("compiler")
2104 }
2105
2106 fn make_run(run: RunConfig<'_>) {
2107 run.builder.ensure(Assemble {
2108 target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2109 });
2110 }
2111
2112 fn run(self, builder: &Builder<'_>) -> Compiler {
2113 let target_compiler = self.target_compiler;
2114
2115 if target_compiler.stage == 0 {
2116 trace!("stage 0 build compiler is always available, simply returning");
2117 assert_eq!(
2118 builder.config.host_target, target_compiler.host,
2119 "Cannot obtain compiler for non-native build triple at stage 0"
2120 );
2121 return target_compiler;
2123 }
2124
2125 let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2128 let libdir_bin = libdir.parent().unwrap().join("bin");
2129 t!(fs::create_dir_all(&libdir_bin));
2130
2131 if builder.config.llvm_enabled(target_compiler.host) {
2132 trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
2133
2134 let target = target_compiler.host;
2135 let llvm::LlvmResult { host_llvm_config, .. } = builder.ensure(llvm::Llvm { target });
2136 if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
2137 trace!("LLVM tools enabled");
2138
2139 let host_llvm_bin_dir = command(&host_llvm_config)
2140 .arg("--bindir")
2141 .cached()
2142 .run_capture_stdout(builder)
2143 .stdout()
2144 .trim()
2145 .to_string();
2146
2147 let llvm_bin_dir = if target == builder.host_target {
2148 PathBuf::from(host_llvm_bin_dir)
2149 } else {
2150 let external_llvm_config = builder
2153 .config
2154 .target_config
2155 .get(&target)
2156 .and_then(|t| t.llvm_config.clone());
2157 if let Some(external_llvm_config) = external_llvm_config {
2158 external_llvm_config.parent().unwrap().to_path_buf()
2161 } else {
2162 let host_llvm_out = builder.llvm_out(builder.host_target);
2166 let target_llvm_out = builder.llvm_out(target);
2167 if let Ok(relative_path) =
2168 Path::new(&host_llvm_bin_dir).strip_prefix(host_llvm_out)
2169 {
2170 target_llvm_out.join(relative_path)
2171 } else {
2172 PathBuf::from(
2175 host_llvm_bin_dir
2176 .replace(&*builder.host_target.triple, &target.triple),
2177 )
2178 }
2179 }
2180 };
2181
2182 #[cfg(feature = "tracing")]
2189 let _llvm_tools_span =
2190 span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
2191 .entered();
2192 for tool in LLVM_TOOLS {
2193 trace!("installing `{tool}`");
2194 let tool_exe = exe(tool, target_compiler.host);
2195 let src_path = llvm_bin_dir.join(&tool_exe);
2196
2197 if !src_path.exists() && builder.config.llvm_from_ci {
2199 eprintln!("{} does not exist; skipping copy", src_path.display());
2200 continue;
2201 }
2202
2203 builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2210 }
2211 }
2212 }
2213
2214 let maybe_install_llvm_bitcode_linker = || {
2215 if builder.config.llvm_bitcode_linker_enabled {
2216 trace!("llvm-bitcode-linker enabled, installing");
2217 let llvm_bitcode_linker = builder.ensure(
2218 crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler(
2219 builder,
2220 target_compiler,
2221 ),
2222 );
2223
2224 let bindir_self_contained = builder
2226 .sysroot(target_compiler)
2227 .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host));
2228 let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2229
2230 t!(fs::create_dir_all(&bindir_self_contained));
2231 builder.copy_link(
2232 &llvm_bitcode_linker.tool_path,
2233 &bindir_self_contained.join(tool_exe),
2234 FileType::Executable,
2235 );
2236 }
2237 };
2238
2239 if builder.download_rustc() {
2241 trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2242
2243 builder.std(target_compiler, target_compiler.host);
2244 let sysroot =
2245 builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2246 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2249 if target_compiler.stage == builder.top_stage {
2251 builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage));
2252 }
2253
2254 maybe_install_llvm_bitcode_linker();
2257
2258 return target_compiler;
2259 }
2260
2261 debug!(
2275 "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2276 target_compiler.stage - 1,
2277 builder.config.host_target,
2278 );
2279 let build_compiler =
2280 builder.compiler(target_compiler.stage - 1, builder.config.host_target);
2281
2282 if builder.config.llvm_enzyme {
2284 debug!("`llvm_enzyme` requested");
2285 let enzyme = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2286 let target_libdir =
2287 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2288 let target_dst_lib = target_libdir.join(enzyme.enzyme_filename());
2289 builder.copy_link(&enzyme.enzyme_path(), &target_dst_lib, FileType::NativeLibrary);
2290 }
2291
2292 if builder.config.llvm_offload && !builder.config.dry_run() {
2293 debug!("`llvm_offload` requested");
2294 let offload_install = builder.ensure(llvm::OmpOffload { target: build_compiler.host });
2295 if let Some(_llvm_config) = builder.llvm_config(builder.config.host_target) {
2296 let target_libdir =
2297 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2298 for p in offload_install.offload_paths() {
2299 let libname = p.file_name().unwrap();
2300 let dst_lib = target_libdir.join(libname);
2301 builder.resolve_symlink_and_copy(&p, &dst_lib);
2302 }
2303 }
2308 }
2309
2310 debug!(
2313 ?build_compiler,
2314 "target_compiler.host" = ?target_compiler.host,
2315 "building compiler libraries to link to"
2316 );
2317
2318 let BuiltRustc { build_compiler } =
2320 builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2321
2322 let stage = target_compiler.stage;
2323 let host = target_compiler.host;
2324 let (host_info, dir_name) = if build_compiler.host == host {
2325 ("".into(), "host".into())
2326 } else {
2327 (format!(" ({host})"), host.to_string())
2328 };
2329 let msg = format!(
2334 "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2335 );
2336 builder.info(&msg);
2337
2338 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2340 let proc_macros = builder
2341 .read_stamp_file(&stamp)
2342 .into_iter()
2343 .filter_map(|(path, dependency_type)| {
2344 if dependency_type == DependencyType::Host {
2345 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2346 } else {
2347 None
2348 }
2349 })
2350 .collect::<HashSet<_>>();
2351
2352 let sysroot = builder.sysroot(target_compiler);
2353 let rustc_libdir = builder.rustc_libdir(target_compiler);
2354 t!(fs::create_dir_all(&rustc_libdir));
2355 let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2356 for f in builder.read_dir(&src_libdir) {
2357 let filename = f.file_name().into_string().unwrap();
2358
2359 let is_proc_macro = proc_macros.contains(&filename);
2360 let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2361
2362 let can_be_rustc_dynamic_dep = if builder
2366 .link_std_into_rustc_driver(target_compiler.host)
2367 && !target_compiler.host.is_windows()
2368 {
2369 let is_std = filename.starts_with("std-") || filename.starts_with("libstd-");
2370 !is_std
2371 } else {
2372 true
2373 };
2374
2375 if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2376 builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2377 }
2378 }
2379
2380 {
2381 #[cfg(feature = "tracing")]
2382 let _codegen_backend_span =
2383 span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2384
2385 for backend in builder.config.enabled_codegen_backends(target_compiler.host) {
2386 if builder.kind == Kind::Check && builder.top_stage == 1 {
2403 continue;
2404 }
2405
2406 let prepare_compilers = || {
2407 RustcPrivateCompilers::from_build_and_target_compiler(
2408 build_compiler,
2409 target_compiler,
2410 )
2411 };
2412
2413 match backend {
2414 CodegenBackendKind::Cranelift => {
2415 let stamp = builder
2416 .ensure(CraneliftCodegenBackend { compilers: prepare_compilers() });
2417 copy_codegen_backends_to_sysroot(builder, stamp, target_compiler);
2418 }
2419 CodegenBackendKind::Gcc => {
2420 let compilers = prepare_compilers();
2453 let cg_gcc = builder
2454 .ensure(GccCodegenBackend::for_target(compilers, target_compiler.host));
2455 copy_codegen_backends_to_sysroot(builder, cg_gcc.stamp, target_compiler);
2456
2457 let mut targets = HashSet::new();
2464 for target in &builder.hosts {
2467 targets.insert(*target);
2468 }
2469 for target in &builder.targets {
2471 targets.insert(*target);
2472 }
2473 targets.insert(compilers.target_compiler().host);
2476
2477 let dylib_set = GccDylibSet::build(
2479 builder,
2480 compilers.target_compiler().host,
2481 targets.into_iter().collect(),
2482 );
2483
2484 dylib_set.install_to(builder, target_compiler);
2487 }
2488 CodegenBackendKind::Llvm | CodegenBackendKind::Custom(_) => continue,
2489 }
2490 }
2491 }
2492
2493 if builder.config.lld_enabled {
2494 let lld_wrapper =
2495 builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler(
2496 builder,
2497 target_compiler,
2498 ));
2499 copy_lld_artifacts(builder, lld_wrapper, target_compiler);
2500 }
2501
2502 if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2503 debug!(
2504 "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2505 workaround faulty homebrew `strip`s"
2506 );
2507
2508 let src_exe = exe("llvm-objcopy", target_compiler.host);
2515 let dst_exe = exe("rust-objcopy", target_compiler.host);
2516 builder.copy_link(
2517 &libdir_bin.join(src_exe),
2518 &libdir_bin.join(dst_exe),
2519 FileType::Executable,
2520 );
2521 }
2522
2523 if builder.tool_enabled("wasm-component-ld") {
2526 let wasm_component = builder.ensure(
2527 crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler(
2528 builder,
2529 target_compiler,
2530 ),
2531 );
2532 builder.copy_link(
2533 &wasm_component.tool_path,
2534 &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2535 FileType::Executable,
2536 );
2537 }
2538
2539 maybe_install_llvm_bitcode_linker();
2540
2541 debug!(
2544 "target_compiler.host" = ?target_compiler.host,
2545 ?sysroot,
2546 "ensuring availability of `libLLVM.so` in compiler directory"
2547 );
2548 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2549 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2550
2551 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2553 let rustc = out_dir.join(exe("rustc-main", host));
2554 let bindir = sysroot.join("bin");
2555 t!(fs::create_dir_all(bindir));
2556 let compiler = builder.rustc(target_compiler);
2557 debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2558 builder.copy_link(&rustc, &compiler, FileType::Executable);
2559
2560 target_compiler
2561 }
2562}
2563
2564#[track_caller]
2569pub fn add_to_sysroot(
2570 builder: &Builder<'_>,
2571 sysroot_dst: &Path,
2572 sysroot_host_dst: &Path,
2573 stamp: &BuildStamp,
2574) {
2575 let self_contained_dst = &sysroot_dst.join("self-contained");
2576 t!(fs::create_dir_all(sysroot_dst));
2577 t!(fs::create_dir_all(sysroot_host_dst));
2578 t!(fs::create_dir_all(self_contained_dst));
2579
2580 let mut crates = HashMap::new();
2581 for (path, dependency_type) in builder.read_stamp_file(stamp) {
2582 let filename = path.file_name().unwrap().to_str().unwrap();
2583 let dst = match dependency_type {
2584 DependencyType::Host => {
2585 if sysroot_dst == sysroot_host_dst {
2586 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2589 }
2590
2591 sysroot_host_dst
2592 }
2593 DependencyType::Target => {
2594 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2597
2598 sysroot_dst
2599 }
2600 DependencyType::TargetSelfContained => self_contained_dst,
2601 };
2602 builder.copy_link(&path, &dst.join(filename), FileType::Regular);
2603 }
2604
2605 let mut seen_crates = HashMap::new();
2611 for (filestem, path) in crates {
2612 if !filestem.contains("rustc_") || filestem.contains("rustc_hash") {
2613 continue;
2614 }
2615 if let Some(other_path) =
2616 seen_crates.insert(filestem.split_once('-').unwrap().0.to_owned(), path.clone())
2617 {
2618 panic!(
2619 "duplicate rustc crate {}\n- first copy at {}\n- second copy at {}",
2620 filestem.split_once('-').unwrap().0.to_owned(),
2621 other_path.display(),
2622 path.display(),
2623 );
2624 }
2625 }
2626}
2627
2628pub enum ArtifactKeepMode {
2632 OnlyRlib,
2634 OnlyRmeta,
2636 BothRlibAndRmeta,
2640 Custom(Box<dyn Fn(&str) -> bool>),
2643}
2644
2645pub fn run_cargo(
2646 builder: &Builder<'_>,
2647 cargo: Cargo,
2648 tail_args: Vec<String>,
2649 stamp: &BuildStamp,
2650 additional_target_deps: Vec<(PathBuf, DependencyType)>,
2651 artifact_keep_mode: ArtifactKeepMode,
2652) -> Vec<PathBuf> {
2653 let target_root_dir = stamp.path().parent().unwrap();
2655 let target_deps_dir = target_root_dir.join("deps");
2657 let host_root_dir = target_root_dir
2659 .parent()
2660 .unwrap() .parent()
2662 .unwrap() .join(target_root_dir.file_name().unwrap());
2664
2665 let mut deps = Vec::new();
2669 let mut toplevel = Vec::new();
2670 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2671 let (filenames_vec, crate_types) = match msg {
2672 CargoMessage::CompilerArtifact {
2673 filenames,
2674 target: CargoTarget { crate_types },
2675 ..
2676 } => {
2677 let mut f: Vec<String> = filenames.into_iter().map(|s| s.into_owned()).collect();
2678 f.sort(); (f, crate_types)
2680 }
2681 _ => return,
2682 };
2683 for filename in filenames_vec {
2684 let keep = if filename.ends_with(".lib")
2686 || filename.ends_with(".a")
2687 || is_debug_info(&filename)
2688 || is_dylib(Path::new(&*filename))
2689 {
2690 true
2692 } else {
2693 match &artifact_keep_mode {
2694 ArtifactKeepMode::OnlyRlib => filename.ends_with(".rlib"),
2695 ArtifactKeepMode::OnlyRmeta => filename.ends_with(".rmeta"),
2696 ArtifactKeepMode::BothRlibAndRmeta => {
2697 filename.ends_with(".rmeta") || filename.ends_with(".rlib")
2698 }
2699 ArtifactKeepMode::Custom(func) => func(&filename),
2700 }
2701 };
2702
2703 if !keep {
2704 continue;
2705 }
2706
2707 let filename = Path::new(&*filename);
2708
2709 if filename.starts_with(&host_root_dir) {
2712 if crate_types.iter().any(|t| t == "proc-macro") {
2714 if filename.file_name().unwrap().to_str().unwrap().contains("-") {
2719 deps.push((filename.to_path_buf(), DependencyType::Host));
2720 }
2721 }
2722 continue;
2723 }
2724
2725 if filename.starts_with(&target_deps_dir) {
2728 deps.push((filename.to_path_buf(), DependencyType::Target));
2729 continue;
2730 }
2731
2732 let expected_len = t!(filename.metadata()).len();
2743 let filename = filename.file_name().unwrap().to_str().unwrap();
2744 let mut parts = filename.splitn(2, '.');
2745 let file_stem = parts.next().unwrap().to_owned();
2746 let extension = parts.next().unwrap().to_owned();
2747
2748 toplevel.push((file_stem, extension, expected_len));
2749 }
2750 });
2751
2752 if !ok {
2753 crate::exit!(1);
2754 }
2755
2756 if builder.config.dry_run() {
2757 return Vec::new();
2758 }
2759
2760 let contents = target_deps_dir
2764 .read_dir()
2765 .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_deps_dir.display(), e))
2766 .map(|e| t!(e))
2767 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2768 .collect::<Vec<_>>();
2769 for (prefix, extension, expected_len) in toplevel {
2770 let candidates = contents.iter().filter(|&(_, filename, meta)| {
2771 meta.len() == expected_len
2772 && filename
2773 .strip_prefix(&prefix[..])
2774 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2775 .unwrap_or(false)
2776 });
2777 let max = candidates.max_by_key(|&(_, _, metadata)| {
2778 metadata.modified().expect("mtime should be available on all relevant OSes")
2779 });
2780 let path_to_add = match max {
2781 Some(triple) => triple.0.to_str().unwrap(),
2782 None => panic!("no output generated for {prefix:?} {extension:?}"),
2783 };
2784 if is_dylib(Path::new(path_to_add)) {
2785 let candidate = format!("{path_to_add}.lib");
2786 let candidate = PathBuf::from(candidate);
2787 if candidate.exists() {
2788 deps.push((candidate, DependencyType::Target));
2789 }
2790 }
2791 deps.push((path_to_add.into(), DependencyType::Target));
2792 }
2793
2794 deps.extend(additional_target_deps);
2795 deps.sort();
2796 let mut new_contents = Vec::new();
2797 for (dep, dependency_type) in deps.iter() {
2798 new_contents.extend(match *dependency_type {
2799 DependencyType::Host => b"h",
2800 DependencyType::Target => b"t",
2801 DependencyType::TargetSelfContained => b"s",
2802 });
2803 new_contents.extend(dep.to_str().unwrap().as_bytes());
2804 new_contents.extend(b"\0");
2805 }
2806 t!(fs::write(stamp.path(), &new_contents));
2807 deps.into_iter().map(|(d, _)| d).collect()
2808}
2809
2810pub fn stream_cargo(
2811 builder: &Builder<'_>,
2812 cargo: Cargo,
2813 tail_args: Vec<String>,
2814 cb: &mut dyn FnMut(CargoMessage<'_>),
2815) -> bool {
2816 let mut cmd = cargo.into_cmd();
2817
2818 let mut message_format = if builder.config.json_output {
2821 String::from("json")
2822 } else {
2823 String::from("json-render-diagnostics")
2824 };
2825 if let Some(s) = &builder.config.rustc_error_format {
2826 message_format.push_str(",json-diagnostic-");
2827 message_format.push_str(s);
2828 }
2829 cmd.arg("--message-format").arg(message_format);
2830
2831 for arg in tail_args {
2832 cmd.arg(arg);
2833 }
2834
2835 builder.do_if_verbose(|| println!("running: {cmd:?}"));
2836
2837 let streaming_command = cmd.stream_capture_stdout(&builder.config.exec_ctx);
2838
2839 let Some(mut streaming_command) = streaming_command else {
2840 return true;
2841 };
2842
2843 let stdout = BufReader::new(streaming_command.stdout.take().unwrap());
2847 for line in stdout.lines() {
2848 let line = t!(line);
2849 match serde_json::from_str::<CargoMessage<'_>>(&line) {
2850 Ok(msg) => {
2851 if builder.config.json_output {
2852 println!("{line}");
2854 }
2855 cb(msg)
2856 }
2857 Err(_) => println!("{line}"),
2859 }
2860 }
2861
2862 let status = t!(streaming_command.wait(&builder.config.exec_ctx));
2864 if builder.is_verbose() && !status.success() {
2865 eprintln!(
2866 "command did not execute successfully: {cmd:?}\n\
2867 expected success, got: {status}"
2868 );
2869 }
2870
2871 status.success()
2872}
2873
2874#[derive(Deserialize)]
2875pub struct CargoTarget<'a> {
2876 crate_types: Vec<Cow<'a, str>>,
2877}
2878
2879#[derive(Deserialize)]
2880#[serde(tag = "reason", rename_all = "kebab-case")]
2881pub enum CargoMessage<'a> {
2882 CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2883 BuildScriptExecuted,
2884 BuildFinished,
2885}
2886
2887pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2888 if target != "x86_64-unknown-linux-gnu"
2892 || !builder.config.is_host_target(target)
2893 || !path.exists()
2894 {
2895 return;
2896 }
2897
2898 let previous_mtime = t!(t!(path.metadata()).modified());
2899 let stamp = BuildStamp::new(path.parent().unwrap())
2900 .with_prefix(path.file_name().unwrap().to_str().unwrap())
2901 .with_prefix("strip")
2902 .add_stamp(previous_mtime.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos());
2903
2904 if !stamp.is_up_to_date() {
2907 command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2908 }
2909 t!(stamp.write());
2910
2911 let file = t!(fs::File::open(path));
2912
2913 t!(file.set_modified(previous_mtime));
2926}
2927
2928pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2930 build_compiler.stage != 0
2931}