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, add_cg_gcc_cargo_flags};
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 self.is_for_mir_opt_tests, false,
301 );
302
303 builder.ensure(StdLink::from_std(
304 self,
305 builder.compiler(build_compiler.stage, builder.config.host_target),
306 ));
307 Some(stamp)
308 }
309
310 fn metadata(&self) -> Option<StepMetadata> {
311 Some(StepMetadata::build("std", self.target).built_by(self.build_compiler))
312 }
313}
314
315fn copy_and_stamp(
316 builder: &Builder<'_>,
317 libdir: &Path,
318 sourcedir: &Path,
319 name: &str,
320 target_deps: &mut Vec<(PathBuf, DependencyType)>,
321 dependency_type: DependencyType,
322) {
323 let target = libdir.join(name);
324 builder.copy_link(&sourcedir.join(name), &target, FileType::Regular);
325
326 target_deps.push((target, dependency_type));
327}
328
329fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
330 let libunwind_path = builder.ensure(llvm::Libunwind { target });
331 let libunwind_source = libunwind_path.join("libunwind.a");
332 let libunwind_target = libdir.join("libunwind.a");
333 builder.copy_link(&libunwind_source, &libunwind_target, FileType::NativeLibrary);
334 libunwind_target
335}
336
337fn copy_third_party_objects(
339 builder: &Builder<'_>,
340 compiler: &Compiler,
341 target: TargetSelection,
342) -> Vec<(PathBuf, DependencyType)> {
343 let mut target_deps = vec![];
344
345 if builder.config.needs_sanitizer_runtime_built(target) && compiler.stage != 0 {
346 target_deps.extend(
349 copy_sanitizers(builder, compiler, target)
350 .into_iter()
351 .map(|d| (d, DependencyType::Target)),
352 );
353 }
354
355 if target == "x86_64-fortanix-unknown-sgx"
356 || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
357 && (target.contains("linux") || target.contains("fuchsia") || target.contains("aix"))
358 {
359 let libunwind_path =
360 copy_llvm_libunwind(builder, target, &builder.sysroot_target_libdir(*compiler, target));
361 target_deps.push((libunwind_path, DependencyType::Target));
362 }
363
364 target_deps
365}
366
367fn copy_self_contained_objects(
369 builder: &Builder<'_>,
370 compiler: &Compiler,
371 target: TargetSelection,
372) -> Vec<(PathBuf, DependencyType)> {
373 let libdir_self_contained =
374 builder.sysroot_target_libdir(*compiler, target).join("self-contained");
375 t!(fs::create_dir_all(&libdir_self_contained));
376 let mut target_deps = vec![];
377
378 if target.needs_crt_begin_end() {
386 let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
387 panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
388 });
389 if !target.starts_with("wasm32") {
390 for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
391 copy_and_stamp(
392 builder,
393 &libdir_self_contained,
394 &srcdir,
395 obj,
396 &mut target_deps,
397 DependencyType::TargetSelfContained,
398 );
399 }
400 let crt_path = builder.ensure(llvm::CrtBeginEnd { target });
401 for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
402 let src = crt_path.join(obj);
403 let target = libdir_self_contained.join(obj);
404 builder.copy_link(&src, &target, FileType::NativeLibrary);
405 target_deps.push((target, DependencyType::TargetSelfContained));
406 }
407 } else {
408 for &obj in &["libc.a", "crt1-command.o"] {
411 copy_and_stamp(
412 builder,
413 &libdir_self_contained,
414 &srcdir,
415 obj,
416 &mut target_deps,
417 DependencyType::TargetSelfContained,
418 );
419 }
420 }
421 if !target.starts_with("s390x") {
422 let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
423 target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
424 }
425 } else if target.contains("-wasi") {
426 let srcdir = builder.wasi_libdir(target).unwrap_or_else(|| {
427 panic!(
428 "Target {:?} does not have a \"wasi-root\" key in bootstrap.toml \
429 or `$WASI_SDK_PATH` set",
430 target.triple
431 )
432 });
433
434 let srcdir = if target == "wasm32-wasip3" {
438 assert!(!srcdir.exists(), "wasip3 support is in wasi-libc, this should be updated now");
439 builder.wasi_libdir(TargetSelection::from_user("wasm32-wasip2")).unwrap()
440 } else {
441 srcdir
442 };
443 for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
444 copy_and_stamp(
445 builder,
446 &libdir_self_contained,
447 &srcdir,
448 obj,
449 &mut target_deps,
450 DependencyType::TargetSelfContained,
451 );
452 }
453 } else if target.is_windows_gnu() || target.is_windows_gnullvm() {
454 for obj in ["crt2.o", "dllcrt2.o"].iter() {
455 let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
456 let dst = libdir_self_contained.join(obj);
457 builder.copy_link(&src, &dst, FileType::NativeLibrary);
458 target_deps.push((dst, DependencyType::TargetSelfContained));
459 }
460 }
461
462 target_deps
463}
464
465pub fn std_crates_for_run_make(run: &RunConfig<'_>) -> Vec<String> {
468 let mut crates = run.make_run_crates(builder::Alias::Library);
469
470 let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
479 if target_is_no_std {
480 crates.retain(|c| c == "core" || c == "alloc");
481 }
482 crates
483}
484
485fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
491 if builder.config.llvm_from_ci {
493 builder.config.maybe_download_ci_llvm();
495 let ci_llvm_compiler_rt = builder.config.ci_llvm_root().join("compiler-rt");
496 if ci_llvm_compiler_rt.exists() {
497 return ci_llvm_compiler_rt;
498 }
499 }
500
501 builder.require_submodule("src/llvm-project", {
503 Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
504 });
505 builder.src.join("src/llvm-project/compiler-rt")
506}
507
508pub fn std_cargo(
511 builder: &Builder<'_>,
512 target: TargetSelection,
513 cargo: &mut Cargo,
514 crates: &[String],
515) {
516 if target.contains("apple") && !builder.config.dry_run() {
534 let mut cmd = builder.rustc_cmd(cargo.compiler());
538 cmd.arg("--target").arg(target.rustc_target_arg());
539 cmd.arg("--print=deployment-target");
540 let output = cmd.run_capture_stdout(builder).stdout();
541
542 let (env_var, value) = output.split_once('=').unwrap();
543 cargo.env(env_var.trim(), value.trim());
546
547 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
557 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
558 }
559 }
560
561 if let Some(path) = builder.config.profiler_path(target) {
563 cargo.env("LLVM_PROFILER_RT_LIB", path);
564 } else if builder.config.profiler_enabled(target) {
565 let compiler_rt = compiler_rt_for_profiler(builder);
566 cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
570 }
571
572 let compiler_builtins_c_feature = match builder.config.optimized_compiler_builtins(target) {
586 CompilerBuiltins::LinkLLVMBuiltinsLib(path) => {
587 cargo.env("LLVM_COMPILER_RT_LIB", path);
588 " compiler-builtins-c"
589 }
590 CompilerBuiltins::BuildLLVMFuncs => {
591 builder.require_submodule(
601 "src/llvm-project",
602 Some(
603 "The `build.optimized-compiler-builtins` config option \
604 requires `compiler-rt` sources from LLVM.",
605 ),
606 );
607 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
608 if !builder.config.dry_run() {
609 assert!(compiler_builtins_root.exists());
612 }
613
614 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
617 " compiler-builtins-c"
618 }
619 CompilerBuiltins::BuildRustOnly => "",
620 };
621
622 if !builder.unstable_features() {
625 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
626 }
627
628 for krate in crates {
629 cargo.args(["-p", krate]);
630 }
631
632 let mut features = String::new();
633
634 if builder.no_std(target) == Some(true) {
635 features += " compiler-builtins-mem";
636 if !target.starts_with("bpf") {
637 features.push_str(compiler_builtins_c_feature);
638 }
639
640 if crates.is_empty() {
642 cargo.args(["-p", "alloc"]);
643 }
644 cargo
645 .arg("--manifest-path")
646 .arg(builder.src.join("library/alloc/Cargo.toml"))
647 .arg("--features")
648 .arg(features);
649 } else {
650 features += &builder.std_features(target);
651 features.push_str(compiler_builtins_c_feature);
652
653 cargo
654 .arg("--features")
655 .arg(features)
656 .arg("--manifest-path")
657 .arg(builder.src.join("library/sysroot/Cargo.toml"));
658
659 if target.contains("musl")
662 && let Some(p) = builder.musl_libdir(target)
663 {
664 let root = format!("native={}", p.to_str().unwrap());
665 cargo.rustflag("-L").rustflag(&root);
666 }
667
668 if target.contains("-wasi")
669 && let Some(dir) = builder.wasi_libdir(target)
670 {
671 let root = format!("native={}", dir.to_str().unwrap());
672 cargo.rustflag("-L").rustflag(&root);
673 }
674 }
675
676 cargo.rustflag("-Cembed-bitcode=yes");
682
683 if builder.config.rust_lto == RustcLto::Off {
684 cargo.rustflag("-Clto=off");
685 }
686
687 if target.contains("riscv") {
694 cargo.rustflag("-Cforce-unwind-tables=yes");
695 }
696
697 cargo.rustflag("-Zunstable-options");
700 cargo.rustflag("-Cforce-frame-pointers=non-leaf");
701
702 let html_root =
703 format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
704 cargo.rustflag(&html_root);
705 cargo.rustdocflag(&html_root);
706
707 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
708}
709
710#[derive(Debug, Clone, PartialEq, Eq, Hash)]
719pub struct StdLink {
720 pub compiler: Compiler,
721 pub target_compiler: Compiler,
722 pub target: TargetSelection,
723 crates: Vec<String>,
725 force_recompile: bool,
727}
728
729impl StdLink {
730 pub fn from_std(std: Std, host_compiler: Compiler) -> Self {
731 Self {
732 compiler: host_compiler,
733 target_compiler: std.build_compiler,
734 target: std.target,
735 crates: std.crates,
736 force_recompile: std.force_recompile,
737 }
738 }
739}
740
741impl Step for StdLink {
742 type Output = ();
743
744 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
745 run.never()
746 }
747
748 fn run(self, builder: &Builder<'_>) {
757 let compiler = self.compiler;
758 let target_compiler = self.target_compiler;
759 let target = self.target;
760
761 let (libdir, hostdir) = if !self.force_recompile && builder.download_rustc() {
763 let lib = builder.sysroot_libdir_relative(self.compiler);
765 let sysroot = builder.ensure(crate::core::build_steps::compile::Sysroot {
766 compiler: self.compiler,
767 force_recompile: self.force_recompile,
768 });
769 let libdir = sysroot.join(lib).join("rustlib").join(target).join("lib");
770 let hostdir = sysroot.join(lib).join("rustlib").join(compiler.host).join("lib");
771 (libdir, hostdir)
772 } else {
773 let libdir = builder.sysroot_target_libdir(target_compiler, target);
774 let hostdir = builder.sysroot_target_libdir(target_compiler, compiler.host);
775 (libdir, hostdir)
776 };
777
778 let is_downloaded_beta_stage0 = builder
779 .build
780 .config
781 .initial_rustc
782 .starts_with(builder.out.join(compiler.host).join("stage0/bin"));
783
784 if compiler.stage == 0 && is_downloaded_beta_stage0 {
788 let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
790
791 let host = compiler.host;
792 let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
793 let sysroot_bin_dir = sysroot.join("bin");
794 t!(fs::create_dir_all(&sysroot_bin_dir));
795 builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
796
797 let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
798 t!(fs::create_dir_all(sysroot.join("lib")));
799 builder.cp_link_r(&stage0_lib_dir, &sysroot.join("lib"));
800
801 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
803 t!(fs::create_dir_all(&sysroot_codegen_backends));
804 let stage0_codegen_backends = builder
805 .out
806 .join(host)
807 .join("stage0/lib/rustlib")
808 .join(host)
809 .join("codegen-backends");
810 if stage0_codegen_backends.exists() {
811 builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
812 }
813 } else if compiler.stage == 0 {
814 let sysroot = builder.out.join(compiler.host.triple).join("stage0-sysroot");
815
816 if builder.local_rebuild {
817 let _ = fs::remove_dir_all(sysroot.join("lib/rustlib/src/rust"));
821 }
822
823 builder.cp_link_r(&builder.initial_sysroot.join("lib"), &sysroot.join("lib"));
824 } else {
825 if builder.download_rustc() {
826 let _ = fs::remove_dir_all(&libdir);
828 let _ = fs::remove_dir_all(&hostdir);
829 }
830
831 add_to_sysroot(
832 builder,
833 &libdir,
834 &hostdir,
835 &build_stamp::libstd_stamp(builder, compiler, target),
836 );
837 }
838 }
839}
840
841fn copy_sanitizers(
843 builder: &Builder<'_>,
844 compiler: &Compiler,
845 target: TargetSelection,
846) -> Vec<PathBuf> {
847 let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
848
849 if builder.config.dry_run() {
850 return Vec::new();
851 }
852
853 let mut target_deps = Vec::new();
854 let libdir = builder.sysroot_target_libdir(*compiler, target);
855
856 for runtime in &runtimes {
857 let dst = libdir.join(&runtime.name);
858 builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
859
860 if target == "x86_64-apple-darwin"
864 || target == "aarch64-apple-darwin"
865 || target == "aarch64-apple-ios"
866 || target == "aarch64-apple-ios-sim"
867 || target == "x86_64-apple-ios"
868 {
869 apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
871 apple_darwin_sign_file(builder, &dst);
874 }
875
876 target_deps.push(dst);
877 }
878
879 target_deps
880}
881
882fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
883 command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
884}
885
886fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
887 command("codesign")
888 .arg("-f") .arg("-s")
890 .arg("-")
891 .arg(file_path)
892 .run(builder);
893}
894
895#[derive(Debug, Clone, PartialEq, Eq, Hash)]
896pub struct StartupObjects {
897 pub compiler: Compiler,
898 pub target: TargetSelection,
899}
900
901impl Step for StartupObjects {
902 type Output = Vec<(PathBuf, DependencyType)>;
903
904 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
905 run.path("library/rtstartup")
906 }
907
908 fn make_run(run: RunConfig<'_>) {
909 run.builder.ensure(StartupObjects {
910 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
911 target: run.target,
912 });
913 }
914
915 fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
922 let for_compiler = self.compiler;
923 let target = self.target;
924 if !target.is_windows_gnu() {
927 return vec![];
928 }
929
930 let mut target_deps = vec![];
931
932 let src_dir = &builder.src.join("library").join("rtstartup");
933 let dst_dir = &builder.native_dir(target).join("rtstartup");
934 let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
935 t!(fs::create_dir_all(dst_dir));
936
937 for file in &["rsbegin", "rsend"] {
938 let src_file = &src_dir.join(file.to_string() + ".rs");
939 let dst_file = &dst_dir.join(file.to_string() + ".o");
940 if !up_to_date(src_file, dst_file) {
941 let mut cmd = command(&builder.initial_rustc);
942 cmd.env("RUSTC_BOOTSTRAP", "1");
943 if !builder.local_rebuild {
944 cmd.arg("--cfg").arg("bootstrap");
946 }
947 cmd.arg("--target")
948 .arg(target.rustc_target_arg())
949 .arg("--emit=obj")
950 .arg("-o")
951 .arg(dst_file)
952 .arg(src_file)
953 .run(builder);
954 }
955
956 let obj = sysroot_dir.join((*file).to_string() + ".o");
957 builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
958 target_deps.push((obj, DependencyType::Target));
959 }
960
961 target_deps
962 }
963}
964
965fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
966 let ci_rustc_dir = builder.config.ci_rustc_dir();
967
968 for file in contents {
969 let src = ci_rustc_dir.join(&file);
970 let dst = sysroot.join(file);
971 if src.is_dir() {
972 t!(fs::create_dir_all(dst));
973 } else {
974 builder.copy_link(&src, &dst, FileType::Regular);
975 }
976 }
977}
978
979#[derive(Clone, Debug)]
981pub struct BuiltRustc {
982 pub build_compiler: Compiler,
986}
987
988#[derive(Debug, Clone, PartialEq, Eq, Hash)]
995pub struct Rustc {
996 pub target: TargetSelection,
998 pub build_compiler: Compiler,
1000 crates: Vec<String>,
1006}
1007
1008impl Rustc {
1009 pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
1010 Self { target, build_compiler, crates: Default::default() }
1011 }
1012}
1013
1014impl Step for Rustc {
1015 type Output = BuiltRustc;
1016 const IS_HOST: bool = true;
1017
1018 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1019 let mut crates = run.builder.in_tree_crates("rustc-main", None);
1020 for (i, krate) in crates.iter().enumerate() {
1021 if krate.name == "rustc-main" {
1024 crates.swap_remove(i);
1025 break;
1026 }
1027 }
1028 run.crates(crates)
1029 }
1030
1031 fn is_default_step(_builder: &Builder<'_>) -> bool {
1032 false
1033 }
1034
1035 fn make_run(run: RunConfig<'_>) {
1036 if run.builder.paths == vec![PathBuf::from("compiler")] {
1039 return;
1040 }
1041
1042 let crates = run.cargo_crates_in_set();
1043 run.builder.ensure(Rustc {
1044 build_compiler: run
1045 .builder
1046 .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1047 target: run.target,
1048 crates,
1049 });
1050 }
1051
1052 fn run(self, builder: &Builder<'_>) -> Self::Output {
1058 let build_compiler = self.build_compiler;
1059 let target = self.target;
1060
1061 if builder.download_rustc() && build_compiler.stage != 0 {
1064 trace!(stage = build_compiler.stage, "`download_rustc` requested");
1065
1066 let sysroot =
1067 builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
1068 cp_rustc_component_to_ci_sysroot(
1069 builder,
1070 &sysroot,
1071 builder.config.ci_rustc_dev_contents(),
1072 );
1073 return BuiltRustc { build_compiler };
1074 }
1075
1076 builder.std(build_compiler, target);
1079
1080 if builder.config.keep_stage.contains(&build_compiler.stage) {
1081 trace!(stage = build_compiler.stage, "`keep-stage` requested");
1082
1083 builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1084 builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1085 builder.ensure(RustcLink::from_rustc(self));
1086
1087 return BuiltRustc { build_compiler };
1088 }
1089
1090 let stage = build_compiler.stage + 1;
1092
1093 if build_compiler.stage >= 2
1098 && !builder.config.full_bootstrap
1099 && target == builder.host_target
1100 {
1101 let uplift_build_compiler = builder.compiler(1, build_compiler.host);
1105
1106 let msg = format!("Uplifting rustc from stage2 to stage{stage})");
1107 builder.info(&msg);
1108
1109 builder.ensure(RustcLink::from_build_compiler_and_sysroot(
1113 uplift_build_compiler,
1115 build_compiler,
1117 target,
1118 self.crates,
1119 ));
1120
1121 return BuiltRustc { build_compiler: uplift_build_compiler };
1124 }
1125
1126 builder.std(
1132 builder.compiler(self.build_compiler.stage, builder.config.host_target),
1133 builder.config.host_target,
1134 );
1135
1136 let mut cargo = builder::Cargo::new(
1137 builder,
1138 build_compiler,
1139 Mode::Rustc,
1140 SourceType::InTree,
1141 target,
1142 Kind::Build,
1143 );
1144
1145 rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
1146
1147 for krate in &*self.crates {
1151 cargo.arg("-p").arg(krate);
1152 }
1153
1154 if builder.build.config.enable_bolt_settings && build_compiler.stage == 1 {
1155 cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1157 }
1158
1159 let _guard = builder.msg(
1160 Kind::Build,
1161 format_args!("compiler artifacts{}", crate_description(&self.crates)),
1162 Mode::Rustc,
1163 build_compiler,
1164 target,
1165 );
1166 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
1167 run_cargo(
1168 builder,
1169 cargo,
1170 vec![],
1171 &stamp,
1172 vec![],
1173 false,
1174 true, );
1176
1177 let target_root_dir = stamp.path().parent().unwrap();
1178 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1184 && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1185 {
1186 let rustc_driver = target_root_dir.join("librustc_driver.so");
1187 strip_debug(builder, target, &rustc_driver);
1188 }
1189
1190 if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1191 strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1194 }
1195
1196 builder.ensure(RustcLink::from_rustc(self));
1197 BuiltRustc { build_compiler }
1198 }
1199
1200 fn metadata(&self) -> Option<StepMetadata> {
1201 Some(StepMetadata::build("rustc", self.target).built_by(self.build_compiler))
1202 }
1203}
1204
1205pub fn rustc_cargo(
1206 builder: &Builder<'_>,
1207 cargo: &mut Cargo,
1208 target: TargetSelection,
1209 build_compiler: &Compiler,
1210 crates: &[String],
1211) {
1212 cargo
1213 .arg("--features")
1214 .arg(builder.rustc_features(builder.kind, target, crates))
1215 .arg("--manifest-path")
1216 .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1217
1218 cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1219
1220 cargo.rustflag("-Zon-broken-pipe=kill");
1234
1235 if builder.build.config.bootstrap_override_lld.is_used() {
1240 cargo.rustflag("-Zdefault-visibility=protected");
1241 }
1242
1243 if is_lto_stage(build_compiler) {
1244 match builder.config.rust_lto {
1245 RustcLto::Thin | RustcLto::Fat => {
1246 cargo.rustflag("-Zdylib-lto");
1249 let lto_type = match builder.config.rust_lto {
1253 RustcLto::Thin => "thin",
1254 RustcLto::Fat => "fat",
1255 _ => unreachable!(),
1256 };
1257 cargo.rustflag(&format!("-Clto={lto_type}"));
1258 cargo.rustflag("-Cembed-bitcode=yes");
1259 }
1260 RustcLto::ThinLocal => { }
1261 RustcLto::Off => {
1262 cargo.rustflag("-Clto=off");
1263 }
1264 }
1265 } else if builder.config.rust_lto == RustcLto::Off {
1266 cargo.rustflag("-Clto=off");
1267 }
1268
1269 if builder.config.bootstrap_override_lld.is_used() && !build_compiler.host.is_msvc() {
1277 cargo.rustflag("-Clink-args=-Wl,--icf=all");
1278 }
1279
1280 if builder.config.rust_profile_use.is_some() && builder.config.rust_profile_generate.is_some() {
1281 panic!("Cannot use and generate PGO profiles at the same time");
1282 }
1283 let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
1284 if build_compiler.stage == 1 {
1285 cargo.rustflag(&format!("-Cprofile-generate={path}"));
1286 cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
1289 true
1290 } else {
1291 false
1292 }
1293 } else if let Some(path) = &builder.config.rust_profile_use {
1294 if build_compiler.stage == 1 {
1295 cargo.rustflag(&format!("-Cprofile-use={path}"));
1296 if builder.is_verbose() {
1297 cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
1298 }
1299 true
1300 } else {
1301 false
1302 }
1303 } else {
1304 false
1305 };
1306 if is_collecting {
1307 cargo.rustflag(&format!(
1309 "-Cllvm-args=-static-func-strip-dirname-prefix={}",
1310 builder.config.src.components().count()
1311 ));
1312 }
1313
1314 if let Some(ref ccache) = builder.config.ccache
1319 && build_compiler.stage == 0
1320 && !builder.config.incremental
1321 {
1322 cargo.env("RUSTC_WRAPPER", ccache);
1323 }
1324
1325 rustc_cargo_env(builder, cargo, target);
1326}
1327
1328pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1329 cargo
1332 .env("CFG_RELEASE", builder.rust_release())
1333 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1334 .env("CFG_VERSION", builder.rust_version());
1335
1336 if builder.config.omit_git_hash {
1340 cargo.env("CFG_OMIT_GIT_HASH", "1");
1341 }
1342
1343 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", builder.config.default_codegen_backend(target).name());
1344
1345 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1346 let target_config = builder.config.target_config.get(&target);
1347
1348 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1349
1350 if let Some(ref ver_date) = builder.rust_info().commit_date() {
1351 cargo.env("CFG_VER_DATE", ver_date);
1352 }
1353 if let Some(ref ver_hash) = builder.rust_info().sha() {
1354 cargo.env("CFG_VER_HASH", ver_hash);
1355 }
1356 if !builder.unstable_features() {
1357 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1358 }
1359
1360 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1363 cargo.env("CFG_DEFAULT_LINKER", s);
1364 } else if let Some(ref s) = builder.config.rustc_default_linker {
1365 cargo.env("CFG_DEFAULT_LINKER", s);
1366 }
1367
1368 if let Some(linker) = target_config.map(|c| c.default_linker_linux_override) {
1370 match linker {
1371 DefaultLinuxLinkerOverride::Off => {}
1372 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1373 cargo.env("CFG_DEFAULT_LINKER_SELF_CONTAINED_LLD_CC", "1");
1374 }
1375 }
1376 }
1377
1378 if builder.config.rust_verify_llvm_ir {
1379 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1380 }
1381
1382 if builder.config.llvm_enabled(target) {
1394 let building_llvm_is_expensive =
1395 crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false)
1396 .should_build();
1397
1398 let skip_llvm = (builder.kind == Kind::Check) && building_llvm_is_expensive;
1399 if !skip_llvm {
1400 rustc_llvm_env(builder, cargo, target)
1401 }
1402 }
1403
1404 if builder.config.jemalloc(target) && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none() {
1406 if target.starts_with("aarch64") {
1409 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1410 }
1411 else if target.starts_with("loongarch") {
1413 cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "14");
1414 }
1415 }
1416}
1417
1418fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1424 if builder.config.is_rust_llvm(target) {
1425 cargo.env("LLVM_RUSTLLVM", "1");
1426 }
1427 if builder.config.llvm_enzyme {
1428 cargo.env("LLVM_ENZYME", "1");
1429 }
1430 if builder.config.llvm_offload {
1431 cargo.env("LLVM_OFFLOAD", "1");
1432 }
1433 let llvm::LlvmResult { host_llvm_config, .. } = builder.ensure(llvm::Llvm { target });
1434 cargo.env("LLVM_CONFIG", &host_llvm_config);
1435
1436 let mut llvm_linker_flags = String::new();
1446 if builder.config.llvm_profile_generate
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}
1497
1498#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1511struct RustcLink {
1512 build_compiler: Compiler,
1514 sysroot_compiler: Compiler,
1517 target: TargetSelection,
1518 crates: Vec<String>,
1520}
1521
1522impl RustcLink {
1523 fn from_rustc(rustc: Rustc) -> Self {
1526 Self {
1527 build_compiler: rustc.build_compiler,
1528 sysroot_compiler: rustc.build_compiler,
1529 target: rustc.target,
1530 crates: rustc.crates,
1531 }
1532 }
1533
1534 fn from_build_compiler_and_sysroot(
1536 build_compiler: Compiler,
1537 sysroot_compiler: Compiler,
1538 target: TargetSelection,
1539 crates: Vec<String>,
1540 ) -> Self {
1541 Self { build_compiler, sysroot_compiler, target, crates }
1542 }
1543}
1544
1545impl Step for RustcLink {
1546 type Output = ();
1547
1548 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1549 run.never()
1550 }
1551
1552 fn run(self, builder: &Builder<'_>) {
1554 let build_compiler = self.build_compiler;
1555 let sysroot_compiler = self.sysroot_compiler;
1556 let target = self.target;
1557 add_to_sysroot(
1558 builder,
1559 &builder.sysroot_target_libdir(sysroot_compiler, target),
1560 &builder.sysroot_target_libdir(sysroot_compiler, sysroot_compiler.host),
1561 &build_stamp::librustc_stamp(builder, build_compiler, target),
1562 );
1563 }
1564}
1565
1566#[derive(Clone)]
1568pub struct GccDylibSet {
1569 dylibs: BTreeMap<GccTargetPair, GccOutput>,
1570 host_pair: GccTargetPair,
1571}
1572
1573impl GccDylibSet {
1574 fn host_dylib(&self) -> &GccOutput {
1579 self.dylibs.get(&self.host_pair).unwrap_or_else(|| {
1580 panic!("libgccjit.so was not built for host target {}", self.host_pair)
1581 })
1582 }
1583
1584 pub fn install_to(&self, builder: &Builder<'_>, compiler: Compiler) {
1588 if builder.config.dry_run() {
1589 return;
1590 }
1591
1592 let cg_sysroot = builder.sysroot_codegen_backends(compiler);
1594
1595 for (target_pair, libgccjit) in &self.dylibs {
1596 assert_eq!(
1597 target_pair.host(),
1598 compiler.host,
1599 "Trying to install libgccjit ({target_pair}) to a compiler with a different host ({})",
1600 compiler.host
1601 );
1602 let libgccjit = libgccjit.libgccjit();
1603 let target_filename = libgccjit.file_name().unwrap().to_str().unwrap();
1604
1605 let actual_libgccjit_path = t!(
1609 libgccjit.canonicalize(),
1610 format!("Cannot find libgccjit at {}", libgccjit.display())
1611 );
1612
1613 let dest_dir = cg_sysroot.join("lib").join(target_pair.target());
1615 t!(fs::create_dir_all(&dest_dir));
1616 let dst = dest_dir.join(target_filename);
1617 builder.copy_link(&actual_libgccjit_path, &dst, FileType::NativeLibrary);
1618 }
1619 }
1620}
1621
1622#[derive(Clone)]
1626pub struct GccCodegenBackendOutput {
1627 stamp: BuildStamp,
1628 dylib_set: GccDylibSet,
1629}
1630
1631#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1642pub struct GccCodegenBackend {
1643 compilers: RustcPrivateCompilers,
1644 targets: Vec<TargetSelection>,
1645}
1646
1647impl GccCodegenBackend {
1648 pub fn for_targets(
1651 compilers: RustcPrivateCompilers,
1652 mut targets: Vec<TargetSelection>,
1653 ) -> Self {
1654 targets.sort();
1656 Self { compilers, targets }
1657 }
1658}
1659
1660impl Step for GccCodegenBackend {
1661 type Output = GccCodegenBackendOutput;
1662
1663 const IS_HOST: bool = true;
1664
1665 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1666 run.alias("rustc_codegen_gcc").alias("cg_gcc")
1667 }
1668
1669 fn make_run(run: RunConfig<'_>) {
1670 let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target);
1673 run.builder.ensure(GccCodegenBackend { compilers, targets: vec![run.target] });
1674 }
1675
1676 fn run(self, builder: &Builder<'_>) -> Self::Output {
1677 let host = self.compilers.target();
1678 let build_compiler = self.compilers.build_compiler();
1679
1680 let stamp = build_stamp::codegen_backend_stamp(
1681 builder,
1682 build_compiler,
1683 host,
1684 &CodegenBackendKind::Gcc,
1685 );
1686
1687 let dylib_set = GccDylibSet {
1688 dylibs: self
1689 .targets
1690 .iter()
1691 .map(|&target| {
1692 let target_pair = GccTargetPair::for_target_pair(host, target);
1693 (target_pair, builder.ensure(Gcc { target_pair }))
1694 })
1695 .collect(),
1696 host_pair: GccTargetPair::for_native_build(host),
1697 };
1698
1699 if builder.config.keep_stage.contains(&build_compiler.stage) {
1700 trace!("`keep-stage` requested");
1701 builder.info(
1702 "WARNING: Using a potentially old codegen backend. \
1703 This may not behave well.",
1704 );
1705 return GccCodegenBackendOutput { stamp, dylib_set };
1708 }
1709
1710 let mut cargo = builder::Cargo::new(
1711 builder,
1712 build_compiler,
1713 Mode::Codegen,
1714 SourceType::InTree,
1715 host,
1716 Kind::Build,
1717 );
1718 cargo.arg("--manifest-path").arg(builder.src.join("compiler/rustc_codegen_gcc/Cargo.toml"));
1719 rustc_cargo_env(builder, &mut cargo, host);
1720
1721 add_cg_gcc_cargo_flags(&mut cargo, dylib_set.host_dylib());
1722
1723 let _guard =
1724 builder.msg(Kind::Build, "codegen backend gcc", Mode::Codegen, build_compiler, host);
1725 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], false, false);
1726
1727 GccCodegenBackendOutput {
1728 stamp: write_codegen_backend_stamp(stamp, files, builder.config.dry_run()),
1729 dylib_set,
1730 }
1731 }
1732
1733 fn metadata(&self) -> Option<StepMetadata> {
1734 Some(
1735 StepMetadata::build("rustc_codegen_gcc", self.compilers.target())
1736 .built_by(self.compilers.build_compiler()),
1737 )
1738 }
1739}
1740
1741#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1742pub struct CraneliftCodegenBackend {
1743 pub compilers: RustcPrivateCompilers,
1744}
1745
1746impl Step for CraneliftCodegenBackend {
1747 type Output = BuildStamp;
1748 const IS_HOST: bool = true;
1749
1750 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1751 run.alias("rustc_codegen_cranelift").alias("cg_clif")
1752 }
1753
1754 fn make_run(run: RunConfig<'_>) {
1755 run.builder.ensure(CraneliftCodegenBackend {
1756 compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1757 });
1758 }
1759
1760 fn run(self, builder: &Builder<'_>) -> Self::Output {
1761 let target = self.compilers.target();
1762 let build_compiler = self.compilers.build_compiler();
1763
1764 let stamp = build_stamp::codegen_backend_stamp(
1765 builder,
1766 build_compiler,
1767 target,
1768 &CodegenBackendKind::Cranelift,
1769 );
1770
1771 if builder.config.keep_stage.contains(&build_compiler.stage) {
1772 trace!("`keep-stage` requested");
1773 builder.info(
1774 "WARNING: Using a potentially old codegen backend. \
1775 This may not behave well.",
1776 );
1777 return stamp;
1780 }
1781
1782 let mut cargo = builder::Cargo::new(
1783 builder,
1784 build_compiler,
1785 Mode::Codegen,
1786 SourceType::InTree,
1787 target,
1788 Kind::Build,
1789 );
1790 cargo
1791 .arg("--manifest-path")
1792 .arg(builder.src.join("compiler/rustc_codegen_cranelift/Cargo.toml"));
1793 rustc_cargo_env(builder, &mut cargo, target);
1794
1795 let _guard = builder.msg(
1796 Kind::Build,
1797 "codegen backend cranelift",
1798 Mode::Codegen,
1799 build_compiler,
1800 target,
1801 );
1802 let files = run_cargo(builder, cargo, vec![], &stamp, vec![], false, false);
1803 write_codegen_backend_stamp(stamp, files, builder.config.dry_run())
1804 }
1805
1806 fn metadata(&self) -> Option<StepMetadata> {
1807 Some(
1808 StepMetadata::build("rustc_codegen_cranelift", self.compilers.target())
1809 .built_by(self.compilers.build_compiler()),
1810 )
1811 }
1812}
1813
1814fn write_codegen_backend_stamp(
1816 mut stamp: BuildStamp,
1817 files: Vec<PathBuf>,
1818 dry_run: bool,
1819) -> BuildStamp {
1820 if dry_run {
1821 return stamp;
1822 }
1823
1824 let mut files = files.into_iter().filter(|f| {
1825 let filename = f.file_name().unwrap().to_str().unwrap();
1826 is_dylib(f) && filename.contains("rustc_codegen_")
1827 });
1828 let codegen_backend = match files.next() {
1829 Some(f) => f,
1830 None => panic!("no dylibs built for codegen backend?"),
1831 };
1832 if let Some(f) = files.next() {
1833 panic!("codegen backend built two dylibs:\n{}\n{}", codegen_backend.display(), f.display());
1834 }
1835
1836 let codegen_backend = codegen_backend.to_str().unwrap();
1837 stamp = stamp.add_stamp(codegen_backend);
1838 t!(stamp.write());
1839 stamp
1840}
1841
1842fn copy_codegen_backends_to_sysroot(
1849 builder: &Builder<'_>,
1850 stamp: BuildStamp,
1851 target_compiler: Compiler,
1852) {
1853 let dst = builder.sysroot_codegen_backends(target_compiler);
1862 t!(fs::create_dir_all(&dst), dst);
1863
1864 if builder.config.dry_run() {
1865 return;
1866 }
1867
1868 if stamp.path().exists() {
1869 let file = get_codegen_backend_file(&stamp);
1870 builder.copy_link(
1871 &file,
1872 &dst.join(normalize_codegen_backend_name(builder, &file)),
1873 FileType::NativeLibrary,
1874 );
1875 }
1876}
1877
1878pub fn get_codegen_backend_file(stamp: &BuildStamp) -> PathBuf {
1880 PathBuf::from(t!(fs::read_to_string(stamp.path())))
1881}
1882
1883pub fn normalize_codegen_backend_name(builder: &Builder<'_>, path: &Path) -> String {
1885 let filename = path.file_name().unwrap().to_str().unwrap();
1886 let dash = filename.find('-').unwrap();
1889 let dot = filename.find('.').unwrap();
1890 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1891}
1892
1893pub fn compiler_file(
1894 builder: &Builder<'_>,
1895 compiler: &Path,
1896 target: TargetSelection,
1897 c: CLang,
1898 file: &str,
1899) -> PathBuf {
1900 if builder.config.dry_run() {
1901 return PathBuf::new();
1902 }
1903 let mut cmd = command(compiler);
1904 cmd.args(builder.cc_handled_clags(target, c));
1905 cmd.args(builder.cc_unhandled_cflags(target, GitRepo::Rustc, c));
1906 cmd.arg(format!("-print-file-name={file}"));
1907 let out = cmd.run_capture_stdout(builder).stdout();
1908 PathBuf::from(out.trim())
1909}
1910
1911#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1912pub struct Sysroot {
1913 pub compiler: Compiler,
1914 force_recompile: bool,
1916}
1917
1918impl Sysroot {
1919 pub(crate) fn new(compiler: Compiler) -> Self {
1920 Sysroot { compiler, force_recompile: false }
1921 }
1922}
1923
1924impl Step for Sysroot {
1925 type Output = PathBuf;
1926
1927 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1928 run.never()
1929 }
1930
1931 fn run(self, builder: &Builder<'_>) -> PathBuf {
1935 let compiler = self.compiler;
1936 let host_dir = builder.out.join(compiler.host);
1937
1938 let sysroot_dir = |stage| {
1939 if stage == 0 {
1940 host_dir.join("stage0-sysroot")
1941 } else if self.force_recompile && stage == compiler.stage {
1942 host_dir.join(format!("stage{stage}-test-sysroot"))
1943 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1944 host_dir.join("ci-rustc-sysroot")
1945 } else {
1946 host_dir.join(format!("stage{stage}"))
1947 }
1948 };
1949 let sysroot = sysroot_dir(compiler.stage);
1950 trace!(stage = ?compiler.stage, ?sysroot);
1951
1952 builder.do_if_verbose(|| {
1953 println!("Removing sysroot {} to avoid caching bugs", sysroot.display())
1954 });
1955 let _ = fs::remove_dir_all(&sysroot);
1956 t!(fs::create_dir_all(&sysroot));
1957
1958 if compiler.stage == 0 {
1965 dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1966 }
1967
1968 if builder.download_rustc() && compiler.stage != 0 {
1970 assert_eq!(
1971 builder.config.host_target, compiler.host,
1972 "Cross-compiling is not yet supported with `download-rustc`",
1973 );
1974
1975 for stage in 0..=2 {
1977 if stage != compiler.stage {
1978 let dir = sysroot_dir(stage);
1979 if !dir.ends_with("ci-rustc-sysroot") {
1980 let _ = fs::remove_dir_all(dir);
1981 }
1982 }
1983 }
1984
1985 let mut filtered_files = Vec::new();
1995 let mut add_filtered_files = |suffix, contents| {
1996 for path in contents {
1997 let path = Path::new(&path);
1998 if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
1999 filtered_files.push(path.file_name().unwrap().to_owned());
2000 }
2001 }
2002 };
2003 let suffix = format!("lib/rustlib/{}/lib", compiler.host);
2004 add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
2005 add_filtered_files("lib", builder.config.ci_rust_std_contents());
2008
2009 let filtered_extensions = [
2010 OsStr::new("rmeta"),
2011 OsStr::new("rlib"),
2012 OsStr::new(std::env::consts::DLL_EXTENSION),
2014 ];
2015 let ci_rustc_dir = builder.config.ci_rustc_dir();
2016 builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
2017 if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
2018 return true;
2019 }
2020 if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
2021 return true;
2022 }
2023 filtered_files.iter().all(|f| f != path.file_name().unwrap())
2024 });
2025 }
2026
2027 if compiler.stage != 0 {
2033 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
2034 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
2035 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
2036 if let Err(e) =
2037 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust)
2038 {
2039 eprintln!(
2040 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2041 sysroot_lib_rustlib_src_rust.display(),
2042 builder.src.display(),
2043 e,
2044 );
2045 if builder.config.rust_remap_debuginfo {
2046 eprintln!(
2047 "ERROR: some `tests/ui` tests will fail when lacking `{}`",
2048 sysroot_lib_rustlib_src_rust.display(),
2049 );
2050 }
2051 build_helper::exit!(1);
2052 }
2053 }
2054
2055 if !builder.download_rustc() {
2057 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
2058 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
2059 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
2060 if let Err(e) =
2061 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
2062 {
2063 eprintln!(
2064 "ERROR: creating symbolic link `{}` to `{}` failed with {}",
2065 sysroot_lib_rustlib_rustcsrc_rust.display(),
2066 builder.src.display(),
2067 e,
2068 );
2069 build_helper::exit!(1);
2070 }
2071 }
2072
2073 sysroot
2074 }
2075}
2076
2077#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2084pub struct Assemble {
2085 pub target_compiler: Compiler,
2090}
2091
2092impl Step for Assemble {
2093 type Output = Compiler;
2094 const IS_HOST: bool = true;
2095
2096 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2097 run.path("compiler/rustc").path("compiler")
2098 }
2099
2100 fn make_run(run: RunConfig<'_>) {
2101 run.builder.ensure(Assemble {
2102 target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2103 });
2104 }
2105
2106 fn run(self, builder: &Builder<'_>) -> Compiler {
2107 let target_compiler = self.target_compiler;
2108
2109 if target_compiler.stage == 0 {
2110 trace!("stage 0 build compiler is always available, simply returning");
2111 assert_eq!(
2112 builder.config.host_target, target_compiler.host,
2113 "Cannot obtain compiler for non-native build triple at stage 0"
2114 );
2115 return target_compiler;
2117 }
2118
2119 let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2122 let libdir_bin = libdir.parent().unwrap().join("bin");
2123 t!(fs::create_dir_all(&libdir_bin));
2124
2125 if builder.config.llvm_enabled(target_compiler.host) {
2126 trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
2127
2128 let target = target_compiler.host;
2129 let llvm::LlvmResult { host_llvm_config, .. } = builder.ensure(llvm::Llvm { target });
2130 if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
2131 trace!("LLVM tools enabled");
2132
2133 let host_llvm_bin_dir = command(&host_llvm_config)
2134 .arg("--bindir")
2135 .cached()
2136 .run_capture_stdout(builder)
2137 .stdout()
2138 .trim()
2139 .to_string();
2140
2141 let llvm_bin_dir = if target == builder.host_target {
2142 PathBuf::from(host_llvm_bin_dir)
2143 } else {
2144 let external_llvm_config = builder
2147 .config
2148 .target_config
2149 .get(&target)
2150 .and_then(|t| t.llvm_config.clone());
2151 if let Some(external_llvm_config) = external_llvm_config {
2152 external_llvm_config.parent().unwrap().to_path_buf()
2155 } else {
2156 let host_llvm_out = builder.llvm_out(builder.host_target);
2160 let target_llvm_out = builder.llvm_out(target);
2161 if let Ok(relative_path) =
2162 Path::new(&host_llvm_bin_dir).strip_prefix(host_llvm_out)
2163 {
2164 target_llvm_out.join(relative_path)
2165 } else {
2166 PathBuf::from(
2169 host_llvm_bin_dir
2170 .replace(&*builder.host_target.triple, &target.triple),
2171 )
2172 }
2173 }
2174 };
2175
2176 #[cfg(feature = "tracing")]
2183 let _llvm_tools_span =
2184 span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
2185 .entered();
2186 for tool in LLVM_TOOLS {
2187 trace!("installing `{tool}`");
2188 let tool_exe = exe(tool, target_compiler.host);
2189 let src_path = llvm_bin_dir.join(&tool_exe);
2190
2191 if !src_path.exists() && builder.config.llvm_from_ci {
2193 eprintln!("{} does not exist; skipping copy", src_path.display());
2194 continue;
2195 }
2196
2197 builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2204 }
2205 }
2206 }
2207
2208 let maybe_install_llvm_bitcode_linker = || {
2209 if builder.config.llvm_bitcode_linker_enabled {
2210 trace!("llvm-bitcode-linker enabled, installing");
2211 let llvm_bitcode_linker = builder.ensure(
2212 crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler(
2213 builder,
2214 target_compiler,
2215 ),
2216 );
2217
2218 let bindir_self_contained = builder
2220 .sysroot(target_compiler)
2221 .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host));
2222 let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2223
2224 t!(fs::create_dir_all(&bindir_self_contained));
2225 builder.copy_link(
2226 &llvm_bitcode_linker.tool_path,
2227 &bindir_self_contained.join(tool_exe),
2228 FileType::Executable,
2229 );
2230 }
2231 };
2232
2233 if builder.download_rustc() {
2235 trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2236
2237 builder.std(target_compiler, target_compiler.host);
2238 let sysroot =
2239 builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2240 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2243 if target_compiler.stage == builder.top_stage {
2245 builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage));
2246 }
2247
2248 maybe_install_llvm_bitcode_linker();
2251
2252 return target_compiler;
2253 }
2254
2255 debug!(
2269 "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2270 target_compiler.stage - 1,
2271 builder.config.host_target,
2272 );
2273 let build_compiler =
2274 builder.compiler(target_compiler.stage - 1, builder.config.host_target);
2275
2276 if builder.config.llvm_enzyme && !builder.config.dry_run() {
2278 debug!("`llvm_enzyme` requested");
2279 let enzyme_install = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2280 if let Some(llvm_config) = builder.llvm_config(builder.config.host_target) {
2281 let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
2282 let lib_ext = std::env::consts::DLL_EXTENSION;
2283 let libenzyme = format!("libEnzyme-{llvm_version_major}");
2284 let src_lib =
2285 enzyme_install.join("build/Enzyme").join(&libenzyme).with_extension(lib_ext);
2286 let libdir = builder.sysroot_target_libdir(build_compiler, build_compiler.host);
2287 let target_libdir =
2288 builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2289 let dst_lib = libdir.join(&libenzyme).with_extension(lib_ext);
2290 let target_dst_lib = target_libdir.join(&libenzyme).with_extension(lib_ext);
2291 builder.copy_link(&src_lib, &dst_lib, FileType::NativeLibrary);
2292 builder.copy_link(&src_lib, &target_dst_lib, FileType::NativeLibrary);
2293 }
2294 }
2295
2296 debug!(
2299 ?build_compiler,
2300 "target_compiler.host" = ?target_compiler.host,
2301 "building compiler libraries to link to"
2302 );
2303
2304 let BuiltRustc { build_compiler } =
2306 builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2307
2308 let stage = target_compiler.stage;
2309 let host = target_compiler.host;
2310 let (host_info, dir_name) = if build_compiler.host == host {
2311 ("".into(), "host".into())
2312 } else {
2313 (format!(" ({host})"), host.to_string())
2314 };
2315 let msg = format!(
2320 "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2321 );
2322 builder.info(&msg);
2323
2324 let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2326 let proc_macros = builder
2327 .read_stamp_file(&stamp)
2328 .into_iter()
2329 .filter_map(|(path, dependency_type)| {
2330 if dependency_type == DependencyType::Host {
2331 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2332 } else {
2333 None
2334 }
2335 })
2336 .collect::<HashSet<_>>();
2337
2338 let sysroot = builder.sysroot(target_compiler);
2339 let rustc_libdir = builder.rustc_libdir(target_compiler);
2340 t!(fs::create_dir_all(&rustc_libdir));
2341 let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2342 for f in builder.read_dir(&src_libdir) {
2343 let filename = f.file_name().into_string().unwrap();
2344
2345 let is_proc_macro = proc_macros.contains(&filename);
2346 let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2347
2348 let can_be_rustc_dynamic_dep = if builder
2352 .link_std_into_rustc_driver(target_compiler.host)
2353 && !target_compiler.host.is_windows()
2354 {
2355 let is_std = filename.starts_with("std-") || filename.starts_with("libstd-");
2356 !is_std
2357 } else {
2358 true
2359 };
2360
2361 if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2362 builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2363 }
2364 }
2365
2366 {
2367 #[cfg(feature = "tracing")]
2368 let _codegen_backend_span =
2369 span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2370
2371 for backend in builder.config.enabled_codegen_backends(target_compiler.host) {
2372 if builder.kind == Kind::Check && builder.top_stage == 1 {
2389 continue;
2390 }
2391
2392 let prepare_compilers = || {
2393 RustcPrivateCompilers::from_build_and_target_compiler(
2394 build_compiler,
2395 target_compiler,
2396 )
2397 };
2398
2399 match backend {
2400 CodegenBackendKind::Cranelift => {
2401 let stamp = builder
2402 .ensure(CraneliftCodegenBackend { compilers: prepare_compilers() });
2403 copy_codegen_backends_to_sysroot(builder, stamp, target_compiler);
2404 }
2405 CodegenBackendKind::Gcc => {
2406 let compilers = prepare_compilers();
2438
2439 let mut targets = HashSet::new();
2444 for target in &builder.hosts {
2447 targets.insert(*target);
2448 }
2449 for target in &builder.targets {
2451 targets.insert(*target);
2452 }
2453 targets.insert(compilers.target_compiler().host);
2456
2457 let output = builder.ensure(GccCodegenBackend::for_targets(
2458 compilers,
2459 targets.into_iter().collect(),
2460 ));
2461 copy_codegen_backends_to_sysroot(builder, output.stamp, target_compiler);
2462 output.dylib_set.install_to(builder, target_compiler);
2465 }
2466 CodegenBackendKind::Llvm | CodegenBackendKind::Custom(_) => continue,
2467 }
2468 }
2469 }
2470
2471 if builder.config.lld_enabled {
2472 let lld_wrapper =
2473 builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler(
2474 builder,
2475 target_compiler,
2476 ));
2477 copy_lld_artifacts(builder, lld_wrapper, target_compiler);
2478 }
2479
2480 if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2481 debug!(
2482 "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2483 workaround faulty homebrew `strip`s"
2484 );
2485
2486 let src_exe = exe("llvm-objcopy", target_compiler.host);
2493 let dst_exe = exe("rust-objcopy", target_compiler.host);
2494 builder.copy_link(
2495 &libdir_bin.join(src_exe),
2496 &libdir_bin.join(dst_exe),
2497 FileType::Executable,
2498 );
2499 }
2500
2501 if builder.tool_enabled("wasm-component-ld") {
2504 let wasm_component = builder.ensure(
2505 crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler(
2506 builder,
2507 target_compiler,
2508 ),
2509 );
2510 builder.copy_link(
2511 &wasm_component.tool_path,
2512 &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2513 FileType::Executable,
2514 );
2515 }
2516
2517 maybe_install_llvm_bitcode_linker();
2518
2519 debug!(
2522 "target_compiler.host" = ?target_compiler.host,
2523 ?sysroot,
2524 "ensuring availability of `libLLVM.so` in compiler directory"
2525 );
2526 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2527 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2528
2529 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2531 let rustc = out_dir.join(exe("rustc-main", host));
2532 let bindir = sysroot.join("bin");
2533 t!(fs::create_dir_all(bindir));
2534 let compiler = builder.rustc(target_compiler);
2535 debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2536 builder.copy_link(&rustc, &compiler, FileType::Executable);
2537
2538 target_compiler
2539 }
2540}
2541
2542#[track_caller]
2547pub fn add_to_sysroot(
2548 builder: &Builder<'_>,
2549 sysroot_dst: &Path,
2550 sysroot_host_dst: &Path,
2551 stamp: &BuildStamp,
2552) {
2553 let self_contained_dst = &sysroot_dst.join("self-contained");
2554 t!(fs::create_dir_all(sysroot_dst));
2555 t!(fs::create_dir_all(sysroot_host_dst));
2556 t!(fs::create_dir_all(self_contained_dst));
2557
2558 let mut crates = HashMap::new();
2559 for (path, dependency_type) in builder.read_stamp_file(stamp) {
2560 let filename = path.file_name().unwrap().to_str().unwrap();
2561 let dst = match dependency_type {
2562 DependencyType::Host => {
2563 if sysroot_dst == sysroot_host_dst {
2564 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2567 }
2568
2569 sysroot_host_dst
2570 }
2571 DependencyType::Target => {
2572 crates.insert(filename.split_once('.').unwrap().0.to_owned(), path.clone());
2575
2576 sysroot_dst
2577 }
2578 DependencyType::TargetSelfContained => self_contained_dst,
2579 };
2580 builder.copy_link(&path, &dst.join(filename), FileType::Regular);
2581 }
2582
2583 let mut seen_crates = HashMap::new();
2589 for (filestem, path) in crates {
2590 if !filestem.contains("rustc_") || filestem.contains("rustc_hash") {
2591 continue;
2592 }
2593 if let Some(other_path) =
2594 seen_crates.insert(filestem.split_once('-').unwrap().0.to_owned(), path.clone())
2595 {
2596 panic!(
2597 "duplicate rustc crate {}\n- first copy at {}\n- second copy at {}",
2598 filestem.split_once('-').unwrap().0.to_owned(),
2599 other_path.display(),
2600 path.display(),
2601 );
2602 }
2603 }
2604}
2605
2606pub fn run_cargo(
2607 builder: &Builder<'_>,
2608 cargo: Cargo,
2609 tail_args: Vec<String>,
2610 stamp: &BuildStamp,
2611 additional_target_deps: Vec<(PathBuf, DependencyType)>,
2612 is_check: bool,
2613 rlib_only_metadata: bool,
2614) -> Vec<PathBuf> {
2615 let target_root_dir = stamp.path().parent().unwrap();
2617 let target_deps_dir = target_root_dir.join("deps");
2619 let host_root_dir = target_root_dir
2621 .parent()
2622 .unwrap() .parent()
2624 .unwrap() .join(target_root_dir.file_name().unwrap());
2626
2627 let mut deps = Vec::new();
2631 let mut toplevel = Vec::new();
2632 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2633 let (filenames_vec, crate_types) = match msg {
2634 CargoMessage::CompilerArtifact {
2635 filenames,
2636 target: CargoTarget { crate_types },
2637 ..
2638 } => {
2639 let mut f: Vec<String> = filenames.into_iter().map(|s| s.into_owned()).collect();
2640 f.sort(); (f, crate_types)
2642 }
2643 _ => return,
2644 };
2645 for filename in filenames_vec {
2646 let mut keep = false;
2648 if filename.ends_with(".lib")
2649 || filename.ends_with(".a")
2650 || is_debug_info(&filename)
2651 || is_dylib(Path::new(&*filename))
2652 {
2653 keep = true;
2655 }
2656 if is_check && filename.ends_with(".rmeta") {
2657 keep = true;
2659 } else if rlib_only_metadata {
2660 if filename.contains("jemalloc_sys")
2661 || filename.contains("rustc_public_bridge")
2662 || filename.contains("rustc_public")
2663 {
2664 keep |= filename.ends_with(".rlib");
2667 } else {
2668 keep |= filename.ends_with(".rmeta");
2672 }
2673 } else {
2674 keep |= filename.ends_with(".rlib");
2676 }
2677
2678 if !keep {
2679 continue;
2680 }
2681
2682 let filename = Path::new(&*filename);
2683
2684 if filename.starts_with(&host_root_dir) {
2687 if crate_types.iter().any(|t| t == "proc-macro") {
2689 if filename.file_name().unwrap().to_str().unwrap().contains("-") {
2694 deps.push((filename.to_path_buf(), DependencyType::Host));
2695 }
2696 }
2697 continue;
2698 }
2699
2700 if filename.starts_with(&target_deps_dir) {
2703 deps.push((filename.to_path_buf(), DependencyType::Target));
2704 continue;
2705 }
2706
2707 let expected_len = t!(filename.metadata()).len();
2718 let filename = filename.file_name().unwrap().to_str().unwrap();
2719 let mut parts = filename.splitn(2, '.');
2720 let file_stem = parts.next().unwrap().to_owned();
2721 let extension = parts.next().unwrap().to_owned();
2722
2723 toplevel.push((file_stem, extension, expected_len));
2724 }
2725 });
2726
2727 if !ok {
2728 crate::exit!(1);
2729 }
2730
2731 if builder.config.dry_run() {
2732 return Vec::new();
2733 }
2734
2735 let contents = target_deps_dir
2739 .read_dir()
2740 .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_deps_dir.display(), e))
2741 .map(|e| t!(e))
2742 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2743 .collect::<Vec<_>>();
2744 for (prefix, extension, expected_len) in toplevel {
2745 let candidates = contents.iter().filter(|&(_, filename, meta)| {
2746 meta.len() == expected_len
2747 && filename
2748 .strip_prefix(&prefix[..])
2749 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2750 .unwrap_or(false)
2751 });
2752 let max = candidates.max_by_key(|&(_, _, metadata)| {
2753 metadata.modified().expect("mtime should be available on all relevant OSes")
2754 });
2755 let path_to_add = match max {
2756 Some(triple) => triple.0.to_str().unwrap(),
2757 None => panic!("no output generated for {prefix:?} {extension:?}"),
2758 };
2759 if is_dylib(Path::new(path_to_add)) {
2760 let candidate = format!("{path_to_add}.lib");
2761 let candidate = PathBuf::from(candidate);
2762 if candidate.exists() {
2763 deps.push((candidate, DependencyType::Target));
2764 }
2765 }
2766 deps.push((path_to_add.into(), DependencyType::Target));
2767 }
2768
2769 deps.extend(additional_target_deps);
2770 deps.sort();
2771 let mut new_contents = Vec::new();
2772 for (dep, dependency_type) in deps.iter() {
2773 new_contents.extend(match *dependency_type {
2774 DependencyType::Host => b"h",
2775 DependencyType::Target => b"t",
2776 DependencyType::TargetSelfContained => b"s",
2777 });
2778 new_contents.extend(dep.to_str().unwrap().as_bytes());
2779 new_contents.extend(b"\0");
2780 }
2781 t!(fs::write(stamp.path(), &new_contents));
2782 deps.into_iter().map(|(d, _)| d).collect()
2783}
2784
2785pub fn stream_cargo(
2786 builder: &Builder<'_>,
2787 cargo: Cargo,
2788 tail_args: Vec<String>,
2789 cb: &mut dyn FnMut(CargoMessage<'_>),
2790) -> bool {
2791 let mut cmd = cargo.into_cmd();
2792
2793 let mut message_format = if builder.config.json_output {
2796 String::from("json")
2797 } else {
2798 String::from("json-render-diagnostics")
2799 };
2800 if let Some(s) = &builder.config.rustc_error_format {
2801 message_format.push_str(",json-diagnostic-");
2802 message_format.push_str(s);
2803 }
2804 cmd.arg("--message-format").arg(message_format);
2805
2806 for arg in tail_args {
2807 cmd.arg(arg);
2808 }
2809
2810 builder.do_if_verbose(|| println!("running: {cmd:?}"));
2811
2812 let streaming_command = cmd.stream_capture_stdout(&builder.config.exec_ctx);
2813
2814 let Some(mut streaming_command) = streaming_command else {
2815 return true;
2816 };
2817
2818 let stdout = BufReader::new(streaming_command.stdout.take().unwrap());
2822 for line in stdout.lines() {
2823 let line = t!(line);
2824 match serde_json::from_str::<CargoMessage<'_>>(&line) {
2825 Ok(msg) => {
2826 if builder.config.json_output {
2827 println!("{line}");
2829 }
2830 cb(msg)
2831 }
2832 Err(_) => println!("{line}"),
2834 }
2835 }
2836
2837 let status = t!(streaming_command.wait(&builder.config.exec_ctx));
2839 if builder.is_verbose() && !status.success() {
2840 eprintln!(
2841 "command did not execute successfully: {cmd:?}\n\
2842 expected success, got: {status}"
2843 );
2844 }
2845
2846 status.success()
2847}
2848
2849#[derive(Deserialize)]
2850pub struct CargoTarget<'a> {
2851 crate_types: Vec<Cow<'a, str>>,
2852}
2853
2854#[derive(Deserialize)]
2855#[serde(tag = "reason", rename_all = "kebab-case")]
2856pub enum CargoMessage<'a> {
2857 CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2858 BuildScriptExecuted,
2859 BuildFinished,
2860}
2861
2862pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2863 if target != "x86_64-unknown-linux-gnu"
2867 || !builder.config.is_host_target(target)
2868 || !path.exists()
2869 {
2870 return;
2871 }
2872
2873 let previous_mtime = t!(t!(path.metadata()).modified());
2874 let stamp = BuildStamp::new(path.parent().unwrap())
2875 .with_prefix(path.file_name().unwrap().to_str().unwrap())
2876 .with_prefix("strip")
2877 .add_stamp(previous_mtime.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos());
2878
2879 if !stamp.is_up_to_date() {
2882 command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2883 }
2884 t!(stamp.write());
2885
2886 let file = t!(fs::File::open(path));
2887
2888 t!(file.set_modified(previous_mtime));
2901}
2902
2903pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2905 build_compiler.stage != 0
2906}