]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Rollup merge of #106797 - FawazTirmizi:dev/issues/104284, r=bjorn3
[rust.git] / src / bootstrap / compile.rs
1 //! Implementation of compiling various phases of the compiler and standard
2 //! library.
3 //!
4 //! This module contains some of the real meat in the rustbuild build system
5 //! which is where Cargo is used to compile the standard library, libtest, and
6 //! the compiler. This module is also responsible for assembling the sysroot as it
7 //! goes along from the output of the previous stage.
8
9 use std::borrow::Cow;
10 use std::collections::HashSet;
11 use std::env;
12 use std::fs;
13 use std::io::prelude::*;
14 use std::io::BufReader;
15 use std::path::{Path, PathBuf};
16 use std::process::{Command, Stdio};
17 use std::str;
18
19 use serde::Deserialize;
20
21 use crate::builder::crate_description;
22 use crate::builder::Cargo;
23 use crate::builder::{Builder, Kind, RunConfig, ShouldRun, Step};
24 use crate::cache::{Interned, INTERNER};
25 use crate::config::{LlvmLibunwind, RustcLto, TargetSelection};
26 use crate::dist;
27 use crate::native;
28 use crate::tool::SourceType;
29 use crate::util::get_clang_cl_resource_dir;
30 use crate::util::{exe, is_debug_info, is_dylib, output, symlink_dir, t, up_to_date};
31 use crate::LLVM_TOOLS;
32 use crate::{CLang, Compiler, DependencyType, GitRepo, Mode};
33
34 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
35 pub struct Std {
36     pub target: TargetSelection,
37     pub compiler: Compiler,
38     /// Whether to build only a subset of crates in the standard library.
39     ///
40     /// This shouldn't be used from other steps; see the comment on [`Rustc`].
41     crates: Interned<Vec<String>>,
42 }
43
44 impl Std {
45     pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
46         Self { target, compiler, crates: Default::default() }
47     }
48 }
49
50 impl Step for Std {
51     type Output = ();
52     const DEFAULT: bool = true;
53
54     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
55         // When downloading stage1, the standard library has already been copied to the sysroot, so
56         // there's no need to rebuild it.
57         let builder = run.builder;
58         run.crate_or_deps("test")
59             .path("library")
60             .lazy_default_condition(Box::new(|| !builder.download_rustc()))
61     }
62
63     fn make_run(run: RunConfig<'_>) {
64         // Normally, people will pass *just* library if they pass it.
65         // But it's possible (although strange) to pass something like `library std core`.
66         // Build all crates anyway, as if they hadn't passed the other args.
67         let has_library =
68             run.paths.iter().any(|set| set.assert_single_path().path.ends_with("library"));
69         let crates = if has_library { Default::default() } else { run.cargo_crates_in_set() };
70         run.builder.ensure(Std {
71             compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
72             target: run.target,
73             crates,
74         });
75     }
76
77     /// Builds the standard library.
78     ///
79     /// This will build the standard library for a particular stage of the build
80     /// using the `compiler` targeting the `target` architecture. The artifacts
81     /// created will also be linked into the sysroot directory.
82     fn run(self, builder: &Builder<'_>) {
83         let target = self.target;
84         let compiler = self.compiler;
85
86         // These artifacts were already copied (in `impl Step for Sysroot`).
87         // Don't recompile them.
88         // NOTE: the ABI of the beta compiler is different from the ABI of the downloaded compiler,
89         // so its artifacts can't be reused.
90         if builder.download_rustc() && compiler.stage != 0 {
91             return;
92         }
93
94         if builder.config.keep_stage.contains(&compiler.stage)
95             || builder.config.keep_stage_std.contains(&compiler.stage)
96         {
97             builder.info("Warning: Using a potentially old libstd. This may not behave well.");
98             builder.ensure(StdLink::from_std(self, compiler));
99             return;
100         }
101
102         builder.update_submodule(&Path::new("library").join("stdarch"));
103
104         // Profiler information requires LLVM's compiler-rt
105         if builder.config.profiler {
106             builder.update_submodule(&Path::new("src/llvm-project"));
107         }
108
109         let mut target_deps = builder.ensure(StartupObjects { compiler, target });
110
111         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
112         if compiler_to_use != compiler {
113             builder.ensure(Std::new(compiler_to_use, target));
114             builder.info(&format!(
115                 "Uplifting stage1 library ({} -> {})",
116                 compiler_to_use.host, target
117             ));
118
119             // Even if we're not building std this stage, the new sysroot must
120             // still contain the third party objects needed by various targets.
121             copy_third_party_objects(builder, &compiler, target);
122             copy_self_contained_objects(builder, &compiler, target);
123
124             builder.ensure(StdLink::from_std(self, compiler_to_use));
125             return;
126         }
127
128         target_deps.extend(copy_third_party_objects(builder, &compiler, target));
129         target_deps.extend(copy_self_contained_objects(builder, &compiler, target));
130
131         let mut cargo = builder.cargo(compiler, Mode::Std, SourceType::InTree, target, "build");
132         std_cargo(builder, target, compiler.stage, &mut cargo);
133         for krate in &*self.crates {
134             cargo.arg("-p").arg(krate);
135         }
136
137         builder.info(&format!(
138             "Building{} stage{} library artifacts ({} -> {})",
139             crate_description(&self.crates),
140             compiler.stage,
141             &compiler.host,
142             target,
143         ));
144         run_cargo(
145             builder,
146             cargo,
147             vec![],
148             &libstd_stamp(builder, compiler, target),
149             target_deps,
150             false,
151             false,
152         );
153
154         builder.ensure(StdLink::from_std(
155             self,
156             builder.compiler(compiler.stage, builder.config.build),
157         ));
158     }
159 }
160
161 fn copy_and_stamp(
162     builder: &Builder<'_>,
163     libdir: &Path,
164     sourcedir: &Path,
165     name: &str,
166     target_deps: &mut Vec<(PathBuf, DependencyType)>,
167     dependency_type: DependencyType,
168 ) {
169     let target = libdir.join(name);
170     builder.copy(&sourcedir.join(name), &target);
171
172     target_deps.push((target, dependency_type));
173 }
174
175 fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
176     let libunwind_path = builder.ensure(native::Libunwind { target });
177     let libunwind_source = libunwind_path.join("libunwind.a");
178     let libunwind_target = libdir.join("libunwind.a");
179     builder.copy(&libunwind_source, &libunwind_target);
180     libunwind_target
181 }
182
183 /// Copies third party objects needed by various targets.
184 fn copy_third_party_objects(
185     builder: &Builder<'_>,
186     compiler: &Compiler,
187     target: TargetSelection,
188 ) -> Vec<(PathBuf, DependencyType)> {
189     let mut target_deps = vec![];
190
191     // FIXME: remove this in 2021
192     if target == "x86_64-fortanix-unknown-sgx" {
193         if env::var_os("X86_FORTANIX_SGX_LIBS").is_some() {
194             builder.info("Warning: X86_FORTANIX_SGX_LIBS environment variable is ignored, libunwind is now compiled as part of rustbuild");
195         }
196     }
197
198     if builder.config.sanitizers_enabled(target) && compiler.stage != 0 {
199         // The sanitizers are only copied in stage1 or above,
200         // to avoid creating dependency on LLVM.
201         target_deps.extend(
202             copy_sanitizers(builder, &compiler, target)
203                 .into_iter()
204                 .map(|d| (d, DependencyType::Target)),
205         );
206     }
207
208     if target == "x86_64-fortanix-unknown-sgx"
209         || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
210             && (target.contains("linux") || target.contains("fuchsia"))
211     {
212         let libunwind_path =
213             copy_llvm_libunwind(builder, target, &builder.sysroot_libdir(*compiler, target));
214         target_deps.push((libunwind_path, DependencyType::Target));
215     }
216
217     target_deps
218 }
219
220 /// Copies third party objects needed by various targets for self-contained linkage.
221 fn copy_self_contained_objects(
222     builder: &Builder<'_>,
223     compiler: &Compiler,
224     target: TargetSelection,
225 ) -> Vec<(PathBuf, DependencyType)> {
226     let libdir_self_contained = builder.sysroot_libdir(*compiler, target).join("self-contained");
227     t!(fs::create_dir_all(&libdir_self_contained));
228     let mut target_deps = vec![];
229
230     // Copies the libc and CRT objects.
231     //
232     // rustc historically provides a more self-contained installation for musl targets
233     // not requiring the presence of a native musl toolchain. For example, it can fall back
234     // to using gcc from a glibc-targeting toolchain for linking.
235     // To do that we have to distribute musl startup objects as a part of Rust toolchain
236     // and link with them manually in the self-contained mode.
237     if target.contains("musl") {
238         let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
239             panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
240         });
241         for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
242             copy_and_stamp(
243                 builder,
244                 &libdir_self_contained,
245                 &srcdir,
246                 obj,
247                 &mut target_deps,
248                 DependencyType::TargetSelfContained,
249             );
250         }
251         let crt_path = builder.ensure(native::CrtBeginEnd { target });
252         for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
253             let src = crt_path.join(obj);
254             let target = libdir_self_contained.join(obj);
255             builder.copy(&src, &target);
256             target_deps.push((target, DependencyType::TargetSelfContained));
257         }
258
259         if !target.starts_with("s390x") {
260             let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
261             target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
262         }
263     } else if target.ends_with("-wasi") {
264         let srcdir = builder
265             .wasi_root(target)
266             .unwrap_or_else(|| {
267                 panic!("Target {:?} does not have a \"wasi-root\" key", target.triple)
268             })
269             .join("lib/wasm32-wasi");
270         for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
271             copy_and_stamp(
272                 builder,
273                 &libdir_self_contained,
274                 &srcdir,
275                 obj,
276                 &mut target_deps,
277                 DependencyType::TargetSelfContained,
278             );
279         }
280     } else if target.ends_with("windows-gnu") {
281         for obj in ["crt2.o", "dllcrt2.o"].iter() {
282             let src = compiler_file(builder, builder.cc(target), target, CLang::C, obj);
283             let target = libdir_self_contained.join(obj);
284             builder.copy(&src, &target);
285             target_deps.push((target, DependencyType::TargetSelfContained));
286         }
287     }
288
289     target_deps
290 }
291
292 /// Configure cargo to compile the standard library, adding appropriate env vars
293 /// and such.
294 pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, stage: u32, cargo: &mut Cargo) {
295     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
296         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
297     }
298
299     // Determine if we're going to compile in optimized C intrinsics to
300     // the `compiler-builtins` crate. These intrinsics live in LLVM's
301     // `compiler-rt` repository, but our `src/llvm-project` submodule isn't
302     // always checked out, so we need to conditionally look for this. (e.g. if
303     // an external LLVM is used we skip the LLVM submodule checkout).
304     //
305     // Note that this shouldn't affect the correctness of `compiler-builtins`,
306     // but only its speed. Some intrinsics in C haven't been translated to Rust
307     // yet but that's pretty rare. Other intrinsics have optimized
308     // implementations in C which have only had slower versions ported to Rust,
309     // so we favor the C version where we can, but it's not critical.
310     //
311     // If `compiler-rt` is available ensure that the `c` feature of the
312     // `compiler-builtins` crate is enabled and it's configured to learn where
313     // `compiler-rt` is located.
314     let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
315     let compiler_builtins_c_feature = if compiler_builtins_root.exists() {
316         // Note that `libprofiler_builtins/build.rs` also computes this so if
317         // you're changing something here please also change that.
318         cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
319         " compiler-builtins-c"
320     } else {
321         ""
322     };
323
324     let mut features = String::new();
325
326     // Cranelift doesn't support `asm`.
327     if stage != 0 && builder.config.default_codegen_backend().unwrap_or_default() == "cranelift" {
328         features += " compiler-builtins-no-asm";
329     }
330
331     if builder.no_std(target) == Some(true) {
332         features += " compiler-builtins-mem";
333         if !target.starts_with("bpf") {
334             features.push_str(compiler_builtins_c_feature);
335         }
336
337         // for no-std targets we only compile a few no_std crates
338         cargo
339             .args(&["-p", "alloc"])
340             .arg("--manifest-path")
341             .arg(builder.src.join("library/alloc/Cargo.toml"))
342             .arg("--features")
343             .arg(features);
344     } else {
345         features += &builder.std_features(target);
346         features.push_str(compiler_builtins_c_feature);
347
348         cargo
349             .arg("--features")
350             .arg(features)
351             .arg("--manifest-path")
352             .arg(builder.src.join("library/test/Cargo.toml"));
353
354         // Help the libc crate compile by assisting it in finding various
355         // sysroot native libraries.
356         if target.contains("musl") {
357             if let Some(p) = builder.musl_libdir(target) {
358                 let root = format!("native={}", p.to_str().unwrap());
359                 cargo.rustflag("-L").rustflag(&root);
360             }
361         }
362
363         if target.ends_with("-wasi") {
364             if let Some(p) = builder.wasi_root(target) {
365                 let root = format!("native={}/lib/wasm32-wasi", p.to_str().unwrap());
366                 cargo.rustflag("-L").rustflag(&root);
367             }
368         }
369     }
370
371     // By default, rustc uses `-Cembed-bitcode=yes`, and Cargo overrides that
372     // with `-Cembed-bitcode=no` for non-LTO builds. However, libstd must be
373     // built with bitcode so that the produced rlibs can be used for both LTO
374     // builds (which use bitcode) and non-LTO builds (which use object code).
375     // So we override the override here!
376     //
377     // But we don't bother for the stage 0 compiler because it's never used
378     // with LTO.
379     if stage >= 1 {
380         cargo.rustflag("-Cembed-bitcode=yes");
381     }
382
383     // By default, rustc does not include unwind tables unless they are required
384     // for a particular target. They are not required by RISC-V targets, but
385     // compiling the standard library with them means that users can get
386     // backtraces without having to recompile the standard library themselves.
387     //
388     // This choice was discussed in https://github.com/rust-lang/rust/pull/69890
389     if target.contains("riscv") {
390         cargo.rustflag("-Cforce-unwind-tables=yes");
391     }
392
393     let html_root =
394         format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
395     cargo.rustflag(&html_root);
396     cargo.rustdocflag(&html_root);
397 }
398
399 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
400 struct StdLink {
401     pub compiler: Compiler,
402     pub target_compiler: Compiler,
403     pub target: TargetSelection,
404     /// Not actually used; only present to make sure the cache invalidation is correct.
405     crates: Interned<Vec<String>>,
406 }
407
408 impl StdLink {
409     fn from_std(std: Std, host_compiler: Compiler) -> Self {
410         Self {
411             compiler: host_compiler,
412             target_compiler: std.compiler,
413             target: std.target,
414             crates: std.crates,
415         }
416     }
417 }
418
419 impl Step for StdLink {
420     type Output = ();
421
422     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
423         run.never()
424     }
425
426     /// Link all libstd rlibs/dylibs into the sysroot location.
427     ///
428     /// Links those artifacts generated by `compiler` to the `stage` compiler's
429     /// sysroot for the specified `host` and `target`.
430     ///
431     /// Note that this assumes that `compiler` has already generated the libstd
432     /// libraries for `target`, and this method will find them in the relevant
433     /// output directory.
434     fn run(self, builder: &Builder<'_>) {
435         let compiler = self.compiler;
436         let target_compiler = self.target_compiler;
437         let target = self.target;
438         builder.info(&format!(
439             "Copying stage{} library from stage{} ({} -> {} / {})",
440             target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
441         ));
442         let libdir = builder.sysroot_libdir(target_compiler, target);
443         let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
444         add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
445     }
446 }
447
448 /// Copies sanitizer runtime libraries into target libdir.
449 fn copy_sanitizers(
450     builder: &Builder<'_>,
451     compiler: &Compiler,
452     target: TargetSelection,
453 ) -> Vec<PathBuf> {
454     let runtimes: Vec<native::SanitizerRuntime> = builder.ensure(native::Sanitizers { target });
455
456     if builder.config.dry_run() {
457         return Vec::new();
458     }
459
460     let mut target_deps = Vec::new();
461     let libdir = builder.sysroot_libdir(*compiler, target);
462
463     for runtime in &runtimes {
464         let dst = libdir.join(&runtime.name);
465         builder.copy(&runtime.path, &dst);
466
467         if target == "x86_64-apple-darwin" || target == "aarch64-apple-darwin" {
468             // Update the library’s install name to reflect that it has been renamed.
469             apple_darwin_update_library_name(&dst, &format!("@rpath/{}", &runtime.name));
470             // Upon renaming the install name, the code signature of the file will invalidate,
471             // so we will sign it again.
472             apple_darwin_sign_file(&dst);
473         }
474
475         target_deps.push(dst);
476     }
477
478     target_deps
479 }
480
481 fn apple_darwin_update_library_name(library_path: &Path, new_name: &str) {
482     let status = Command::new("install_name_tool")
483         .arg("-id")
484         .arg(new_name)
485         .arg(library_path)
486         .status()
487         .expect("failed to execute `install_name_tool`");
488     assert!(status.success());
489 }
490
491 fn apple_darwin_sign_file(file_path: &Path) {
492     let status = Command::new("codesign")
493         .arg("-f") // Force to rewrite the existing signature
494         .arg("-s")
495         .arg("-")
496         .arg(file_path)
497         .status()
498         .expect("failed to execute `codesign`");
499     assert!(status.success());
500 }
501
502 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
503 pub struct StartupObjects {
504     pub compiler: Compiler,
505     pub target: TargetSelection,
506 }
507
508 impl Step for StartupObjects {
509     type Output = Vec<(PathBuf, DependencyType)>;
510
511     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
512         run.path("library/rtstartup")
513     }
514
515     fn make_run(run: RunConfig<'_>) {
516         run.builder.ensure(StartupObjects {
517             compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
518             target: run.target,
519         });
520     }
521
522     /// Builds and prepare startup objects like rsbegin.o and rsend.o
523     ///
524     /// These are primarily used on Windows right now for linking executables/dlls.
525     /// They don't require any library support as they're just plain old object
526     /// files, so we just use the nightly snapshot compiler to always build them (as
527     /// no other compilers are guaranteed to be available).
528     fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
529         let for_compiler = self.compiler;
530         let target = self.target;
531         if !target.ends_with("windows-gnu") {
532             return vec![];
533         }
534
535         let mut target_deps = vec![];
536
537         let src_dir = &builder.src.join("library").join("rtstartup");
538         let dst_dir = &builder.native_dir(target).join("rtstartup");
539         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
540         t!(fs::create_dir_all(dst_dir));
541
542         for file in &["rsbegin", "rsend"] {
543             let src_file = &src_dir.join(file.to_string() + ".rs");
544             let dst_file = &dst_dir.join(file.to_string() + ".o");
545             if !up_to_date(src_file, dst_file) {
546                 let mut cmd = Command::new(&builder.initial_rustc);
547                 cmd.env("RUSTC_BOOTSTRAP", "1");
548                 if !builder.local_rebuild {
549                     // a local_rebuild compiler already has stage1 features
550                     cmd.arg("--cfg").arg("bootstrap");
551                 }
552                 builder.run(
553                     cmd.arg("--target")
554                         .arg(target.rustc_target_arg())
555                         .arg("--emit=obj")
556                         .arg("-o")
557                         .arg(dst_file)
558                         .arg(src_file),
559                 );
560             }
561
562             let target = sysroot_dir.join((*file).to_string() + ".o");
563             builder.copy(dst_file, &target);
564             target_deps.push((target, DependencyType::Target));
565         }
566
567         target_deps
568     }
569 }
570
571 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
572 pub struct Rustc {
573     pub target: TargetSelection,
574     pub compiler: Compiler,
575     /// Whether to build a subset of crates, rather than the whole compiler.
576     ///
577     /// This should only be requested by the user, not used within rustbuild itself.
578     /// Using it within rustbuild can lead to confusing situation where lints are replayed
579     /// in two different steps.
580     crates: Interned<Vec<String>>,
581 }
582
583 impl Rustc {
584     pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
585         Self { target, compiler, crates: Default::default() }
586     }
587 }
588
589 impl Step for Rustc {
590     type Output = ();
591     const ONLY_HOSTS: bool = true;
592     const DEFAULT: bool = false;
593
594     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
595         let mut crates = run.builder.in_tree_crates("rustc-main", None);
596         for (i, krate) in crates.iter().enumerate() {
597             if krate.name == "rustc-main" {
598                 crates.swap_remove(i);
599                 break;
600             }
601         }
602         run.crates(crates)
603     }
604
605     fn make_run(run: RunConfig<'_>) {
606         let crates = run.cargo_crates_in_set();
607         run.builder.ensure(Rustc {
608             compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
609             target: run.target,
610             crates,
611         });
612     }
613
614     /// Builds the compiler.
615     ///
616     /// This will build the compiler for a particular stage of the build using
617     /// the `compiler` targeting the `target` architecture. The artifacts
618     /// created will also be linked into the sysroot directory.
619     fn run(self, builder: &Builder<'_>) {
620         let compiler = self.compiler;
621         let target = self.target;
622
623         // NOTE: the ABI of the beta compiler is different from the ABI of the downloaded compiler,
624         // so its artifacts can't be reused.
625         if builder.download_rustc() && compiler.stage != 0 {
626             // Copy the existing artifacts instead of rebuilding them.
627             // NOTE: this path is only taken for tools linking to rustc-dev.
628             builder.ensure(Sysroot { compiler });
629             return;
630         }
631
632         builder.ensure(Std::new(compiler, target));
633
634         if builder.config.keep_stage.contains(&compiler.stage) {
635             builder.info("Warning: Using a potentially old librustc. This may not behave well.");
636             builder.info("Warning: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
637             builder.ensure(RustcLink::from_rustc(self, compiler));
638             return;
639         }
640
641         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
642         if compiler_to_use != compiler {
643             builder.ensure(Rustc::new(compiler_to_use, target));
644             builder
645                 .info(&format!("Uplifting stage1 rustc ({} -> {})", builder.config.build, target));
646             builder.ensure(RustcLink::from_rustc(self, compiler_to_use));
647             return;
648         }
649
650         // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
651         builder.ensure(Std::new(
652             builder.compiler(self.compiler.stage, builder.config.build),
653             builder.config.build,
654         ));
655
656         let mut cargo = builder.cargo(compiler, Mode::Rustc, SourceType::InTree, target, "build");
657         rustc_cargo(builder, &mut cargo, target);
658
659         if builder.config.rust_profile_use.is_some()
660             && builder.config.rust_profile_generate.is_some()
661         {
662             panic!("Cannot use and generate PGO profiles at the same time");
663         }
664
665         // With LLD, we can use ICF (identical code folding) to reduce the executable size
666         // of librustc_driver/rustc and to improve i-cache utilization.
667         //
668         // -Wl,[link options] doesn't work on MSVC. However, /OPT:ICF (technically /OPT:REF,ICF)
669         // is already on by default in MSVC optimized builds, which is interpreted as --icf=all:
670         // https://github.com/llvm/llvm-project/blob/3329cec2f79185bafd678f310fafadba2a8c76d2/lld/COFF/Driver.cpp#L1746
671         // https://github.com/rust-lang/rust/blob/f22819bcce4abaff7d1246a56eec493418f9f4ee/compiler/rustc_codegen_ssa/src/back/linker.rs#L827
672         if builder.config.use_lld && !compiler.host.contains("msvc") {
673             cargo.rustflag("-Clink-args=-Wl,--icf=all");
674         }
675
676         let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
677             if compiler.stage == 1 {
678                 cargo.rustflag(&format!("-Cprofile-generate={}", path));
679                 // Apparently necessary to avoid overflowing the counters during
680                 // a Cargo build profile
681                 cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
682                 true
683             } else {
684                 false
685             }
686         } else if let Some(path) = &builder.config.rust_profile_use {
687             if compiler.stage == 1 {
688                 cargo.rustflag(&format!("-Cprofile-use={}", path));
689                 cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
690                 true
691             } else {
692                 false
693             }
694         } else {
695             false
696         };
697         if is_collecting {
698             // Ensure paths to Rust sources are relative, not absolute.
699             cargo.rustflag(&format!(
700                 "-Cllvm-args=-static-func-strip-dirname-prefix={}",
701                 builder.config.src.components().count()
702             ));
703         }
704
705         // We currently don't support cross-crate LTO in stage0. This also isn't hugely necessary
706         // and may just be a time sink.
707         if compiler.stage != 0 {
708             match builder.config.rust_lto {
709                 RustcLto::Thin | RustcLto::Fat => {
710                     // Since using LTO for optimizing dylibs is currently experimental,
711                     // we need to pass -Zdylib-lto.
712                     cargo.rustflag("-Zdylib-lto");
713                     // Cargo by default passes `-Cembed-bitcode=no` and doesn't pass `-Clto` when
714                     // compiling dylibs (and their dependencies), even when LTO is enabled for the
715                     // crate. Therefore, we need to override `-Clto` and `-Cembed-bitcode` here.
716                     let lto_type = match builder.config.rust_lto {
717                         RustcLto::Thin => "thin",
718                         RustcLto::Fat => "fat",
719                         _ => unreachable!(),
720                     };
721                     cargo.rustflag(&format!("-Clto={}", lto_type));
722                     cargo.rustflag("-Cembed-bitcode=yes");
723                 }
724                 RustcLto::ThinLocal => { /* Do nothing, this is the default */ }
725             }
726         }
727
728         for krate in &*self.crates {
729             cargo.arg("-p").arg(krate);
730         }
731
732         builder.info(&format!(
733             "Building{} stage{} compiler artifacts ({} -> {})",
734             crate_description(&self.crates),
735             compiler.stage,
736             &compiler.host,
737             target,
738         ));
739         run_cargo(
740             builder,
741             cargo,
742             vec![],
743             &librustc_stamp(builder, compiler, target),
744             vec![],
745             false,
746             true, // Only ship rustc_driver.so and .rmeta files, not all intermediate .rlib files.
747         );
748
749         builder.ensure(RustcLink::from_rustc(
750             self,
751             builder.compiler(compiler.stage, builder.config.build),
752         ));
753     }
754 }
755
756 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
757     cargo
758         .arg("--features")
759         .arg(builder.rustc_features(builder.kind))
760         .arg("--manifest-path")
761         .arg(builder.src.join("compiler/rustc/Cargo.toml"));
762     rustc_cargo_env(builder, cargo, target);
763 }
764
765 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
766     // Set some configuration variables picked up by build scripts and
767     // the compiler alike
768     cargo
769         .env("CFG_RELEASE", builder.rust_release())
770         .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
771         .env("CFG_VERSION", builder.rust_version());
772
773     if let Some(backend) = builder.config.default_codegen_backend() {
774         cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", backend);
775     }
776
777     let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
778     let target_config = builder.config.target_config.get(&target);
779
780     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
781
782     if let Some(ref ver_date) = builder.rust_info().commit_date() {
783         cargo.env("CFG_VER_DATE", ver_date);
784     }
785     if let Some(ref ver_hash) = builder.rust_info().sha() {
786         cargo.env("CFG_VER_HASH", ver_hash);
787     }
788     if !builder.unstable_features() {
789         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
790     }
791
792     // Prefer the current target's own default_linker, else a globally
793     // specified one.
794     if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
795         cargo.env("CFG_DEFAULT_LINKER", s);
796     } else if let Some(ref s) = builder.config.rustc_default_linker {
797         cargo.env("CFG_DEFAULT_LINKER", s);
798     }
799
800     if builder.config.rustc_parallel {
801         // keep in sync with `bootstrap/lib.rs:Build::rustc_features`
802         // `cfg` option for rustc, `features` option for cargo, for conditional compilation
803         cargo.rustflag("--cfg=parallel_compiler");
804         cargo.rustdocflag("--cfg=parallel_compiler");
805     }
806     if builder.config.rust_verify_llvm_ir {
807         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
808     }
809
810     // Pass down configuration from the LLVM build into the build of
811     // rustc_llvm and rustc_codegen_llvm.
812     //
813     // Note that this is disabled if LLVM itself is disabled or we're in a check
814     // build. If we are in a check build we still go ahead here presuming we've
815     // detected that LLVM is already built and good to go which helps prevent
816     // busting caches (e.g. like #71152).
817     if builder.config.llvm_enabled()
818         && (builder.kind != Kind::Check
819             || crate::native::prebuilt_llvm_config(builder, target).is_ok())
820     {
821         if builder.is_rust_llvm(target) {
822             cargo.env("LLVM_RUSTLLVM", "1");
823         }
824         let native::LlvmResult { llvm_config, .. } = builder.ensure(native::Llvm { target });
825         cargo.env("LLVM_CONFIG", &llvm_config);
826         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
827             cargo.env("CFG_LLVM_ROOT", s);
828         }
829
830         // Some LLVM linker flags (-L and -l) may be needed to link `rustc_llvm`. Its build script
831         // expects these to be passed via the `LLVM_LINKER_FLAGS` env variable, separated by
832         // whitespace.
833         //
834         // For example:
835         // - on windows, when `clang-cl` is used with instrumentation, we need to manually add
836         // clang's runtime library resource directory so that the profiler runtime library can be
837         // found. This is to avoid the linker errors about undefined references to
838         // `__llvm_profile_instrument_memop` when linking `rustc_driver`.
839         let mut llvm_linker_flags = String::new();
840         if builder.config.llvm_profile_generate && target.contains("msvc") {
841             if let Some(ref clang_cl_path) = builder.config.llvm_clang_cl {
842                 // Add clang's runtime library directory to the search path
843                 let clang_rt_dir = get_clang_cl_resource_dir(clang_cl_path);
844                 llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
845             }
846         }
847
848         // The config can also specify its own llvm linker flags.
849         if let Some(ref s) = builder.config.llvm_ldflags {
850             if !llvm_linker_flags.is_empty() {
851                 llvm_linker_flags.push_str(" ");
852             }
853             llvm_linker_flags.push_str(s);
854         }
855
856         // Set the linker flags via the env var that `rustc_llvm`'s build script will read.
857         if !llvm_linker_flags.is_empty() {
858             cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
859         }
860
861         // Building with a static libstdc++ is only supported on linux right now,
862         // not for MSVC or macOS
863         if builder.config.llvm_static_stdcpp
864             && !target.contains("freebsd")
865             && !target.contains("msvc")
866             && !target.contains("apple")
867             && !target.contains("solaris")
868         {
869             let file = compiler_file(
870                 builder,
871                 builder.cxx(target).unwrap(),
872                 target,
873                 CLang::Cxx,
874                 "libstdc++.a",
875             );
876             cargo.env("LLVM_STATIC_STDCPP", file);
877         }
878         if builder.llvm_link_shared() {
879             cargo.env("LLVM_LINK_SHARED", "1");
880         }
881         if builder.config.llvm_use_libcxx {
882             cargo.env("LLVM_USE_LIBCXX", "1");
883         }
884         if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
885             cargo.env("LLVM_NDEBUG", "1");
886         }
887     }
888 }
889
890 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
891 struct RustcLink {
892     pub compiler: Compiler,
893     pub target_compiler: Compiler,
894     pub target: TargetSelection,
895     /// Not actually used; only present to make sure the cache invalidation is correct.
896     crates: Interned<Vec<String>>,
897 }
898
899 impl RustcLink {
900     fn from_rustc(rustc: Rustc, host_compiler: Compiler) -> Self {
901         Self {
902             compiler: host_compiler,
903             target_compiler: rustc.compiler,
904             target: rustc.target,
905             crates: rustc.crates,
906         }
907     }
908 }
909
910 impl Step for RustcLink {
911     type Output = ();
912
913     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
914         run.never()
915     }
916
917     /// Same as `std_link`, only for librustc
918     fn run(self, builder: &Builder<'_>) {
919         let compiler = self.compiler;
920         let target_compiler = self.target_compiler;
921         let target = self.target;
922         builder.info(&format!(
923             "Copying stage{} rustc from stage{} ({} -> {} / {})",
924             target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
925         ));
926         add_to_sysroot(
927             builder,
928             &builder.sysroot_libdir(target_compiler, target),
929             &builder.sysroot_libdir(target_compiler, compiler.host),
930             &librustc_stamp(builder, compiler, target),
931         );
932     }
933 }
934
935 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
936 pub struct CodegenBackend {
937     pub target: TargetSelection,
938     pub compiler: Compiler,
939     pub backend: Interned<String>,
940 }
941
942 impl Step for CodegenBackend {
943     type Output = ();
944     const ONLY_HOSTS: bool = true;
945     // Only the backends specified in the `codegen-backends` entry of `config.toml` are built.
946     const DEFAULT: bool = true;
947
948     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
949         run.paths(&["compiler/rustc_codegen_cranelift", "compiler/rustc_codegen_gcc"])
950     }
951
952     fn make_run(run: RunConfig<'_>) {
953         for &backend in &run.builder.config.rust_codegen_backends {
954             if backend == "llvm" {
955                 continue; // Already built as part of rustc
956             }
957
958             run.builder.ensure(CodegenBackend {
959                 target: run.target,
960                 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
961                 backend,
962             });
963         }
964     }
965
966     fn run(self, builder: &Builder<'_>) {
967         let compiler = self.compiler;
968         let target = self.target;
969         let backend = self.backend;
970
971         builder.ensure(Rustc::new(compiler, target));
972
973         if builder.config.keep_stage.contains(&compiler.stage) {
974             builder.info(
975                 "Warning: Using a potentially old codegen backend. \
976                 This may not behave well.",
977             );
978             // Codegen backends are linked separately from this step today, so we don't do
979             // anything here.
980             return;
981         }
982
983         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
984         if compiler_to_use != compiler {
985             builder.ensure(CodegenBackend { compiler: compiler_to_use, target, backend });
986             return;
987         }
988
989         let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
990
991         let mut cargo = builder.cargo(compiler, Mode::Codegen, SourceType::InTree, target, "build");
992         cargo
993             .arg("--manifest-path")
994             .arg(builder.src.join(format!("compiler/rustc_codegen_{}/Cargo.toml", backend)));
995         rustc_cargo_env(builder, &mut cargo, target);
996
997         let tmp_stamp = out_dir.join(".tmp.stamp");
998
999         builder.info(&format!(
1000             "Building stage{} codegen backend {} ({} -> {})",
1001             compiler.stage, backend, &compiler.host, target
1002         ));
1003         let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false, false);
1004         if builder.config.dry_run() {
1005             return;
1006         }
1007         let mut files = files.into_iter().filter(|f| {
1008             let filename = f.file_name().unwrap().to_str().unwrap();
1009             is_dylib(filename) && filename.contains("rustc_codegen_")
1010         });
1011         let codegen_backend = match files.next() {
1012             Some(f) => f,
1013             None => panic!("no dylibs built for codegen backend?"),
1014         };
1015         if let Some(f) = files.next() {
1016             panic!(
1017                 "codegen backend built two dylibs:\n{}\n{}",
1018                 codegen_backend.display(),
1019                 f.display()
1020             );
1021         }
1022         let stamp = codegen_backend_stamp(builder, compiler, target, backend);
1023         let codegen_backend = codegen_backend.to_str().unwrap();
1024         t!(fs::write(&stamp, &codegen_backend));
1025     }
1026 }
1027
1028 /// Creates the `codegen-backends` folder for a compiler that's about to be
1029 /// assembled as a complete compiler.
1030 ///
1031 /// This will take the codegen artifacts produced by `compiler` and link them
1032 /// into an appropriate location for `target_compiler` to be a functional
1033 /// compiler.
1034 fn copy_codegen_backends_to_sysroot(
1035     builder: &Builder<'_>,
1036     compiler: Compiler,
1037     target_compiler: Compiler,
1038 ) {
1039     let target = target_compiler.host;
1040
1041     // Note that this step is different than all the other `*Link` steps in
1042     // that it's not assembling a bunch of libraries but rather is primarily
1043     // moving the codegen backend into place. The codegen backend of rustc is
1044     // not linked into the main compiler by default but is rather dynamically
1045     // selected at runtime for inclusion.
1046     //
1047     // Here we're looking for the output dylib of the `CodegenBackend` step and
1048     // we're copying that into the `codegen-backends` folder.
1049     let dst = builder.sysroot_codegen_backends(target_compiler);
1050     t!(fs::create_dir_all(&dst), dst);
1051
1052     if builder.config.dry_run() {
1053         return;
1054     }
1055
1056     for backend in builder.config.rust_codegen_backends.iter() {
1057         if backend == "llvm" {
1058             continue; // Already built as part of rustc
1059         }
1060
1061         let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
1062         let dylib = t!(fs::read_to_string(&stamp));
1063         let file = Path::new(&dylib);
1064         let filename = file.file_name().unwrap().to_str().unwrap();
1065         // change `librustc_codegen_cranelift-xxxxxx.so` to
1066         // `librustc_codegen_cranelift-release.so`
1067         let target_filename = {
1068             let dash = filename.find('-').unwrap();
1069             let dot = filename.find('.').unwrap();
1070             format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1071         };
1072         builder.copy(&file, &dst.join(target_filename));
1073     }
1074 }
1075
1076 /// Cargo's output path for the standard library in a given stage, compiled
1077 /// by a particular compiler for the specified target.
1078 pub fn libstd_stamp(builder: &Builder<'_>, compiler: Compiler, target: TargetSelection) -> PathBuf {
1079     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
1080 }
1081
1082 /// Cargo's output path for librustc in a given stage, compiled by a particular
1083 /// compiler for the specified target.
1084 pub fn librustc_stamp(
1085     builder: &Builder<'_>,
1086     compiler: Compiler,
1087     target: TargetSelection,
1088 ) -> PathBuf {
1089     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
1090 }
1091
1092 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
1093 /// compiler for the specified target and backend.
1094 fn codegen_backend_stamp(
1095     builder: &Builder<'_>,
1096     compiler: Compiler,
1097     target: TargetSelection,
1098     backend: Interned<String>,
1099 ) -> PathBuf {
1100     builder
1101         .cargo_out(compiler, Mode::Codegen, target)
1102         .join(format!(".librustc_codegen_{}.stamp", backend))
1103 }
1104
1105 pub fn compiler_file(
1106     builder: &Builder<'_>,
1107     compiler: &Path,
1108     target: TargetSelection,
1109     c: CLang,
1110     file: &str,
1111 ) -> PathBuf {
1112     let mut cmd = Command::new(compiler);
1113     cmd.args(builder.cflags(target, GitRepo::Rustc, c));
1114     cmd.arg(format!("-print-file-name={}", file));
1115     let out = output(&mut cmd);
1116     PathBuf::from(out.trim())
1117 }
1118
1119 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1120 pub struct Sysroot {
1121     pub compiler: Compiler,
1122 }
1123
1124 impl Step for Sysroot {
1125     type Output = Interned<PathBuf>;
1126
1127     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1128         run.never()
1129     }
1130
1131     /// Returns the sysroot for the `compiler` specified that *this build system
1132     /// generates*.
1133     ///
1134     /// That is, the sysroot for the stage0 compiler is not what the compiler
1135     /// thinks it is by default, but it's the same as the default for stages
1136     /// 1-3.
1137     fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
1138         let compiler = self.compiler;
1139         let host_dir = builder.out.join(&compiler.host.triple);
1140
1141         let sysroot_dir = |stage| {
1142             if stage == 0 {
1143                 host_dir.join("stage0-sysroot")
1144             } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1145                 host_dir.join("ci-rustc-sysroot")
1146             } else {
1147                 host_dir.join(format!("stage{}", stage))
1148             }
1149         };
1150         let sysroot = sysroot_dir(compiler.stage);
1151
1152         let _ = fs::remove_dir_all(&sysroot);
1153         t!(fs::create_dir_all(&sysroot));
1154
1155         // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0.
1156         if builder.download_rustc() && compiler.stage != 0 {
1157             assert_eq!(
1158                 builder.config.build, compiler.host,
1159                 "Cross-compiling is not yet supported with `download-rustc`",
1160             );
1161
1162             // #102002, cleanup old toolchain folders when using download-rustc so people don't use them by accident.
1163             for stage in 0..=2 {
1164                 if stage != compiler.stage {
1165                     let dir = sysroot_dir(stage);
1166                     if !dir.ends_with("ci-rustc-sysroot") {
1167                         let _ = fs::remove_dir_all(dir);
1168                     }
1169                 }
1170             }
1171
1172             // Copy the compiler into the correct sysroot.
1173             let ci_rustc_dir =
1174                 builder.config.out.join(&*builder.config.build.triple).join("ci-rustc");
1175             builder.cp_r(&ci_rustc_dir, &sysroot);
1176             return INTERNER.intern_path(sysroot);
1177         }
1178
1179         // Symlink the source root into the same location inside the sysroot,
1180         // where `rust-src` component would go (`$sysroot/lib/rustlib/src/rust`),
1181         // so that any tools relying on `rust-src` also work for local builds,
1182         // and also for translating the virtual `/rustc/$hash` back to the real
1183         // directory (for running tests with `rust.remap-debuginfo = true`).
1184         let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
1185         t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
1186         let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
1187         if let Err(e) = symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust) {
1188             eprintln!(
1189                 "warning: creating symbolic link `{}` to `{}` failed with {}",
1190                 sysroot_lib_rustlib_src_rust.display(),
1191                 builder.src.display(),
1192                 e,
1193             );
1194             if builder.config.rust_remap_debuginfo {
1195                 eprintln!(
1196                     "warning: some `tests/ui` tests will fail when lacking `{}`",
1197                     sysroot_lib_rustlib_src_rust.display(),
1198                 );
1199             }
1200         }
1201         // Same for the rustc-src component.
1202         let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
1203         t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
1204         let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
1205         if let Err(e) =
1206             symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
1207         {
1208             eprintln!(
1209                 "warning: creating symbolic link `{}` to `{}` failed with {}",
1210                 sysroot_lib_rustlib_rustcsrc_rust.display(),
1211                 builder.src.display(),
1212                 e,
1213             );
1214         }
1215
1216         INTERNER.intern_path(sysroot)
1217     }
1218 }
1219
1220 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
1221 pub struct Assemble {
1222     /// The compiler which we will produce in this step. Assemble itself will
1223     /// take care of ensuring that the necessary prerequisites to do so exist,
1224     /// that is, this target can be a stage2 compiler and Assemble will build
1225     /// previous stages for you.
1226     pub target_compiler: Compiler,
1227 }
1228
1229 impl Step for Assemble {
1230     type Output = Compiler;
1231     const ONLY_HOSTS: bool = true;
1232
1233     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1234         run.path("compiler/rustc").path("compiler")
1235     }
1236
1237     fn make_run(run: RunConfig<'_>) {
1238         run.builder.ensure(Assemble {
1239             target_compiler: run.builder.compiler(run.builder.top_stage + 1, run.target),
1240         });
1241     }
1242
1243     /// Prepare a new compiler from the artifacts in `stage`
1244     ///
1245     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
1246     /// must have been previously produced by the `stage - 1` builder.build
1247     /// compiler.
1248     fn run(self, builder: &Builder<'_>) -> Compiler {
1249         let target_compiler = self.target_compiler;
1250
1251         if target_compiler.stage == 0 {
1252             assert_eq!(
1253                 builder.config.build, target_compiler.host,
1254                 "Cannot obtain compiler for non-native build triple at stage 0"
1255             );
1256             // The stage 0 compiler for the build triple is always pre-built.
1257             return target_compiler;
1258         }
1259
1260         // Get the compiler that we'll use to bootstrap ourselves.
1261         //
1262         // Note that this is where the recursive nature of the bootstrap
1263         // happens, as this will request the previous stage's compiler on
1264         // downwards to stage 0.
1265         //
1266         // Also note that we're building a compiler for the host platform. We
1267         // only assume that we can run `build` artifacts, which means that to
1268         // produce some other architecture compiler we need to start from
1269         // `build` to get there.
1270         //
1271         // FIXME: It may be faster if we build just a stage 1 compiler and then
1272         //        use that to bootstrap this compiler forward.
1273         let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
1274
1275         // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0.
1276         if builder.download_rustc() {
1277             builder.ensure(Sysroot { compiler: target_compiler });
1278             return target_compiler;
1279         }
1280
1281         // Build the libraries for this compiler to link to (i.e., the libraries
1282         // it uses at runtime). NOTE: Crates the target compiler compiles don't
1283         // link to these. (FIXME: Is that correct? It seems to be correct most
1284         // of the time but I think we do link to these for stage2/bin compilers
1285         // when not performing a full bootstrap).
1286         builder.ensure(Rustc::new(build_compiler, target_compiler.host));
1287
1288         for &backend in builder.config.rust_codegen_backends.iter() {
1289             if backend == "llvm" {
1290                 continue; // Already built as part of rustc
1291             }
1292
1293             builder.ensure(CodegenBackend {
1294                 compiler: build_compiler,
1295                 target: target_compiler.host,
1296                 backend,
1297             });
1298         }
1299
1300         let lld_install = if builder.config.lld_enabled {
1301             Some(builder.ensure(native::Lld { target: target_compiler.host }))
1302         } else {
1303             None
1304         };
1305
1306         let stage = target_compiler.stage;
1307         let host = target_compiler.host;
1308         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
1309
1310         // Link in all dylibs to the libdir
1311         let stamp = librustc_stamp(builder, build_compiler, target_compiler.host);
1312         let proc_macros = builder
1313             .read_stamp_file(&stamp)
1314             .into_iter()
1315             .filter_map(|(path, dependency_type)| {
1316                 if dependency_type == DependencyType::Host {
1317                     Some(path.file_name().unwrap().to_owned().into_string().unwrap())
1318                 } else {
1319                     None
1320                 }
1321             })
1322             .collect::<HashSet<_>>();
1323
1324         let sysroot = builder.sysroot(target_compiler);
1325         let rustc_libdir = builder.rustc_libdir(target_compiler);
1326         t!(fs::create_dir_all(&rustc_libdir));
1327         let src_libdir = builder.sysroot_libdir(build_compiler, host);
1328         for f in builder.read_dir(&src_libdir) {
1329             let filename = f.file_name().into_string().unwrap();
1330             if (is_dylib(&filename) || is_debug_info(&filename)) && !proc_macros.contains(&filename)
1331             {
1332                 builder.copy(&f.path(), &rustc_libdir.join(&filename));
1333             }
1334         }
1335
1336         copy_codegen_backends_to_sysroot(builder, build_compiler, target_compiler);
1337
1338         // We prepend this bin directory to the user PATH when linking Rust binaries. To
1339         // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
1340         let libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
1341         let libdir_bin = libdir.parent().unwrap().join("bin");
1342         t!(fs::create_dir_all(&libdir_bin));
1343         if let Some(lld_install) = lld_install {
1344             let src_exe = exe("lld", target_compiler.host);
1345             let dst_exe = exe("rust-lld", target_compiler.host);
1346             builder.copy(&lld_install.join("bin").join(&src_exe), &libdir_bin.join(&dst_exe));
1347             // for `-Z gcc-ld=lld`
1348             let gcc_ld_dir = libdir_bin.join("gcc-ld");
1349             t!(fs::create_dir(&gcc_ld_dir));
1350             let lld_wrapper_exe = builder.ensure(crate::tool::LldWrapper {
1351                 compiler: build_compiler,
1352                 target: target_compiler.host,
1353             });
1354             for name in crate::LLD_FILE_NAMES {
1355                 builder.copy(&lld_wrapper_exe, &gcc_ld_dir.join(exe(name, target_compiler.host)));
1356             }
1357         }
1358
1359         if builder.config.rust_codegen_backends.contains(&INTERNER.intern_str("llvm")) {
1360             let native::LlvmResult { llvm_config, .. } =
1361                 builder.ensure(native::Llvm { target: target_compiler.host });
1362             if !builder.config.dry_run() {
1363                 let llvm_bin_dir = output(Command::new(llvm_config).arg("--bindir"));
1364                 let llvm_bin_dir = Path::new(llvm_bin_dir.trim());
1365
1366                 // Since we've already built the LLVM tools, install them to the sysroot.
1367                 // This is the equivalent of installing the `llvm-tools-preview` component via
1368                 // rustup, and lets developers use a locally built toolchain to
1369                 // build projects that expect llvm tools to be present in the sysroot
1370                 // (e.g. the `bootimage` crate).
1371                 for tool in LLVM_TOOLS {
1372                     let tool_exe = exe(tool, target_compiler.host);
1373                     let src_path = llvm_bin_dir.join(&tool_exe);
1374                     // When using `download-ci-llvm`, some of the tools
1375                     // may not exist, so skip trying to copy them.
1376                     if src_path.exists() {
1377                         builder.copy(&src_path, &libdir_bin.join(&tool_exe));
1378                     }
1379                 }
1380             }
1381         }
1382
1383         // Ensure that `libLLVM.so` ends up in the newly build compiler directory,
1384         // so that it can be found when the newly built `rustc` is run.
1385         dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
1386         dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
1387
1388         // Link the compiler binary itself into place
1389         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
1390         let rustc = out_dir.join(exe("rustc-main", host));
1391         let bindir = sysroot.join("bin");
1392         t!(fs::create_dir_all(&bindir));
1393         let compiler = builder.rustc(target_compiler);
1394         builder.copy(&rustc, &compiler);
1395
1396         target_compiler
1397     }
1398 }
1399
1400 /// Link some files into a rustc sysroot.
1401 ///
1402 /// For a particular stage this will link the file listed in `stamp` into the
1403 /// `sysroot_dst` provided.
1404 pub fn add_to_sysroot(
1405     builder: &Builder<'_>,
1406     sysroot_dst: &Path,
1407     sysroot_host_dst: &Path,
1408     stamp: &Path,
1409 ) {
1410     let self_contained_dst = &sysroot_dst.join("self-contained");
1411     t!(fs::create_dir_all(&sysroot_dst));
1412     t!(fs::create_dir_all(&sysroot_host_dst));
1413     t!(fs::create_dir_all(&self_contained_dst));
1414     for (path, dependency_type) in builder.read_stamp_file(stamp) {
1415         let dst = match dependency_type {
1416             DependencyType::Host => sysroot_host_dst,
1417             DependencyType::Target => sysroot_dst,
1418             DependencyType::TargetSelfContained => self_contained_dst,
1419         };
1420         builder.copy(&path, &dst.join(path.file_name().unwrap()));
1421     }
1422 }
1423
1424 pub fn run_cargo(
1425     builder: &Builder<'_>,
1426     cargo: Cargo,
1427     tail_args: Vec<String>,
1428     stamp: &Path,
1429     additional_target_deps: Vec<(PathBuf, DependencyType)>,
1430     is_check: bool,
1431     rlib_only_metadata: bool,
1432 ) -> Vec<PathBuf> {
1433     if builder.config.dry_run() {
1434         return Vec::new();
1435     }
1436
1437     // `target_root_dir` looks like $dir/$target/release
1438     let target_root_dir = stamp.parent().unwrap();
1439     // `target_deps_dir` looks like $dir/$target/release/deps
1440     let target_deps_dir = target_root_dir.join("deps");
1441     // `host_root_dir` looks like $dir/release
1442     let host_root_dir = target_root_dir
1443         .parent()
1444         .unwrap() // chop off `release`
1445         .parent()
1446         .unwrap() // chop off `$target`
1447         .join(target_root_dir.file_name().unwrap());
1448
1449     // Spawn Cargo slurping up its JSON output. We'll start building up the
1450     // `deps` array of all files it generated along with a `toplevel` array of
1451     // files we need to probe for later.
1452     let mut deps = Vec::new();
1453     let mut toplevel = Vec::new();
1454     let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
1455         let (filenames, crate_types) = match msg {
1456             CargoMessage::CompilerArtifact {
1457                 filenames,
1458                 target: CargoTarget { crate_types },
1459                 ..
1460             } => (filenames, crate_types),
1461             _ => return,
1462         };
1463         for filename in filenames {
1464             // Skip files like executables
1465             let mut keep = false;
1466             if filename.ends_with(".lib")
1467                 || filename.ends_with(".a")
1468                 || is_debug_info(&filename)
1469                 || is_dylib(&filename)
1470             {
1471                 // Always keep native libraries, rust dylibs and debuginfo
1472                 keep = true;
1473             }
1474             if is_check && filename.ends_with(".rmeta") {
1475                 // During check builds we need to keep crate metadata
1476                 keep = true;
1477             } else if rlib_only_metadata {
1478                 if filename.contains("jemalloc_sys") || filename.contains("rustc_smir") {
1479                     // jemalloc_sys and rustc_smir are not linked into librustc_driver.so,
1480                     // so we need to distribute them as rlib to be able to use them.
1481                     keep |= filename.ends_with(".rlib");
1482                 } else {
1483                     // Distribute the rest of the rustc crates as rmeta files only to reduce
1484                     // the tarball sizes by about 50%. The object files are linked into
1485                     // librustc_driver.so, so it is still possible to link against them.
1486                     keep |= filename.ends_with(".rmeta");
1487                 }
1488             } else {
1489                 // In all other cases keep all rlibs
1490                 keep |= filename.ends_with(".rlib");
1491             }
1492
1493             if !keep {
1494                 continue;
1495             }
1496
1497             let filename = Path::new(&*filename);
1498
1499             // If this was an output file in the "host dir" we don't actually
1500             // worry about it, it's not relevant for us
1501             if filename.starts_with(&host_root_dir) {
1502                 // Unless it's a proc macro used in the compiler
1503                 if crate_types.iter().any(|t| t == "proc-macro") {
1504                     deps.push((filename.to_path_buf(), DependencyType::Host));
1505                 }
1506                 continue;
1507             }
1508
1509             // If this was output in the `deps` dir then this is a precise file
1510             // name (hash included) so we start tracking it.
1511             if filename.starts_with(&target_deps_dir) {
1512                 deps.push((filename.to_path_buf(), DependencyType::Target));
1513                 continue;
1514             }
1515
1516             // Otherwise this was a "top level artifact" which right now doesn't
1517             // have a hash in the name, but there's a version of this file in
1518             // the `deps` folder which *does* have a hash in the name. That's
1519             // the one we'll want to we'll probe for it later.
1520             //
1521             // We do not use `Path::file_stem` or `Path::extension` here,
1522             // because some generated files may have multiple extensions e.g.
1523             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1524             // split the file name by the last extension (`.lib`) while we need
1525             // to split by all extensions (`.dll.lib`).
1526             let expected_len = t!(filename.metadata()).len();
1527             let filename = filename.file_name().unwrap().to_str().unwrap();
1528             let mut parts = filename.splitn(2, '.');
1529             let file_stem = parts.next().unwrap().to_owned();
1530             let extension = parts.next().unwrap().to_owned();
1531
1532             toplevel.push((file_stem, extension, expected_len));
1533         }
1534     });
1535
1536     if !ok {
1537         crate::detail_exit(1);
1538     }
1539
1540     // Ok now we need to actually find all the files listed in `toplevel`. We've
1541     // got a list of prefix/extensions and we basically just need to find the
1542     // most recent file in the `deps` folder corresponding to each one.
1543     let contents = t!(target_deps_dir.read_dir())
1544         .map(|e| t!(e))
1545         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1546         .collect::<Vec<_>>();
1547     for (prefix, extension, expected_len) in toplevel {
1548         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1549             meta.len() == expected_len
1550                 && filename
1551                     .strip_prefix(&prefix[..])
1552                     .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
1553                     .unwrap_or(false)
1554         });
1555         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1556             metadata.modified().expect("mtime should be available on all relevant OSes")
1557         });
1558         let path_to_add = match max {
1559             Some(triple) => triple.0.to_str().unwrap(),
1560             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1561         };
1562         if is_dylib(path_to_add) {
1563             let candidate = format!("{}.lib", path_to_add);
1564             let candidate = PathBuf::from(candidate);
1565             if candidate.exists() {
1566                 deps.push((candidate, DependencyType::Target));
1567             }
1568         }
1569         deps.push((path_to_add.into(), DependencyType::Target));
1570     }
1571
1572     deps.extend(additional_target_deps);
1573     deps.sort();
1574     let mut new_contents = Vec::new();
1575     for (dep, dependency_type) in deps.iter() {
1576         new_contents.extend(match *dependency_type {
1577             DependencyType::Host => b"h",
1578             DependencyType::Target => b"t",
1579             DependencyType::TargetSelfContained => b"s",
1580         });
1581         new_contents.extend(dep.to_str().unwrap().as_bytes());
1582         new_contents.extend(b"\0");
1583     }
1584     t!(fs::write(&stamp, &new_contents));
1585     deps.into_iter().map(|(d, _)| d).collect()
1586 }
1587
1588 pub fn stream_cargo(
1589     builder: &Builder<'_>,
1590     cargo: Cargo,
1591     tail_args: Vec<String>,
1592     cb: &mut dyn FnMut(CargoMessage<'_>),
1593 ) -> bool {
1594     let mut cargo = Command::from(cargo);
1595     if builder.config.dry_run() {
1596         return true;
1597     }
1598     // Instruct Cargo to give us json messages on stdout, critically leaving
1599     // stderr as piped so we can get those pretty colors.
1600     let mut message_format = if builder.config.json_output {
1601         String::from("json")
1602     } else {
1603         String::from("json-render-diagnostics")
1604     };
1605     if let Some(s) = &builder.config.rustc_error_format {
1606         message_format.push_str(",json-diagnostic-");
1607         message_format.push_str(s);
1608     }
1609     cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
1610
1611     for arg in tail_args {
1612         cargo.arg(arg);
1613     }
1614
1615     builder.verbose(&format!("running: {:?}", cargo));
1616     let mut child = match cargo.spawn() {
1617         Ok(child) => child,
1618         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1619     };
1620
1621     // Spawn Cargo slurping up its JSON output. We'll start building up the
1622     // `deps` array of all files it generated along with a `toplevel` array of
1623     // files we need to probe for later.
1624     let stdout = BufReader::new(child.stdout.take().unwrap());
1625     for line in stdout.lines() {
1626         let line = t!(line);
1627         match serde_json::from_str::<CargoMessage<'_>>(&line) {
1628             Ok(msg) => {
1629                 if builder.config.json_output {
1630                     // Forward JSON to stdout.
1631                     println!("{}", line);
1632                 }
1633                 cb(msg)
1634             }
1635             // If this was informational, just print it out and continue
1636             Err(_) => println!("{}", line),
1637         }
1638     }
1639
1640     // Make sure Cargo actually succeeded after we read all of its stdout.
1641     let status = t!(child.wait());
1642     if builder.is_verbose() && !status.success() {
1643         eprintln!(
1644             "command did not execute successfully: {:?}\n\
1645                   expected success, got: {}",
1646             cargo, status
1647         );
1648     }
1649     status.success()
1650 }
1651
1652 #[derive(Deserialize)]
1653 pub struct CargoTarget<'a> {
1654     crate_types: Vec<Cow<'a, str>>,
1655 }
1656
1657 #[derive(Deserialize)]
1658 #[serde(tag = "reason", rename_all = "kebab-case")]
1659 pub enum CargoMessage<'a> {
1660     CompilerArtifact {
1661         package_id: Cow<'a, str>,
1662         features: Vec<Cow<'a, str>>,
1663         filenames: Vec<Cow<'a, str>>,
1664         target: CargoTarget<'a>,
1665     },
1666     BuildScriptExecuted {
1667         package_id: Cow<'a, str>,
1668     },
1669     BuildFinished {
1670         success: bool,
1671     },
1672 }