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::{
26 self, Builder, Cargo, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
27 apply_pgo, crate_description,
28};
29use crate::core::config::toml::target::DefaultLinuxLinkerOverride;
30use crate::core::config::{
31 Allocator, 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, exit, 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 CommandLineStep 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_make_run(&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 if srcdir.join("eh").exists() {
461 copy_and_stamp(
462 builder,
463 &libdir_self_contained,
464 &srcdir.join("eh"),
465 "libunwind.a",
466 &mut target_deps,
467 DependencyType::TargetSelfContained,
468 );
469 }
470 } else if target.is_windows_gnu() || target.is_windows_gnullvm() {
471 for obj in ["crt2.o", "dllcrt2.o"].iter() {
472 let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
473 let dst = libdir_self_contained.join(obj);
474 builder.copy_link(&src, &dst, FileType::NativeLibrary);
475 target_deps.push((dst, DependencyType::TargetSelfContained));
476 }
477 }
478
479 target_deps
480}
481
482pub fn std_crates_for_make_run(run: &RunConfig<'_>) -> Vec<String> {
485 let mut crates = run.make_run_crates(builder::Alias::Library);
486
487 let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
496 if target_is_no_std {
497 crates.retain(|c| c == "core" || c == "alloc");
498 }
499 crates
500}
501
502fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
508 if builder.config.llvm_from_ci {
510 builder.config.maybe_download_ci_llvm();
512 let ci_llvm_compiler_rt = builder.config.ci_llvm_root().join("compiler-rt");
513 if ci_llvm_compiler_rt.exists() {
514 return ci_llvm_compiler_rt;
515 }
516 }
517
518 builder.require_submodule("src/llvm-project", {
520 Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
521 });
522 builder.src.join("src/llvm-project/compiler-rt")
523}
524
525pub fn std_cargo(
528 builder: &Builder<'_>,
529 target: TargetSelection,
530 cargo: &mut Cargo,
531 crates: &[String],
532) {
533 if target.contains("apple") && !builder.config.dry_run() {
551 let mut cmd = builder.rustc_cmd(cargo.compiler());
555 cmd.arg("--target").arg(target.rustc_target_arg());
556 cmd.arg("-Zunstable-options").env("RUSTC_BOOTSTRAP", "1");
559 cmd.arg("--print=deployment-target");
560 let output = cmd.run_capture_stdout(builder).stdout();
561
562 let (env_var, value) = output.split_once('=').unwrap();
563 cargo.env(env_var.trim(), value.trim());
566
567 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
577 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
578 }
579 }
580
581 if let Some(path) = builder.config.profiler_path(target) {
583 cargo.env("LLVM_PROFILER_RT_LIB", path);
584 } else if builder.config.profiler_enabled(target) {
585 let compiler_rt = compiler_rt_for_profiler(builder);
586 cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
590 }
591
592 let compiler_builtins_c_feature = match builder.config.optimized_compiler_builtins(target) {
606 CompilerBuiltins::LinkLLVMBuiltinsLib(path) => {
607 cargo.env("LLVM_COMPILER_RT_LIB", path);
608 " compiler-builtins-c"
609 }
610 CompilerBuiltins::BuildLLVMFuncs => {
611 builder.require_submodule(
621 "src/llvm-project",
622 Some(
623 "The `build.optimized-compiler-builtins` config option \
624 requires `compiler-rt` sources from LLVM.",
625 ),
626 );
627 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
628 if !builder.config.dry_run() {
629 assert!(compiler_builtins_root.exists());
632 }
633
634 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
637 " compiler-builtins-c"
638 }
639 CompilerBuiltins::BuildRustOnly => "",
640 };
641
642 for krate in crates {
643 cargo.args(["-p", krate]);
644 }
645
646 let mut features = String::new();
647
648 if builder.no_std(target) == Some(true) {
649 features += " compiler-builtins-mem";
650 if !target.starts_with("bpf") {
651 features.push_str(compiler_builtins_c_feature);
652 }
653
654 if crates.is_empty() {
656 cargo.args(["-p", "alloc"]);
657 }
658 cargo
659 .arg("--manifest-path")
660 .arg(builder.src.join("library/alloc/Cargo.toml"))
661 .arg("--features")
662 .arg(features);
663 } else {
664 features += &builder.std_features(target);
665 features.push_str(compiler_builtins_c_feature);
666
667 cargo
668 .arg("--features")
669 .arg(features)
670 .arg("--manifest-path")
671 .arg(builder.src.join("library/sysroot/Cargo.toml"));
672
673 if target.contains("musl")
676 && let Some(p) = builder.musl_libdir(target)
677 {
678 let root = format!("native={}", p.to_str().unwrap());
679 cargo.rustflag("-L").rustflag(&root);
680 }
681
682 if target.contains("-wasi")
683 && let Some(dir) = builder.wasi_libdir(target)
684 {
685 let root = format!("native={}", dir.to_str().unwrap());
686 cargo.rustflag("-L").rustflag(&root);
687 }
688 }
689
690 if builder.config.rust_lto == RustcLto::Off {
691 cargo.rustflag("-Clto=off");
692 }
693
694 if target.contains("riscv") {
701 cargo.rustflag("-Cforce-unwind-tables=yes");
702 }
703
704 let html_root =
705 format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
706 cargo.rustflag(&html_root);
707 cargo.rustdocflag(&html_root);
708
709 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
710}
711
712#[derive(Debug, Clone, PartialEq, Eq, Hash)]
721pub struct StdLink {
722 pub compiler: Compiler,
723 pub target_compiler: Compiler,
724 pub target: TargetSelection,
725 crates: Vec<String>,
727 force_recompile: bool,
729}
730
731impl StdLink {
732 pub fn from_std(std: Std, host_compiler: Compiler) -> Self {
733 Self {
734 compiler: host_compiler,
735 target_compiler: std.build_compiler,
736 target: std.target,
737 crates: std.crates,
738 force_recompile: std.force_recompile,
739 }
740 }
741}
742
743impl Step for StdLink {
744 type Output = ();
745
746 fn run(self, builder: &Builder<'_>) {
755 let compiler = self.compiler;
756 let target_compiler = self.target_compiler;
757 let target = self.target;
758
759 let (libdir, hostdir) = if !self.force_recompile && builder.download_rustc() {
761 let lib = builder.sysroot_libdir_relative(self.compiler);
763 let sysroot = builder.ensure(crate::core::build_steps::compile::Sysroot {
764 compiler: self.compiler,
765 force_recompile: self.force_recompile,
766 });
767 let libdir = sysroot.join(lib).join("rustlib").join(target).join("lib");
768 let hostdir = sysroot.join(lib).join("rustlib").join(compiler.host).join("lib");
769 (libdir, hostdir)
770 } else {
771 let libdir = builder.sysroot_target_libdir(target_compiler, target);
772 let hostdir = builder.sysroot_target_libdir(target_compiler, compiler.host);
773 (libdir, hostdir)
774 };
775
776 let is_downloaded_beta_stage0 = builder
777 .build
778 .config
779 .initial_rustc
780 .starts_with(builder.out.join(compiler.host).join("stage0/bin"));
781
782 if compiler.stage == 0 && is_downloaded_beta_stage0 {
786 let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
788
789 let host = compiler.host;
790 let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
791 let sysroot_bin_dir = sysroot.join("bin");
792 t!(fs::create_dir_all(&sysroot_bin_dir));
793 builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
794
795 let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
796 t!(fs::create_dir_all(sysroot.join("lib")));
797 builder.cp_link_r(&stage0_lib_dir, &sysroot.join("lib"));
798
799 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
801 t!(fs::create_dir_all(&sysroot_codegen_backends));
802 let stage0_codegen_backends = builder
803 .out
804 .join(host)
805 .join("stage0/lib/rustlib")
806 .join(host)
807 .join("codegen-backends");
808 if stage0_codegen_backends.exists() {
809 builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
810 }
811 } else if compiler.stage == 0 {
812 let sysroot = builder.out.join(compiler.host.triple).join("stage0-sysroot");
813
814 if builder.local_rebuild {
815 let _ = fs::remove_dir_all(sysroot.join("lib/rustlib/src/rust"));
819 }
820
821 builder.cp_link_r(&builder.initial_sysroot.join("lib"), &sysroot.join("lib"));
822 } else {
823 if builder.download_rustc() {
824 let _ = fs::remove_dir_all(&libdir);
826 let _ = fs::remove_dir_all(&hostdir);
827 }
828
829 add_to_sysroot(
830 builder,
831 &libdir,
832 &hostdir,
833 &build_stamp::libstd_stamp(builder, compiler, target),
834 );
835 }
836 }
837}
838
839fn copy_sanitizers(
841 builder: &Builder<'_>,
842 compiler: &Compiler,
843 target: TargetSelection,
844) -> Vec<PathBuf> {
845 let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
846
847 if builder.config.dry_run() {
848 return Vec::new();
849 }
850
851 let mut target_deps = Vec::new();
852 let libdir = builder.sysroot_target_libdir(*compiler, target);
853
854 for runtime in &runtimes {
855 let dst = libdir.join(&runtime.name);
856 builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
857
858 if target == "x86_64-apple-darwin"
862 || target == "aarch64-apple-darwin"
863 || target == "aarch64-apple-ios"
864 || target == "aarch64-apple-ios-sim"
865 || target == "x86_64-apple-ios"
866 {
867 apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
869 apple_darwin_sign_file(builder, &dst);
872 }
873
874 target_deps.push(dst);
875 }
876
877 target_deps
878}
879
880fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
881 command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
882}
883
884fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
885 command("codesign")
886 .arg("-f") .arg("-s")
888 .arg("-")
889 .arg(file_path)
890 .run(builder);
891}
892
893#[derive(Debug, Clone, PartialEq, Eq, Hash)]
894pub struct StartupObjects {
895 pub compiler: Compiler,
896 pub target: TargetSelection,
897}
898
899impl CommandLineStep for StartupObjects {
900 type Output = Vec<(PathBuf, DependencyType)>;
901
902 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
903 run.path("library/rtstartup")
904 }
905
906 fn make_run(run: RunConfig<'_>) {
907 run.builder.ensure(StartupObjects {
908 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
909 target: run.target,
910 });
911 }
912
913 fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
920 let for_compiler = self.compiler;
921 let target = self.target;
922 if !target.is_windows_gnu() {
925 return vec![];
926 }
927
928 let mut target_deps = vec![];
929
930 let src_dir = &builder.src.join("library").join("rtstartup");
931 let dst_dir = &builder.native_dir(target).join("rtstartup");
932 let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
933 t!(fs::create_dir_all(dst_dir));
934
935 for file in &["rsbegin", "rsend"] {
936 let src_file = &src_dir.join(file.to_string() + ".rs");
937 let dst_file = &dst_dir.join(file.to_string() + ".o");
938 if !up_to_date(src_file, dst_file) {
939 let mut cmd = command(&builder.initial_rustc);
940 cmd.env("RUSTC_BOOTSTRAP", "1");
941 if !builder.local_rebuild {
942 cmd.arg("--cfg").arg("bootstrap");
944 }
945 cmd.arg("--target")
946 .arg(target.rustc_target_arg())
947 .arg("--emit=obj")
948 .arg("-o")
949 .arg(dst_file)
950 .arg(src_file)
951 .run(builder);
952 }
953
954 let obj = sysroot_dir.join((*file).to_string() + ".o");
955 builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
956 target_deps.push((obj, DependencyType::Target));
957 }
958
959 target_deps
960 }
961}
962
963fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
964 let ci_rustc_dir = builder.config.ci_rustc_dir();
965
966 for file in contents {
967 let src = ci_rustc_dir.join(&file);
968 let dst = sysroot.join(file);
969 if src.is_dir() {
970 t!(fs::create_dir_all(dst));
971 } else {
972 builder.copy_link(&src, &dst, FileType::Regular);
973 }
974 }
975}
976
977#[derive(Clone, Debug)]
979pub struct BuiltRustc {
980 pub build_compiler: Compiler,
984}
985
986#[derive(Debug, Clone, PartialEq, Eq, Hash)]
993pub struct Rustc {
994 pub target: TargetSelection,
996 pub build_compiler: Compiler,
998 crates: Vec<String>,
1004}
1005
1006impl Rustc {
1007 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
1008 Self { target, build_compiler, crates: Default::default() }
1009 }
1010}
1011
1012impl CommandLineStep for Rustc {
1013 type Output = BuiltRustc;
1014 const IS_HOST: bool = true;
1015
1016 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1017 run.crate_or_deps_filtered("rustc-main", |krate| {
1018 krate.name != "rustc-main"
1021 })
1022 }
1023
1024 fn is_default_step(_builder: &Builder<'_>) -> bool {
1025 false
1026 }
1027
1028 fn make_run(run: RunConfig<'_>) {
1029 if run.builder.paths == vec![PathBuf::from("compiler")] {
1032 return;
1033 }
1034
1035 let crates = run.cargo_crates_in_set();
1036 run.builder.ensure(Rustc {
1037 build_compiler: run
1038 .builder
1039 .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1040 target: run.target,
1041 crates,
1042 });
1043 }
1044
1045 fn run(self, builder: &Builder<'_>) -> Self::Output {
1051 let build_compiler = self.build_compiler;
1052 let target = self.target;
1053
1054 if builder.download_rustc() && build_compiler.stage != 0 {
1057 trace!(stage = build_compiler.stage, "`download_rustc` requested");
1058
1059 let sysroot =
1060 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
1061 cp_rustc_component_to_ci_sysroot(
1062 builder,
1063 &sysroot,
1064 builder.config.ci_rustc_dev_contents(),
1065 );
1066 return BuiltRustc { build_compiler };
1067 }
1068
1069 builder.std(build_compiler, target);
1072
1073 if builder.config.keep_stage.contains(&build_compiler.stage) {
1074 trace!(stage = build_compiler.stage, "`keep-stage` requested");
1075
1076 builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1077 builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1078 builder.ensure(RustcLink::from_rustc(self));
1079
1080 return BuiltRustc { build_compiler };
1081 }
1082
1083 let stage = build_compiler.stage + 1;
1085
1086 if build_compiler.stage >= 2
1091 && !builder.config.full_bootstrap
1092 && target == builder.host_target
1093 {
1094 let uplift_build_compiler = builder.compiler(1, build_compiler.host);
1098
1099 let msg = format!("Uplifting rustc from stage2 to stage{stage})");
1100 builder.info(&msg);
1101
1102 builder.ensure(RustcLink::from_build_compiler_and_sysroot(
1106 uplift_build_compiler,
1108 build_compiler,
1110 target,
1111 self.crates,
1112 ));
1113
1114 return BuiltRustc { build_compiler: uplift_build_compiler };
1117 }
1118
1119 builder.std(
1125 builder.compiler(self.build_compiler.stage, builder.config.host_target),
1126 builder.config.host_target,
1127 );
1128
1129 let mut cargo = builder::Cargo::new(
1130 builder,
1131 build_compiler,
1132 Mode::Rustc,
1133 SourceType::InTree,
1134 target,
1135 Kind::Build,
1136 );
1137
1138 rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
1139
1140 for krate in &*self.crates {
1144 cargo.arg("-p").arg(krate);
1145 }
1146
1147 if builder.build.config.enable_bolt_settings && build_compiler.stage == 1 {
1148 cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1150 }
1151
1152 let _guard = builder.msg(
1153 Kind::Build,
1154 format_args!("compiler artifacts{}", crate_description(&self.crates)),
1155 Mode::Rustc,
1156 build_compiler,
1157 target,
1158 );
1159 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
1160
1161 run_cargo(
1162 builder,
1163 cargo,
1164 vec![],
1165 &stamp,
1166 vec![],
1167 ArtifactKeepMode::Custom(Box::new(|filename| {
1168 if filename.contains("jemalloc_sys")
1169 || filename.contains("rustc_public_bridge")
1170 || filename.contains("rustc_public")
1171 {
1172 filename.ends_with(".rlib")
1175 } else {
1176 filename.ends_with(".rmeta")
1180 }
1181 })),
1182 );
1183
1184 let target_root_dir = stamp.path().parent().unwrap();
1185 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1191 && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1192 {
1193 let rustc_driver = target_root_dir.join("librustc_driver.so");
1194 strip_debug(builder, target, &rustc_driver);
1195 }
1196
1197 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1198 strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1201 }
1202
1203 builder.ensure(RustcLink::from_rustc(self));
1204 BuiltRustc { build_compiler }
1205 }
1206
1207 fn metadata(&self) -> Option<StepMetadata> {
1208 Some(StepMetadata::build("rustc", self.target).built_by(self.build_compiler))
1209 }
1210}
1211
1212pub fn rustc_cargo(
1213 builder: &Builder<'_>,
1214 cargo: &mut Cargo,
1215 target: TargetSelection,
1216 build_compiler: &Compiler,
1217 crates: &[String],
1218) {
1219 cargo
1220 .arg("--features")
1221 .arg(builder.rustc_features(builder.kind, target, crates))
1222 .arg("--manifest-path")
1223 .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1224
1225 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1226
1227 cargo.rustflag("-Zon-broken-pipe=kill");
1241
1242 if target.is_msvc() {
1247 cargo.rustflag("-Clink-arg=/Brepro");
1248 }
1249
1250 if builder.build.config.bootstrap_override_lld.is_used() {
1255 cargo.rustflag("-Zdefault-visibility=protected");
1256 }
1257
1258 if is_lto_stage(build_compiler) {
1259 match builder.config.rust_lto {
1260 RustcLto::Thin | RustcLto::Fat => {
1261 cargo.rustflag("-Zdylib-lto");
1264 let lto_type = match builder.config.rust_lto {
1268 RustcLto::Thin => "thin",
1269 RustcLto::Fat => "fat",
1270 _ => unreachable!(),
1271 };
1272 cargo.rustflag(&format!("-Clto={lto_type}"));
1273 cargo.rustflag("-Cembed-bitcode=yes");
1274 }
1275 RustcLto::ThinLocal => { }
1276 RustcLto::Off => {
1277 cargo.rustflag("-Clto=off");
1278 }
1279 }
1280 } else if builder.config.rust_lto == RustcLto::Off {
1281 cargo.rustflag("-Clto=off");
1282 }
1283
1284 if builder.config.bootstrap_override_lld.is_used() && !build_compiler.host.is_msvc() {
1292 cargo.rustflag("-Clink-args=-Wl,--icf=all");
1293 }
1294
1295 apply_pgo(builder, cargo, *build_compiler, &builder.config.rust_pgo);
1296
1297 if let Some(ref ccache) = builder.config.ccache
1305 && build_compiler.stage == 0
1306 && !cfg!(windows)
1307 && !builder.config.incremental
1308 {
1309 cargo.env("RUSTC_WRAPPER", ccache);
1310 }
1311
1312 rustc_cargo_env(builder, cargo, target);
1313}
1314
1315pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1316 cargo
1319 .env("CFG_RELEASE", builder.rust_release())
1320 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1321 .env("CFG_VERSION", builder.rust_version());
1322
1323 if builder.config.omit_git_hash {
1327 cargo.env("CFG_OMIT_GIT_HASH", "1");
1328 }
1329
1330 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", builder.config.default_codegen_backend(target).name());
1331
1332 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1333 let target_config = builder.config.target_config.get(&target);
1334
1335 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1336
1337 if let Some(ref ver_date) = builder.rust_info().commit_date() {
1338 cargo.env("CFG_VER_DATE", ver_date);
1339 }
1340 if let Some(ref ver_hash) = builder.rust_info().sha() {
1341 cargo.env("CFG_VER_HASH", ver_hash);
1342 }
1343 if !builder.unstable_features() {
1344 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1345 }
1346
1347 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1350 cargo.env("CFG_DEFAULT_LINKER", s);
1351 } else if let Some(ref s) = builder.config.rustc_default_linker {
1352 cargo.env("CFG_DEFAULT_LINKER", s);
1353 }
1354
1355 if let Some(linker) = target_config.map(|c| c.default_linker_linux_override) {
1357 match linker {
1358 DefaultLinuxLinkerOverride::Off => {}
1359 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1360 cargo.env("CFG_DEFAULT_LINKER_SELF_CONTAINED_LLD_CC", "1");
1361 }
1362 }
1363 }
1364
1365 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1367
1368 if builder.config.rust_verify_llvm_ir {
1369 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1370 }
1371
1372 let nightly = builder.config.channel == "nightly" || builder.config.channel == "dev";
1373 if nightly {
1374 cargo.env("CFG_DEFAULT_POLONIUS_NEXT", "1");
1376 }
1377
1378 if builder.config.llvm_enabled(target) {
1390 let building_llvm_is_expensive =
1391 crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false)
1392 .should_build();
1393
1394 let skip_llvm = (builder.kind == Kind::Check) && building_llvm_is_expensive;
1395 if !skip_llvm {
1396 rustc_llvm_env(builder, cargo, target)
1397 }
1398 }
1399
1400 if builder.config.allocator(target) == Allocator::Jemalloc
1402 && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none()
1403 {
1404 if target.starts_with("aarch64") {
1407 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1408 }
1409 else if target.starts_with("loongarch") {
1411 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "14");
1412 }
1413 }
1414}
1415
1416fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1422 if builder.config.is_rust_llvm(target) {
1423 cargo.env("LLVM_RUSTLLVM", "1");
1424 }
1425 if builder.config.llvm_enzyme {
1426 cargo.env("LLVM_ENZYME", "1");
1427 }
1428 let llvm_output = builder.ensure(llvm::Llvm { target });
1429 if builder.config.llvm_offload {
1430 builder.ensure(llvm::OmpOffload { target });
1431 cargo.env("LLVM_OFFLOAD", "1");
1432 }
1433
1434 cargo.env("LLVM_CONFIG", &llvm_output.host_llvm_config);
1435
1436 let mut llvm_linker_flags = String::new();
1446 if builder.config.llvm_pgo.generate_profile.is_some()
1447 && target.is_msvc()
1448 && let Some(ref clang_cl_path) = builder.config.llvm_clang_cl
1449 {
1450 let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1452 llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
1453 }
1454
1455 if let Some(ref s) = builder.config.llvm_ldflags {
1457 if !llvm_linker_flags.is_empty() {
1458 llvm_linker_flags.push(' ');
1459 }
1460 llvm_linker_flags.push_str(s);
1461 }
1462
1463 if !llvm_linker_flags.is_empty() {
1465 cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
1466 }
1467
1468 if builder.config.llvm_static_stdcpp
1471 && !target.contains("freebsd")
1472 && !target.is_msvc()
1473 && !target.contains("apple")
1474 && !target.contains("solaris")
1475 {
1476 let libstdcxx_name =
1477 if target.contains("windows-gnullvm") { "libc++.a" } else { "libstdc++.a" };
1478 let file = compiler_file(
1479 builder,
1480 &builder.cxx(target).unwrap(),
1481 target,
1482 CLang::Cxx,
1483 libstdcxx_name,
1484 );
1485 cargo.env("LLVM_STATIC_STDCPP", file);
1486 }
1487 if builder.llvm_link_shared() {
1488 cargo.env("LLVM_LINK_SHARED", "1");
1489 }
1490 if builder.config.llvm_use_libcxx {
1491 cargo.env("LLVM_USE_LIBCXX", "1");
1492 }
1493 if builder.config.llvm_assertions {
1494 cargo.env("LLVM_ASSERTIONS", "1");
1495 }
1496 if builder.cxx_tool(target).is_like_gnu() || builder.cc_tool(target).is_like_gnu() {
1497 cargo.env("LLVM_COMPILER_IS_GNU_LIKE", "1");
1498 }
1499}
1500
1501#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1514struct RustcLink {
1515 build_compiler: Compiler,
1517 sysroot_compiler: Compiler,
1520 target: TargetSelection,
1521 crates: Vec<String>,
1523}
1524
1525impl RustcLink {
1526 fn from_rustc(rustc: Rustc) -> Self {
1529 Self {
1530 build_compiler: rustc.build_compiler,
1531 sysroot_compiler: rustc.build_compiler,
1532 target: rustc.target,
1533 crates: rustc.crates,
1534 }
1535 }
1536
1537 fn from_build_compiler_and_sysroot(
1539 build_compiler: Compiler,
1540 sysroot_compiler: Compiler,
1541 target: TargetSelection,
1542 crates: Vec<String>,
1543 ) -> Self {
1544 Self { build_compiler, sysroot_compiler, target, crates }
1545 }
1546}
1547
1548impl Step for RustcLink {
1549 type Output = ();
1550
1551 fn run(self, builder: &Builder<'_>) {
1553 let build_compiler = self.build_compiler;
1554 let sysroot_compiler = self.sysroot_compiler;
1555 let target = self.target;
1556 add_to_sysroot(
1557 builder,
1558 &builder.sysroot_target_libdir(sysroot_compiler, target),
1559 &builder.sysroot_target_libdir(sysroot_compiler, sysroot_compiler.host),
1560 &build_stamp::librustc_stamp(builder, build_compiler, target),
1561 );
1562 }
1563}
1564
1565#[derive(Clone)]
1571pub struct GccDylibSet {
1572 dylibs: BTreeMap<GccTargetPair, GccOutput>,
1573}
1574
1575impl GccDylibSet {
1576 pub fn build(
1579 builder: &Builder<'_>,
1580 host: TargetSelection,
1581 targets: Vec<TargetSelection>,
1582 ) -> Self {
1583 let dylibs = targets
1584 .iter()
1585 .map(|t| GccTargetPair::for_target_pair(host, *t))
1586 .map(|target_pair| (target_pair, builder.ensure(Gcc { target_pair })))
1587 .collect();
1588 Self { dylibs }
1589 }
1590
1591 pub fn install_to(&self, builder: &Builder<'_>, compiler: Compiler) {
1595 if builder.config.dry_run() {
1596 return;
1597 }
1598
1599 let cg_sysroot = builder.sysroot_codegen_backends(compiler);
1601
1602 for (target_pair, libgccjit) in &self.dylibs {
1603 assert_eq!(
1604 target_pair.host(),
1605 compiler.host,
1606 "Trying to install libgccjit ({target_pair}) to a compiler with a different host ({})",
1607 compiler.host
1608 );
1609 let libgccjit_path = libgccjit.libgccjit();
1610
1611 let libgccjit_path = t!(
1615 libgccjit_path.canonicalize(),
1616 format!("Cannot find libgccjit at {}", libgccjit_path.display())
1617 );
1618
1619 let dst = cg_sysroot.join(libgccjit_path_relative_to_cg_dir(target_pair, libgccjit));
1620 t!(std::fs::create_dir_all(dst.parent().unwrap()));
1621 builder.copy_link(&libgccjit_path, &dst, FileType::NativeLibrary);
1622 }
1623 }
1624}
1625
1626pub fn libgccjit_path_relative_to_cg_dir(
1629 target_pair: &GccTargetPair,
1630 libgccjit: &GccOutput,
1631) -> PathBuf {
1632 let target_filename = libgccjit.libgccjit().file_name().unwrap().to_str().unwrap();
1633
1634 Path::new("lib").join(target_pair.target()).join(target_filename)
1636}
1637
1638#[derive(Clone)]
1642pub struct GccCodegenBackendOutput {
1643 stamp: BuildStamp,
1644}
1645
1646impl GccCodegenBackendOutput {
1647 pub fn stamp(&self) -> &BuildStamp {
1648 &self.stamp
1649 }
1650}
1651
1652#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1659pub struct GccCodegenBackend {
1660 compilers: RustcPrivateCompilers,
1661 target: TargetSelection,
1662}
1663
1664impl GccCodegenBackend {
1665 pub fn for_target(compilers: RustcPrivateCompilers, target: TargetSelection) -> Self {
1667 Self { compilers, target }
1668 }
1669}
1670
1671impl CommandLineStep for GccCodegenBackend {
1672 type Output = GccCodegenBackendOutput;
1673
1674 const IS_HOST: bool = true;
1675
1676 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1677 run.alias("rustc_codegen_gcc").alias("cg_gcc")
1678 }
1679
1680 fn make_run(run: RunConfig<'_>) {
1681 let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target);
1682 run.builder.ensure(GccCodegenBackend::for_target(compilers, run.target));
1683 }
1684
1685 fn run(self, builder: &Builder<'_>) -> Self::Output {
1686 let host = self.compilers.target();
1687 let build_compiler = self.compilers.build_compiler();
1688
1689 let stamp = build_stamp::codegen_backend_stamp(
1690 builder,
1691 build_compiler,
1692 host,
1693 &CodegenBackendKind::Gcc,
1694 );
1695
1696 if builder.config.keep_stage.contains(&build_compiler.stage) && stamp.path().exists() {
1697 trace!("`keep-stage` requested");
1698 builder.info(
1699 "WARNING: Using a potentially old codegen backend. \
1700 This may not behave well.",
1701 );
1702 return GccCodegenBackendOutput { stamp };
1705 }
1706
1707 let mut cargo = builder::Cargo::new(
1708 builder,
1709 build_compiler,
1710 Mode::Codegen,
1711 SourceType::InTree,
1712 host,
1713 Kind::Build,
1714 );
1715 cargo.arg("--manifest-path").arg(builder.src.join("compiler/rustc_codegen_gcc/Cargo.toml"));
1716 rustc_cargo_env(builder, &mut cargo, host);
1717
1718 let _guard =
1719 builder.msg(Kind::Build, "codegen backend gcc", Mode::Codegen, build_compiler, host);
1720 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyRlib);
1721
1722 GccCodegenBackendOutput {
1723 stamp: write_codegen_backend_stamp(stamp, files, builder.config.dry_run()),
1724 }
1725 }
1726
1727 fn metadata(&self) -> Option<StepMetadata> {
1728 Some(
1729 StepMetadata::build("rustc_codegen_gcc", self.compilers.target())
1730 .built_by(self.compilers.build_compiler()),
1731 )
1732 }
1733}
1734
1735#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1736pub struct CraneliftCodegenBackend {
1737 pub compilers: RustcPrivateCompilers,
1738}
1739
1740impl CommandLineStep for CraneliftCodegenBackend {
1741 type Output = BuildStamp;
1742 const IS_HOST: bool = true;
1743
1744 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1745 run.alias("rustc_codegen_cranelift").alias("cg_clif")
1746 }
1747
1748 fn make_run(run: RunConfig<'_>) {
1749 run.builder.ensure(CraneliftCodegenBackend {
1750 compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1751 });
1752 }
1753
1754 fn run(self, builder: &Builder<'_>) -> Self::Output {
1755 let target = self.compilers.target();
1756 let build_compiler = self.compilers.build_compiler();
1757
1758 let stamp = build_stamp::codegen_backend_stamp(
1759 builder,
1760 build_compiler,
1761 target,
1762 &CodegenBackendKind::Cranelift,
1763 );
1764
1765 if builder.config.keep_stage.contains(&build_compiler.stage) {
1766 trace!("`keep-stage` requested");
1767 builder.info(
1768 "WARNING: Using a potentially old codegen backend. \
1769 This may not behave well.",
1770 );
1771 return stamp;
1774 }
1775
1776 let mut cargo = builder::Cargo::new(
1777 builder,
1778 build_compiler,
1779 Mode::Codegen,
1780 SourceType::InTree,
1781 target,
1782 Kind::Build,
1783 );
1784 cargo
1785 .arg("--manifest-path")
1786 .arg(builder.src.join("compiler/rustc_codegen_cranelift/Cargo.toml"));
1787 rustc_cargo_env(builder, &mut cargo, target);
1788
1789 let _guard = builder.msg(
1790 Kind::Build,
1791 "codegen backend cranelift",
1792 Mode::Codegen,
1793 build_compiler,
1794 target,
1795 );
1796 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], ArtifactKeepMode::OnlyRlib);
1797 write_codegen_backend_stamp(stamp, files, builder.config.dry_run())
1798 }
1799
1800 fn metadata(&self) -> Option<StepMetadata> {
1801 Some(
1802 StepMetadata::build("rustc_codegen_cranelift", self.compilers.target())
1803 .built_by(self.compilers.build_compiler()),
1804 )
1805 }
1806}
1807
1808fn write_codegen_backend_stamp(
1810 mut stamp: BuildStamp,
1811 files: Vec<PathBuf>,
1812 dry_run: bool,
1813) -> BuildStamp {
1814 if dry_run {
1815 return stamp;
1816 }
1817
1818 let mut files = files.into_iter().filter(|f| looks_like_codegen_backend(Path::new(f)));
1819 let codegen_backend = match files.next() {
1820 Some(f) => f,
1821 None => panic!("no dylibs built for codegen backend?"),
1822 };
1823 if let Some(f) = files.next() {
1824 panic!("codegen backend built two dylibs:\n{}\n{}", codegen_backend.display(), f.display());
1825 }
1826
1827 let codegen_backend = codegen_backend.to_str().unwrap();
1828 stamp = stamp.add_stamp(codegen_backend);
1829 t!(stamp.write());
1830 stamp
1831}
1832
1833pub fn looks_like_codegen_backend(path: &Path) -> bool {
1834 is_dylib(path)
1835 && path.file_name().and_then(|p| p.to_str()).is_some_and(|n| n.contains("rustc_codegen_"))
1836}
1837
1838fn copy_codegen_backends_to_sysroot(
1845 builder: &Builder<'_>,
1846 stamp: BuildStamp,
1847 target_compiler: Compiler,
1848) {
1849 let dst = builder.sysroot_codegen_backends(target_compiler);
1858 t!(fs::create_dir_all(&dst), dst);
1859
1860 if builder.config.dry_run() {
1861 return;
1862 }
1863
1864 if stamp.path().exists() {
1865 let file = get_codegen_backend_file(&stamp);
1866 builder.copy_link(
1867 &file,
1868 &dst.join(normalize_codegen_backend_name(builder, &file)),
1869 FileType::NativeLibrary,
1870 );
1871 }
1872}
1873
1874pub fn get_codegen_backend_file(stamp: &BuildStamp) -> PathBuf {
1876 PathBuf::from(t!(fs::read_to_string(stamp.path())))
1877}
1878
1879pub fn normalize_codegen_backend_name(builder: &Builder<'_>, path: &Path) -> String {
1881 let filename = path.file_name().unwrap().to_str().unwrap();
1882 let dash = filename.find('-').unwrap();
1885 let dot = filename.find('.').unwrap();
1886 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1887}
1888
1889pub fn compiler_file(
1890 builder: &Builder<'_>,
1891 compiler: &Path,
1892 target: TargetSelection,
1893 c: CLang,
1894 file: &str,
1895) -> PathBuf {
1896 if builder.config.dry_run() {
1897 return PathBuf::new();
1898 }
1899 let mut cmd = command(compiler);
1900 cmd.args(builder.cc_handled_cflags(target, c));
1901 cmd.args(builder.cc_unhandled_cflags(target, GitRepo::Rustc, c));
1902 cmd.arg(format!("-print-file-name={file}"));
1903 let out = cmd.run_capture_stdout(builder).stdout();
1904 PathBuf::from(out.trim())
1905}
1906
1907#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1908pub struct Sysroot {
1909 pub compiler: Compiler,
1910 force_recompile: bool,
1912}
1913
1914impl Sysroot {
1915 pub(crate) fn new(compiler: Compiler) -> Self {
1916 Sysroot { compiler, force_recompile: false }
1917 }
1918}
1919
1920impl Step for Sysroot {
1921 type Output = PathBuf;
1922
1923 fn run(self, builder: &Builder<'_>) -> PathBuf {
1927 let compiler = self.compiler;
1928 let host_dir = builder.out.join(compiler.host);
1929
1930 let sysroot_dir = |stage| {
1931 if stage == 0 {
1932 host_dir.join("stage0-sysroot")
1933 } else if self.force_recompile && stage == compiler.stage {
1934 host_dir.join(format!("stage{stage}-test-sysroot"))
1935 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1936 host_dir.join("ci-rustc-sysroot")
1937 } else {
1938 host_dir.join(format!("stage{stage}"))
1939 }
1940 };
1941 let sysroot = sysroot_dir(compiler.stage);
1942 trace!(stage = ?compiler.stage, ?sysroot);
1943
1944 builder.do_if_verbose(|| {
1945 println!("Removing sysroot {} to avoid caching bugs", sysroot.display())
1946 });
1947 let _ = fs::remove_dir_all(&sysroot);
1948 t!(fs::create_dir_all(&sysroot));
1949
1950 if compiler.stage == 0 {
1957 dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1958 }
1959
1960 if builder.download_rustc() && compiler.stage != 0 {
1962 assert_eq!(
1963 builder.config.host_target, compiler.host,
1964 "Cross-compiling is not yet supported with `download-rustc`",
1965 );
1966
1967 for stage in 0..=2 {
1969 if stage != compiler.stage {
1970 let dir = sysroot_dir(stage);
1971 if !dir.ends_with("ci-rustc-sysroot") {
1972 let _ = fs::remove_dir_all(dir);
1973 }
1974 }
1975 }
1976
1977 let mut filtered_files = Vec::new();
1991 let mut add_filtered_files = |suffix, contents| {
1992 for path in contents {
1993 let path = Path::new(&path);
1994 if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
1995 filtered_files.push(path.file_name().unwrap().to_owned());
1996 }
1997 }
1998 };
1999 let suffix = format!("lib/rustlib/{}/lib", compiler.host);
2000 add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
2001 add_filtered_files("lib", builder.config.ci_rust_std_contents());
2004
2005 let filtered_extensions = [
2006 OsStr::new("rmeta"),
2007 OsStr::new("rlib"),
2008 OsStr::new(std::env::consts::DLL_EXTENSION),
2010 ];
2011 let ci_rustc_dir = builder.config.ci_rustc_dir();
2012 builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
2013 if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
2014 return true;
2015 }
2016 if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
2017 return true;
2018 }
2019 filtered_files.iter().all(|f| f != path.file_name().unwrap())
2020 });
2021 }
2022
2023 if compiler.stage != 0 {
2029 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
2030 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
2031 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
2032 if let Err(e) =
2033 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust)
2034 {
2035 eprintln!(
2036 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2037 sysroot_lib_rustlib_src_rust.display(),
2038 builder.src.display(),
2039 e,
2040 );
2041 if builder.config.rust_remap_debuginfo {
2042 eprintln!(
2043 "ERROR: some `tests/ui` tests will fail when lacking `{}`",
2044 sysroot_lib_rustlib_src_rust.display(),
2045 );
2046 }
2047 exit!(1);
2048 }
2049 }
2050
2051 if !builder.download_rustc() {
2053 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
2054 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
2055 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
2056 if let Err(e) =
2057 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
2058 {
2059 eprintln!(
2060 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2061 sysroot_lib_rustlib_rustcsrc_rust.display(),
2062 builder.src.display(),
2063 e,
2064 );
2065 exit!(1);
2066 }
2067 }
2068
2069 sysroot
2070 }
2071}
2072
2073#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2080pub struct Assemble {
2081 pub target_compiler: Compiler,
2086}
2087
2088impl CommandLineStep for Assemble {
2089 type Output = Compiler;
2090 const IS_HOST: bool = true;
2091
2092 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2093 run.path("compiler/rustc").path("compiler")
2094 }
2095
2096 fn make_run(run: RunConfig<'_>) {
2097 run.builder.ensure(Assemble {
2098 target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2099 });
2100 }
2101
2102 fn run(self, builder: &Builder<'_>) -> Compiler {
2103 let target_compiler = self.target_compiler;
2104
2105 if target_compiler.stage == 0 {
2106 trace!("stage 0 build compiler is always available, simply returning");
2107 assert_eq!(
2108 builder.config.host_target, target_compiler.host,
2109 "Cannot obtain compiler for non-native build triple at stage 0"
2110 );
2111 return target_compiler;
2113 }
2114
2115 let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2118 let libdir_bin = libdir.parent().unwrap().join("bin");
2119 t!(fs::create_dir_all(&libdir_bin));
2120
2121 if builder.config.llvm_enabled(target_compiler.host) {
2122 trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
2123
2124 let target = target_compiler.host;
2125 let llvm_output = builder.ensure(llvm::Llvm { target });
2126 if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
2127 trace!("LLVM tools enabled");
2128
2129 let host_llvm_bin_dir = command(&llvm_output.host_llvm_config)
2130 .arg("--bindir")
2131 .cached()
2132 .run_capture_stdout(builder)
2133 .stdout()
2134 .trim()
2135 .to_string();
2136
2137 let llvm_bin_dir = if target == builder.host_target {
2138 PathBuf::from(host_llvm_bin_dir)
2139 } else {
2140 let external_llvm_config = builder
2143 .config
2144 .target_config
2145 .get(&target)
2146 .and_then(|t| t.llvm_config.clone());
2147 if let Some(external_llvm_config) = external_llvm_config {
2148 external_llvm_config.parent().unwrap().to_path_buf()
2151 } else {
2152 let host_llvm_out = builder.llvm_out(builder.host_target);
2156 let target_llvm_out = llvm_output.root_dir();
2157 if let Ok(relative_path) =
2158 Path::new(&host_llvm_bin_dir).strip_prefix(host_llvm_out)
2159 {
2160 target_llvm_out.join(relative_path)
2161 } else {
2162 PathBuf::from(
2165 host_llvm_bin_dir
2166 .replace(&*builder.host_target.triple, &target.triple),
2167 )
2168 }
2169 }
2170 };
2171
2172 #[cfg(feature = "tracing")]
2179 let _llvm_tools_span =
2180 span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
2181 .entered();
2182 for tool in LLVM_TOOLS {
2183 trace!("installing `{tool}`");
2184 let tool_exe = exe(tool, target_compiler.host);
2185 let src_path = llvm_bin_dir.join(&tool_exe);
2186
2187 if !src_path.exists() && builder.config.llvm_from_ci {
2189 eprintln!("{} does not exist; skipping copy", src_path.display());
2190 continue;
2191 }
2192
2193 builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2200 }
2201 }
2202 }
2203
2204 let maybe_install_llvm_bitcode_linker = || {
2205 if builder.config.llvm_bitcode_linker_enabled {
2206 trace!("llvm-bitcode-linker enabled, installing");
2207 let llvm_bitcode_linker = builder.ensure(
2208 crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler(
2209 builder,
2210 target_compiler,
2211 ),
2212 );
2213
2214 let bindir_self_contained = builder
2216 .sysroot(target_compiler)
2217 .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host));
2218 let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2219
2220 t!(fs::create_dir_all(&bindir_self_contained));
2221 builder.copy_link(
2222 &llvm_bitcode_linker.tool_path,
2223 &bindir_self_contained.join(tool_exe),
2224 FileType::Executable,
2225 );
2226 }
2227 };
2228
2229 if builder.download_rustc() {
2231 trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2232
2233 builder.std(target_compiler, target_compiler.host);
2234 let sysroot =
2235 builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2236 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2239 if target_compiler.stage == builder.top_stage {
2241 builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage));
2242 }
2243
2244 maybe_install_llvm_bitcode_linker();
2247
2248 return target_compiler;
2249 }
2250
2251 debug!(
2265 "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2266 target_compiler.stage - 1,
2267 builder.config.host_target,
2268 );
2269 let build_compiler =
2270 builder.compiler(target_compiler.stage - 1, builder.config.host_target);
2271
2272 if builder.config.llvm_enzyme {
2274 debug!("`llvm_enzyme` requested");
2275 let enzyme = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2276 let target_libdir =
2277 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2278 let target_dst_lib = target_libdir.join(enzyme.enzyme_filename());
2279 builder.copy_link(&enzyme.enzyme_path(), &target_dst_lib, FileType::NativeLibrary);
2280 }
2281
2282 if builder.config.llvm_offload && !builder.config.dry_run() {
2283 debug!("`llvm_offload` requested");
2284 if let Some(_llvm_config) = builder.llvm_config(builder.config.host_target) {
2285 let rust_offload =
2286 builder.ensure(llvm::RustOffload { target: build_compiler.host });
2287 let target_libdir =
2288 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2289 let rust_offload_dst_lib = target_libdir.join(rust_offload.rust_offload_filename());
2290 builder.copy_link(
2291 &rust_offload.rust_offload_path(),
2292 &rust_offload_dst_lib,
2293 FileType::NativeLibrary,
2294 );
2295
2296 let omp_offload = builder.ensure(llvm::OmpOffload { target: build_compiler.host });
2297 for p in omp_offload.artifact_paths_with_symlink_targets() {
2298 let libname = p.file_name().unwrap();
2299 let dst_lib = target_libdir.join(libname);
2300 builder.resolve_symlink_and_copy(&p, &dst_lib);
2301 }
2302 }
2303 }
2304
2305 debug!(
2308 ?build_compiler,
2309 "target_compiler.host" = ?target_compiler.host,
2310 "building compiler libraries to link to"
2311 );
2312
2313 let BuiltRustc { build_compiler } =
2315 builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2316
2317 let stage = target_compiler.stage;
2318 let host = target_compiler.host;
2319 let (host_info, dir_name) = if build_compiler.host == host {
2320 ("".into(), "host".into())
2321 } else {
2322 (format!(" ({host})"), host.to_string())
2323 };
2324 let msg = format!(
2329 "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2330 );
2331 builder.info(&msg);
2332
2333 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2335 let proc_macros = builder
2336 .read_stamp_file(&stamp)
2337 .into_iter()
2338 .filter_map(|(path, dependency_type)| {
2339 if dependency_type == DependencyType::Host {
2340 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2341 } else {
2342 None
2343 }
2344 })
2345 .collect::<HashSet<_>>();
2346
2347 let sysroot = builder.sysroot(target_compiler);
2348 let rustc_libdir = builder.rustc_libdir(target_compiler);
2349 t!(fs::create_dir_all(&rustc_libdir));
2350 let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2351 for f in builder.read_dir(&src_libdir) {
2352 let filename = f.file_name().into_string().unwrap();
2353
2354 let is_proc_macro = proc_macros.contains(&filename);
2355 let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2356
2357 let can_be_rustc_dynamic_dep =
2359 if builder.link_std_into_rustc_driver(target_compiler.host) {
2360 let is_std = filename.starts_with("std-") || filename.starts_with("libstd-");
2361 !is_std
2362 } else {
2363 true
2364 };
2365
2366 if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2367 builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2368 }
2369 }
2370
2371 {
2372 #[cfg(feature = "tracing")]
2373 let _codegen_backend_span =
2374 span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2375
2376 for backend in builder.config.enabled_codegen_backends(target_compiler.host) {
2377 if builder.kind == Kind::Check && builder.top_stage == 1 {
2394 continue;
2395 }
2396
2397 let prepare_compilers = || {
2398 RustcPrivateCompilers::from_build_and_target_compiler(
2399 build_compiler,
2400 target_compiler,
2401 )
2402 };
2403
2404 match backend {
2405 CodegenBackendKind::Cranelift => {
2406 let stamp = builder
2407 .ensure(CraneliftCodegenBackend { compilers: prepare_compilers() });
2408 copy_codegen_backends_to_sysroot(builder, stamp, target_compiler);
2409 }
2410 CodegenBackendKind::Gcc => {
2411 let compilers = prepare_compilers();
2444 let cg_gcc = builder
2445 .ensure(GccCodegenBackend::for_target(compilers, target_compiler.host));
2446 copy_codegen_backends_to_sysroot(builder, cg_gcc.stamp, target_compiler);
2447
2448 let mut targets = HashSet::new();
2455 for target in &builder.hosts {
2458 targets.insert(*target);
2459 }
2460 for target in &builder.targets {
2462 targets.insert(*target);
2463 }
2464 targets.insert(compilers.target_compiler().host);
2467
2468 let dylib_set = GccDylibSet::build(
2470 builder,
2471 compilers.target_compiler().host,
2472 targets.into_iter().collect(),
2473 );
2474
2475 dylib_set.install_to(builder, target_compiler);
2478 }
2479 CodegenBackendKind::Llvm | CodegenBackendKind::Custom(_) => continue,
2480 }
2481 }
2482 }
2483
2484 if builder.config.lld_enabled {
2485 let lld_wrapper =
2486 builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler(
2487 builder,
2488 target_compiler,
2489 ));
2490 copy_lld_artifacts(builder, lld_wrapper, target_compiler);
2491 }
2492
2493 if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2494 debug!(
2495 "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2496 workaround faulty homebrew `strip`s"
2497 );
2498
2499 let src_exe = exe("llvm-objcopy", target_compiler.host);
2506 let dst_exe = exe("rust-objcopy", target_compiler.host);
2507 builder.copy_link(
2508 &libdir_bin.join(src_exe),
2509 &libdir_bin.join(dst_exe),
2510 FileType::Executable,
2511 );
2512 }
2513
2514 if builder.tool_enabled("wasm-component-ld") {
2517 let wasm_component = builder.ensure(
2518 crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler(
2519 builder,
2520 target_compiler,
2521 ),
2522 );
2523 builder.copy_link(
2524 &wasm_component.tool_path,
2525 &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2526 FileType::Executable,
2527 );
2528 }
2529
2530 maybe_install_llvm_bitcode_linker();
2531
2532 debug!(
2535 "target_compiler.host" = ?target_compiler.host,
2536 ?sysroot,
2537 "ensuring availability of `libLLVM.so` in compiler directory"
2538 );
2539 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2540 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2541
2542 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2544 let rustc = out_dir.join(exe("rustc-main", host));
2545 let bindir = sysroot.join("bin");
2546 t!(fs::create_dir_all(bindir));
2547 let compiler = builder.rustc(target_compiler);
2548 debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2549 builder.copy_link(&rustc, &compiler, FileType::Executable);
2550
2551 target_compiler
2552 }
2553}
2554
2555#[track_caller]
2560pub fn add_to_sysroot(
2561 builder: &Builder<'_>,
2562 sysroot_dst: &Path,
2563 sysroot_host_dst: &Path,
2564 stamp: &BuildStamp,
2565) {
2566 let self_contained_dst = &sysroot_dst.join("self-contained");
2567 t!(fs::create_dir_all(sysroot_dst));
2568 t!(fs::create_dir_all(sysroot_host_dst));
2569 t!(fs::create_dir_all(self_contained_dst));
2570
2571 let mut crates = HashMap::new();
2572 for (path, dependency_type) in builder.read_stamp_file(stamp) {
2573 let filename = path.file_name().unwrap().to_str().unwrap();
2574 let dst = match dependency_type {
2575 DependencyType::Host => {
2576 if sysroot_dst == sysroot_host_dst {
2577 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2580 }
2581
2582 sysroot_host_dst
2583 }
2584 DependencyType::Target => {
2585 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2588
2589 sysroot_dst
2590 }
2591 DependencyType::TargetSelfContained => self_contained_dst,
2592 };
2593 builder.copy_link(&path, &dst.join(filename), FileType::Regular);
2594 }
2595
2596 let mut seen_crates = HashMap::new();
2602 for (filestem, path) in crates {
2603 if !filestem.contains("rustc_") || filestem.contains("rustc_hash") {
2604 continue;
2605 }
2606 if let Some(other_path) =
2607 seen_crates.insert(filestem.split_once('-').unwrap().0.to_owned(), path.clone())
2608 {
2609 panic!(
2610 "duplicate rustc crate {}\n- first copy at {}\n- second copy at {}",
2611 filestem.split_once('-').unwrap().0.to_owned(),
2612 other_path.display(),
2613 path.display(),
2614 );
2615 }
2616 }
2617}
2618
2619pub enum ArtifactKeepMode {
2623 OnlyRlib,
2625 OnlyRmeta,
2627 BothRlibAndRmeta,
2631 Custom(Box<dyn Fn(&str) -> bool>),
2634}
2635
2636pub fn run_cargo(
2637 builder: &Builder<'_>,
2638 cargo: Cargo,
2639 tail_args: Vec<String>,
2640 stamp: &BuildStamp,
2641 additional_target_deps: Vec<(PathBuf, DependencyType)>,
2642 artifact_keep_mode: ArtifactKeepMode,
2643) -> Vec<PathBuf> {
2644 let target_root_dir = stamp.path().parent().unwrap();
2646 let target_build_dir = target_root_dir.join("build");
2648 let host_root_dir = target_root_dir
2650 .parent()
2651 .unwrap() .parent()
2653 .unwrap() .join(target_root_dir.file_name().unwrap());
2655
2656 let mut deps = Vec::new();
2660 let mut toplevel = Vec::new();
2661 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2662 let (filenames_vec, crate_types) = match msg {
2663 CargoMessage::CompilerArtifact {
2664 filenames,
2665 target: CargoTarget { crate_types },
2666 ..
2667 } => {
2668 let mut f: Vec<String> = filenames.into_iter().map(|s| s.into_owned()).collect();
2669 f.sort(); (f, crate_types)
2671 }
2672 _ => return,
2673 };
2674 for filename in filenames_vec {
2675 let keep = if filename.ends_with(".lib")
2677 || filename.ends_with(".a")
2678 || is_debug_info(&filename)
2679 || is_dylib(Path::new(&*filename))
2680 {
2681 true
2683 } else {
2684 match &artifact_keep_mode {
2685 ArtifactKeepMode::OnlyRlib => filename.ends_with(".rlib"),
2686 ArtifactKeepMode::OnlyRmeta => filename.ends_with(".rmeta"),
2687 ArtifactKeepMode::BothRlibAndRmeta => {
2688 filename.ends_with(".rmeta") || filename.ends_with(".rlib")
2689 }
2690 ArtifactKeepMode::Custom(func) => func(&filename),
2691 }
2692 };
2693
2694 if !keep {
2695 continue;
2696 }
2697
2698 let filename = Path::new(&*filename);
2699
2700 if filename.starts_with(&host_root_dir) {
2703 if crate_types.iter().any(|t| t == "proc-macro") {
2705 if filename.file_name().unwrap().to_str().unwrap().contains("-") {
2710 deps.push((filename.to_path_buf(), DependencyType::Host));
2711 }
2712 }
2713 continue;
2714 }
2715
2716 if filename.starts_with(&target_build_dir) {
2719 deps.push((filename.to_path_buf(), DependencyType::Target));
2720 continue;
2721 }
2722
2723 let expected_len = t!(filename.metadata()).len();
2734 let filename = filename.file_name().unwrap().to_str().unwrap();
2735 let mut parts = filename.splitn(2, '.');
2736 let file_stem = parts.next().unwrap().to_owned();
2737 let extension = parts.next().unwrap().to_owned();
2738
2739 toplevel.push((file_stem, extension, expected_len));
2740 }
2741 });
2742
2743 if !ok {
2744 crate::exit!(1);
2745 }
2746
2747 if builder.config.dry_run() {
2748 return Vec::new();
2749 }
2750
2751 let read_dir = |path: &Path| path.read_dir().ok().into_iter().flatten().filter_map(Result::ok);
2758 let contents = target_build_dir
2759 .read_dir()
2760 .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_build_dir.display(), e))
2761 .map(|e| e.unwrap())
2762 .flat_map(|e| read_dir(&e.path()))
2763 .flat_map(|e| read_dir(&e.path()))
2764 .flat_map(|e| read_dir(&e.path()))
2765 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2766 .collect::<Vec<_>>();
2767 for (prefix, extension, expected_len) in toplevel {
2768 let candidates = contents.iter().filter(|&(_, filename, meta)| {
2769 meta.len() == expected_len
2770 && filename
2771 .strip_prefix(&prefix[..])
2772 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2773 .unwrap_or(false)
2774 });
2775 let max = candidates.max_by_key(|&(_, _, metadata)| {
2776 metadata.modified().expect("mtime should be available on all relevant OSes")
2777 });
2778 let path_to_add = match max {
2779 Some(triple) => triple.0.to_str().unwrap(),
2780 None => panic!("no output generated for {prefix:?} {extension:?}"),
2781 };
2782 if is_dylib(Path::new(path_to_add)) {
2783 let candidate = format!("{path_to_add}.lib");
2784 let candidate = PathBuf::from(candidate);
2785 if candidate.exists() {
2786 deps.push((candidate, DependencyType::Target));
2787 }
2788 }
2789 deps.push((path_to_add.into(), DependencyType::Target));
2790 }
2791
2792 deps.extend(additional_target_deps);
2793 deps.sort();
2794 let mut new_contents = Vec::new();
2795 for (dep, dependency_type) in deps.iter() {
2796 new_contents.extend(match *dependency_type {
2797 DependencyType::Host => b"h",
2798 DependencyType::Target => b"t",
2799 DependencyType::TargetSelfContained => b"s",
2800 });
2801 new_contents.extend(dep.to_str().unwrap().as_bytes());
2802 new_contents.extend(b"\0");
2803 }
2804 t!(fs::write(stamp.path(), &new_contents));
2805 deps.into_iter().map(|(d, _)| d).collect()
2806}
2807
2808pub fn stream_cargo(
2809 builder: &Builder<'_>,
2810 cargo: Cargo,
2811 tail_args: Vec<String>,
2812 cb: &mut dyn FnMut(CargoMessage<'_>),
2813) -> bool {
2814 let mut cmd = cargo.into_cmd();
2815
2816 let mut message_format = if builder.config.json_output {
2819 String::from("json")
2820 } else {
2821 String::from("json-render-diagnostics")
2822 };
2823 if let Some(s) = &builder.config.rustc_error_format {
2824 message_format.push_str(",json-diagnostic-");
2825 message_format.push_str(s);
2826 }
2827 cmd.arg("--message-format").arg(message_format);
2828
2829 for arg in tail_args {
2830 cmd.arg(arg);
2831 }
2832
2833 builder.do_if_verbose(|| println!("running: {cmd:?}"));
2834
2835 let streaming_command = cmd.stream_capture_stdout(&builder.config.exec_ctx);
2836
2837 let Some(mut streaming_command) = streaming_command else {
2838 return true;
2839 };
2840
2841 let stdout = BufReader::new(streaming_command.stdout.take().unwrap());
2845 for line in stdout.lines() {
2846 let line = t!(line);
2847 match serde_json::from_str::<CargoMessage<'_>>(&line) {
2848 Ok(msg) => {
2849 if builder.config.json_output {
2850 println!("{line}");
2852 }
2853 cb(msg)
2854 }
2855 Err(_) => println!("{line}"),
2857 }
2858 }
2859
2860 let status = t!(streaming_command.wait(&builder.config.exec_ctx));
2862 if builder.is_verbose() && !status.success() {
2863 eprintln!(
2864 "command did not execute successfully: {cmd:?}\n\
2865 expected success, got: {status}"
2866 );
2867 }
2868
2869 status.success()
2870}
2871
2872#[derive(Deserialize)]
2873pub struct CargoTarget<'a> {
2874 crate_types: Vec<Cow<'a, str>>,
2875}
2876
2877#[derive(Deserialize)]
2878#[serde(tag = "reason", rename_all = "kebab-case")]
2879pub enum CargoMessage<'a> {
2880 CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2881 BuildScriptExecuted,
2882 BuildFinished,
2883}
2884
2885pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2886 if target != "x86_64-unknown-linux-gnu"
2890 || !builder.config.is_host_target(target)
2891 || !path.exists()
2892 {
2893 return;
2894 }
2895
2896 let previous_mtime = t!(t!(path.metadata()).modified());
2897 let stamp = BuildStamp::new(path.parent().unwrap())
2898 .with_prefix(path.file_name().unwrap().to_str().unwrap())
2899 .with_prefix("strip")
2900 .add_stamp(previous_mtime.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos());
2901
2902 if !stamp.is_up_to_date() {
2905 command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2906 }
2907 t!(stamp.write());
2908
2909 let file = t!(fs::File::open(path));
2910
2911 t!(file.set_modified(previous_mtime));
2924}
2925
2926pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2928 build_compiler.stage != 0
2929}