]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Rollup merge of #73261 - estebank:generics-sized, r=nikomatsakis
[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 compiler the standard library, libtest, and
6 //! 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::env;
11 use std::fs;
12 use std::io::prelude::*;
13 use std::io::BufReader;
14 use std::path::{Path, PathBuf};
15 use std::process::{exit, Command, Stdio};
16 use std::str;
17
18 use build_helper::{output, t, up_to_date};
19 use filetime::FileTime;
20 use serde::Deserialize;
21
22 use crate::builder::Cargo;
23 use crate::dist;
24 use crate::native;
25 use crate::util::{exe, is_dylib, symlink_dir};
26 use crate::{Compiler, DependencyType, GitRepo, Mode};
27
28 use crate::builder::{Builder, Kind, RunConfig, ShouldRun, Step};
29 use crate::cache::{Interned, INTERNER};
30
31 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
32 pub struct Std {
33     pub target: Interned<String>,
34     pub compiler: Compiler,
35 }
36
37 impl Step for Std {
38     type Output = ();
39     const DEFAULT: bool = true;
40
41     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
42         run.all_krates("test")
43     }
44
45     fn make_run(run: RunConfig<'_>) {
46         run.builder.ensure(Std {
47             compiler: run.builder.compiler(run.builder.top_stage, run.host),
48             target: run.target,
49         });
50     }
51
52     /// Builds the standard library.
53     ///
54     /// This will build the standard library for a particular stage of the build
55     /// using the `compiler` targeting the `target` architecture. The artifacts
56     /// created will also be linked into the sysroot directory.
57     fn run(self, builder: &Builder<'_>) {
58         let target = self.target;
59         let compiler = self.compiler;
60
61         if builder.config.keep_stage.contains(&compiler.stage) {
62             builder.info("Warning: Using a potentially old libstd. This may not behave well.");
63             builder.ensure(StdLink { compiler, target_compiler: compiler, target });
64             return;
65         }
66
67         let mut target_deps = builder.ensure(StartupObjects { compiler, target });
68
69         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
70         if compiler_to_use != compiler {
71             builder.ensure(Std { compiler: compiler_to_use, target });
72             builder.info(&format!("Uplifting stage1 std ({} -> {})", compiler_to_use.host, target));
73
74             // Even if we're not building std this stage, the new sysroot must
75             // still contain the third party objects needed by various targets.
76             copy_third_party_objects(builder, &compiler, target);
77             copy_self_contained_objects(builder, &compiler, target);
78
79             builder.ensure(StdLink {
80                 compiler: compiler_to_use,
81                 target_compiler: compiler,
82                 target,
83             });
84             return;
85         }
86
87         target_deps.extend(copy_third_party_objects(builder, &compiler, target));
88         target_deps.extend(copy_self_contained_objects(builder, &compiler, target));
89
90         let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
91         std_cargo(builder, target, compiler.stage, &mut cargo);
92
93         builder.info(&format!(
94             "Building stage{} std artifacts ({} -> {})",
95             compiler.stage, &compiler.host, target
96         ));
97         run_cargo(
98             builder,
99             cargo,
100             vec![],
101             &libstd_stamp(builder, compiler, target),
102             target_deps,
103             false,
104         );
105
106         builder.ensure(StdLink {
107             compiler: builder.compiler(compiler.stage, builder.config.build),
108             target_compiler: compiler,
109             target,
110         });
111     }
112 }
113
114 fn copy_and_stamp(
115     builder: &Builder<'_>,
116     libdir: &Path,
117     sourcedir: &Path,
118     name: &str,
119     target_deps: &mut Vec<(PathBuf, DependencyType)>,
120     dependency_type: DependencyType,
121 ) {
122     let target = libdir.join(name);
123     builder.copy(&sourcedir.join(name), &target);
124
125     target_deps.push((target, dependency_type));
126 }
127
128 /// Copies third party objects needed by various targets.
129 fn copy_third_party_objects(
130     builder: &Builder<'_>,
131     compiler: &Compiler,
132     target: Interned<String>,
133 ) -> Vec<(PathBuf, DependencyType)> {
134     let libdir = builder.sysroot_libdir(*compiler, target);
135     let mut target_deps = vec![];
136
137     // Copies libunwind.a compiled to be linked with x86_64-fortanix-unknown-sgx.
138     //
139     // This target needs to be linked to Fortanix's port of llvm's libunwind.
140     // libunwind requires support for rwlock and printing to stderr,
141     // which is provided by std for this target.
142     if target == "x86_64-fortanix-unknown-sgx" {
143         let src_path_env = "X86_FORTANIX_SGX_LIBS";
144         let src =
145             env::var(src_path_env).unwrap_or_else(|_| panic!("{} not found in env", src_path_env));
146         copy_and_stamp(
147             builder,
148             &*libdir,
149             Path::new(&src),
150             "libunwind.a",
151             &mut target_deps,
152             DependencyType::Target,
153         );
154     }
155
156     if builder.config.sanitizers && compiler.stage != 0 {
157         // The sanitizers are only copied in stage1 or above,
158         // to avoid creating dependency on LLVM.
159         target_deps.extend(
160             copy_sanitizers(builder, &compiler, target)
161                 .into_iter()
162                 .map(|d| (d, DependencyType::Target)),
163         );
164     }
165
166     target_deps
167 }
168
169 /// Copies third party objects needed by various targets for self-contained linkage.
170 fn copy_self_contained_objects(
171     builder: &Builder<'_>,
172     compiler: &Compiler,
173     target: Interned<String>,
174 ) -> Vec<(PathBuf, DependencyType)> {
175     // cfg(bootstrap)
176     // Remove when upgrading bootstrap compiler.
177     let libdir_self_contained = if compiler.stage == 0 {
178         builder.sysroot_libdir(*compiler, target).to_path_buf()
179     } else {
180         builder.sysroot_libdir(*compiler, target).join("self-contained")
181     };
182     t!(fs::create_dir_all(&libdir_self_contained));
183     let mut target_deps = vec![];
184
185     // Copies the CRT objects.
186     //
187     // rustc historically provides a more self-contained installation for musl targets
188     // not requiring the presence of a native musl toolchain. For example, it can fall back
189     // to using gcc from a glibc-targeting toolchain for linking.
190     // To do that we have to distribute musl startup objects as a part of Rust toolchain
191     // and link with them manually in the self-contained mode.
192     if target.contains("musl") {
193         let srcdir = builder.musl_root(target).unwrap().join("lib");
194         for &obj in &["crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
195             copy_and_stamp(
196                 builder,
197                 &libdir_self_contained,
198                 &srcdir,
199                 obj,
200                 &mut target_deps,
201                 DependencyType::TargetSelfContained,
202             );
203         }
204     } else if target.ends_with("-wasi") {
205         let srcdir = builder.wasi_root(target).unwrap().join("lib/wasm32-wasi");
206         copy_and_stamp(
207             builder,
208             &libdir_self_contained,
209             &srcdir,
210             "crt1.o",
211             &mut target_deps,
212             DependencyType::TargetSelfContained,
213         );
214     } else if target.contains("windows-gnu") {
215         for obj in ["crt2.o", "dllcrt2.o"].iter() {
216             let src = compiler_file(builder, builder.cc(target), target, obj);
217             let target = libdir_self_contained.join(obj);
218             builder.copy(&src, &target);
219             target_deps.push((target, DependencyType::TargetSelfContained));
220         }
221     }
222
223     target_deps
224 }
225
226 /// Configure cargo to compile the standard library, adding appropriate env vars
227 /// and such.
228 pub fn std_cargo(builder: &Builder<'_>, target: Interned<String>, stage: u32, cargo: &mut Cargo) {
229     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
230         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
231     }
232
233     // Determine if we're going to compile in optimized C intrinsics to
234     // the `compiler-builtins` crate. These intrinsics live in LLVM's
235     // `compiler-rt` repository, but our `src/llvm-project` submodule isn't
236     // always checked out, so we need to conditionally look for this. (e.g. if
237     // an external LLVM is used we skip the LLVM submodule checkout).
238     //
239     // Note that this shouldn't affect the correctness of `compiler-builtins`,
240     // but only its speed. Some intrinsics in C haven't been translated to Rust
241     // yet but that's pretty rare. Other intrinsics have optimized
242     // implementations in C which have only had slower versions ported to Rust,
243     // so we favor the C version where we can, but it's not critical.
244     //
245     // If `compiler-rt` is available ensure that the `c` feature of the
246     // `compiler-builtins` crate is enabled and it's configured to learn where
247     // `compiler-rt` is located.
248     let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
249     let compiler_builtins_c_feature = if compiler_builtins_root.exists() {
250         // Note that `libprofiler_builtins/build.rs` also computes this so if
251         // you're changing something here please also change that.
252         cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
253         " compiler-builtins-c".to_string()
254     } else {
255         String::new()
256     };
257
258     if builder.no_std(target) == Some(true) {
259         let mut features = "compiler-builtins-mem".to_string();
260         features.push_str(&compiler_builtins_c_feature);
261
262         // for no-std targets we only compile a few no_std crates
263         cargo
264             .args(&["-p", "alloc"])
265             .arg("--manifest-path")
266             .arg(builder.src.join("src/liballoc/Cargo.toml"))
267             .arg("--features")
268             .arg("compiler-builtins-mem compiler-builtins-c");
269     } else {
270         let mut features = builder.std_features();
271         features.push_str(&compiler_builtins_c_feature);
272
273         cargo
274             .arg("--features")
275             .arg(features)
276             .arg("--manifest-path")
277             .arg(builder.src.join("src/libtest/Cargo.toml"));
278
279         // Help the libc crate compile by assisting it in finding various
280         // sysroot native libraries.
281         if target.contains("musl") {
282             if let Some(p) = builder.musl_root(target) {
283                 let root = format!("native={}/lib", p.to_str().unwrap());
284                 cargo.rustflag("-L").rustflag(&root);
285             }
286         }
287
288         if target.ends_with("-wasi") {
289             if let Some(p) = builder.wasi_root(target) {
290                 let root = format!("native={}/lib/wasm32-wasi", p.to_str().unwrap());
291                 cargo.rustflag("-L").rustflag(&root);
292             }
293         }
294     }
295
296     // By default, rustc uses `-Cembed-bitcode=yes`, and Cargo overrides that
297     // with `-Cembed-bitcode=no` for non-LTO builds. However, libstd must be
298     // built with bitcode so that the produced rlibs can be used for both LTO
299     // builds (which use bitcode) and non-LTO builds (which use object code).
300     // So we override the override here!
301     //
302     // But we don't bother for the stage 0 compiler because it's never used
303     // with LTO.
304     if stage >= 1 {
305         cargo.rustflag("-Cembed-bitcode=yes");
306     }
307
308     // By default, rustc does not include unwind tables unless they are required
309     // for a particular target. They are not required by RISC-V targets, but
310     // compiling the standard library with them means that users can get
311     // backtraces without having to recompile the standard library themselves.
312     //
313     // This choice was discussed in https://github.com/rust-lang/rust/pull/69890
314     if target.contains("riscv") {
315         cargo.rustflag("-Cforce-unwind-tables=yes");
316     }
317 }
318
319 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
320 struct StdLink {
321     pub compiler: Compiler,
322     pub target_compiler: Compiler,
323     pub target: Interned<String>,
324 }
325
326 impl Step for StdLink {
327     type Output = ();
328
329     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
330         run.never()
331     }
332
333     /// Link all libstd rlibs/dylibs into the sysroot location.
334     ///
335     /// Links those artifacts generated by `compiler` to the `stage` compiler's
336     /// sysroot for the specified `host` and `target`.
337     ///
338     /// Note that this assumes that `compiler` has already generated the libstd
339     /// libraries for `target`, and this method will find them in the relevant
340     /// output directory.
341     fn run(self, builder: &Builder<'_>) {
342         let compiler = self.compiler;
343         let target_compiler = self.target_compiler;
344         let target = self.target;
345         builder.info(&format!(
346             "Copying stage{} std from stage{} ({} -> {} / {})",
347             target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
348         ));
349         let libdir = builder.sysroot_libdir(target_compiler, target);
350         let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
351         add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
352     }
353 }
354
355 /// Copies sanitizer runtime libraries into target libdir.
356 fn copy_sanitizers(
357     builder: &Builder<'_>,
358     compiler: &Compiler,
359     target: Interned<String>,
360 ) -> Vec<PathBuf> {
361     let runtimes: Vec<native::SanitizerRuntime> = builder.ensure(native::Sanitizers { target });
362
363     if builder.config.dry_run {
364         return Vec::new();
365     }
366
367     let mut target_deps = Vec::new();
368     let libdir = builder.sysroot_libdir(*compiler, target);
369
370     for runtime in &runtimes {
371         let dst = libdir.join(&runtime.name);
372         builder.copy(&runtime.path, &dst);
373
374         if target == "x86_64-apple-darwin" {
375             // Update the library install name reflect the fact it has been renamed.
376             let status = Command::new("install_name_tool")
377                 .arg("-id")
378                 .arg(format!("@rpath/{}", runtime.name))
379                 .arg(&dst)
380                 .status()
381                 .expect("failed to execute `install_name_tool`");
382             assert!(status.success());
383         }
384
385         target_deps.push(dst);
386     }
387
388     target_deps
389 }
390
391 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
392 pub struct StartupObjects {
393     pub compiler: Compiler,
394     pub target: Interned<String>,
395 }
396
397 impl Step for StartupObjects {
398     type Output = Vec<(PathBuf, DependencyType)>;
399
400     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
401         run.path("src/rtstartup")
402     }
403
404     fn make_run(run: RunConfig<'_>) {
405         run.builder.ensure(StartupObjects {
406             compiler: run.builder.compiler(run.builder.top_stage, run.host),
407             target: run.target,
408         });
409     }
410
411     /// Builds and prepare startup objects like rsbegin.o and rsend.o
412     ///
413     /// These are primarily used on Windows right now for linking executables/dlls.
414     /// They don't require any library support as they're just plain old object
415     /// files, so we just use the nightly snapshot compiler to always build them (as
416     /// no other compilers are guaranteed to be available).
417     fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
418         let for_compiler = self.compiler;
419         let target = self.target;
420         if !target.contains("windows-gnu") {
421             return vec![];
422         }
423
424         let mut target_deps = vec![];
425
426         let src_dir = &builder.src.join("src/rtstartup");
427         let dst_dir = &builder.native_dir(target).join("rtstartup");
428         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
429         t!(fs::create_dir_all(dst_dir));
430
431         for file in &["rsbegin", "rsend"] {
432             let src_file = &src_dir.join(file.to_string() + ".rs");
433             let dst_file = &dst_dir.join(file.to_string() + ".o");
434             if !up_to_date(src_file, dst_file) {
435                 let mut cmd = Command::new(&builder.initial_rustc);
436                 builder.run(
437                     cmd.env("RUSTC_BOOTSTRAP", "1")
438                         .arg("--cfg")
439                         .arg("bootstrap")
440                         .arg("--target")
441                         .arg(target)
442                         .arg("--emit=obj")
443                         .arg("-o")
444                         .arg(dst_file)
445                         .arg(src_file),
446                 );
447             }
448
449             let target = sysroot_dir.join((*file).to_string() + ".o");
450             builder.copy(dst_file, &target);
451             target_deps.push((target, DependencyType::Target));
452         }
453
454         target_deps
455     }
456 }
457
458 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
459 pub struct Rustc {
460     pub target: Interned<String>,
461     pub compiler: Compiler,
462 }
463
464 impl Step for Rustc {
465     type Output = ();
466     const ONLY_HOSTS: bool = true;
467     const DEFAULT: bool = true;
468
469     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
470         run.all_krates("rustc-main")
471     }
472
473     fn make_run(run: RunConfig<'_>) {
474         run.builder.ensure(Rustc {
475             compiler: run.builder.compiler(run.builder.top_stage, run.host),
476             target: run.target,
477         });
478     }
479
480     /// Builds the compiler.
481     ///
482     /// This will build the compiler for a particular stage of the build using
483     /// the `compiler` targeting the `target` architecture. The artifacts
484     /// created will also be linked into the sysroot directory.
485     fn run(self, builder: &Builder<'_>) {
486         let compiler = self.compiler;
487         let target = self.target;
488
489         builder.ensure(Std { compiler, target });
490
491         if builder.config.keep_stage.contains(&compiler.stage) {
492             builder.info("Warning: Using a potentially old librustc. This may not behave well.");
493             builder.ensure(RustcLink { compiler, target_compiler: compiler, target });
494             return;
495         }
496
497         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
498         if compiler_to_use != compiler {
499             builder.ensure(Rustc { compiler: compiler_to_use, target });
500             builder
501                 .info(&format!("Uplifting stage1 rustc ({} -> {})", builder.config.build, target));
502             builder.ensure(RustcLink {
503                 compiler: compiler_to_use,
504                 target_compiler: compiler,
505                 target,
506             });
507             return;
508         }
509
510         // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
511         builder.ensure(Std {
512             compiler: builder.compiler(self.compiler.stage, builder.config.build),
513             target: builder.config.build,
514         });
515
516         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
517         rustc_cargo(builder, &mut cargo, target);
518
519         builder.info(&format!(
520             "Building stage{} compiler artifacts ({} -> {})",
521             compiler.stage, &compiler.host, target
522         ));
523         run_cargo(
524             builder,
525             cargo,
526             vec![],
527             &librustc_stamp(builder, compiler, target),
528             vec![],
529             false,
530         );
531
532         builder.ensure(RustcLink {
533             compiler: builder.compiler(compiler.stage, builder.config.build),
534             target_compiler: compiler,
535             target,
536         });
537     }
538 }
539
540 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
541     cargo
542         .arg("--features")
543         .arg(builder.rustc_features())
544         .arg("--manifest-path")
545         .arg(builder.src.join("src/rustc/Cargo.toml"));
546     rustc_cargo_env(builder, cargo, target);
547 }
548
549 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
550     // Set some configuration variables picked up by build scripts and
551     // the compiler alike
552     cargo
553         .env("CFG_RELEASE", builder.rust_release())
554         .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
555         .env("CFG_VERSION", builder.rust_version())
556         .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default());
557
558     let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
559     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
560
561     if let Some(ref ver_date) = builder.rust_info.commit_date() {
562         cargo.env("CFG_VER_DATE", ver_date);
563     }
564     if let Some(ref ver_hash) = builder.rust_info.sha() {
565         cargo.env("CFG_VER_HASH", ver_hash);
566     }
567     if !builder.unstable_features() {
568         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
569     }
570     if let Some(ref s) = builder.config.rustc_default_linker {
571         cargo.env("CFG_DEFAULT_LINKER", s);
572     }
573     if builder.config.rustc_parallel {
574         cargo.rustflag("--cfg=parallel_compiler");
575     }
576     if builder.config.rust_verify_llvm_ir {
577         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
578     }
579
580     // Pass down configuration from the LLVM build into the build of
581     // librustc_llvm and librustc_codegen_llvm.
582     //
583     // Note that this is disabled if LLVM itself is disabled or we're in a check
584     // build. If we are in a check build we still go ahead here presuming we've
585     // detected that LLVM is alreay built and good to go which helps prevent
586     // busting caches (e.g. like #71152).
587     if builder.config.llvm_enabled()
588         && (builder.kind != Kind::Check
589             || crate::native::prebuilt_llvm_config(builder, target).is_ok())
590     {
591         if builder.is_rust_llvm(target) {
592             cargo.env("LLVM_RUSTLLVM", "1");
593         }
594         let llvm_config = builder.ensure(native::Llvm { target });
595         cargo.env("LLVM_CONFIG", &llvm_config);
596         let target_config = builder.config.target_config.get(&target);
597         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
598             cargo.env("CFG_LLVM_ROOT", s);
599         }
600         // Some LLVM linker flags (-L and -l) may be needed to link librustc_llvm.
601         if let Some(ref s) = builder.config.llvm_ldflags {
602             cargo.env("LLVM_LINKER_FLAGS", s);
603         }
604         // Building with a static libstdc++ is only supported on linux right now,
605         // not for MSVC or macOS
606         if builder.config.llvm_static_stdcpp
607             && !target.contains("freebsd")
608             && !target.contains("msvc")
609             && !target.contains("apple")
610         {
611             let file = compiler_file(builder, builder.cxx(target).unwrap(), target, "libstdc++.a");
612             cargo.env("LLVM_STATIC_STDCPP", file);
613         }
614         if builder.config.llvm_link_shared || builder.config.llvm_thin_lto {
615             cargo.env("LLVM_LINK_SHARED", "1");
616         }
617         if builder.config.llvm_use_libcxx {
618             cargo.env("LLVM_USE_LIBCXX", "1");
619         }
620         if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
621             cargo.env("LLVM_NDEBUG", "1");
622         }
623     }
624 }
625
626 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
627 struct RustcLink {
628     pub compiler: Compiler,
629     pub target_compiler: Compiler,
630     pub target: Interned<String>,
631 }
632
633 impl Step for RustcLink {
634     type Output = ();
635
636     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
637         run.never()
638     }
639
640     /// Same as `std_link`, only for librustc
641     fn run(self, builder: &Builder<'_>) {
642         let compiler = self.compiler;
643         let target_compiler = self.target_compiler;
644         let target = self.target;
645         builder.info(&format!(
646             "Copying stage{} rustc from stage{} ({} -> {} / {})",
647             target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
648         ));
649         add_to_sysroot(
650             builder,
651             &builder.sysroot_libdir(target_compiler, target),
652             &builder.sysroot_libdir(target_compiler, compiler.host),
653             &librustc_stamp(builder, compiler, target),
654         );
655     }
656 }
657
658 /// Cargo's output path for the standard library in a given stage, compiled
659 /// by a particular compiler for the specified target.
660 pub fn libstd_stamp(
661     builder: &Builder<'_>,
662     compiler: Compiler,
663     target: Interned<String>,
664 ) -> PathBuf {
665     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
666 }
667
668 /// Cargo's output path for librustc in a given stage, compiled by a particular
669 /// compiler for the specified target.
670 pub fn librustc_stamp(
671     builder: &Builder<'_>,
672     compiler: Compiler,
673     target: Interned<String>,
674 ) -> PathBuf {
675     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
676 }
677
678 pub fn compiler_file(
679     builder: &Builder<'_>,
680     compiler: &Path,
681     target: Interned<String>,
682     file: &str,
683 ) -> PathBuf {
684     let mut cmd = Command::new(compiler);
685     cmd.args(builder.cflags(target, GitRepo::Rustc));
686     cmd.arg(format!("-print-file-name={}", file));
687     let out = output(&mut cmd);
688     PathBuf::from(out.trim())
689 }
690
691 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
692 pub struct Sysroot {
693     pub compiler: Compiler,
694 }
695
696 impl Step for Sysroot {
697     type Output = Interned<PathBuf>;
698
699     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
700         run.never()
701     }
702
703     /// Returns the sysroot for the `compiler` specified that *this build system
704     /// generates*.
705     ///
706     /// That is, the sysroot for the stage0 compiler is not what the compiler
707     /// thinks it is by default, but it's the same as the default for stages
708     /// 1-3.
709     fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
710         let compiler = self.compiler;
711         let sysroot = if compiler.stage == 0 {
712             builder.out.join(&compiler.host).join("stage0-sysroot")
713         } else {
714             builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
715         };
716         let _ = fs::remove_dir_all(&sysroot);
717         t!(fs::create_dir_all(&sysroot));
718
719         // Symlink the source root into the same location inside the sysroot,
720         // where `rust-src` component would go (`$sysroot/lib/rustlib/src/rust`),
721         // so that any tools relying on `rust-src` also work for local builds,
722         // and also for translating the virtual `/rustc/$hash` back to the real
723         // directory (for running tests with `rust.remap-debuginfo = true`).
724         let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
725         t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
726         let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
727         if let Err(e) = symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust) {
728             eprintln!(
729                 "warning: creating symbolic link `{}` to `{}` failed with {}",
730                 sysroot_lib_rustlib_src_rust.display(),
731                 builder.src.display(),
732                 e,
733             );
734             if builder.config.rust_remap_debuginfo {
735                 eprintln!(
736                     "warning: some `src/test/ui` tests will fail when lacking `{}`",
737                     sysroot_lib_rustlib_src_rust.display(),
738                 );
739             }
740         }
741
742         INTERNER.intern_path(sysroot)
743     }
744 }
745
746 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
747 pub struct Assemble {
748     /// The compiler which we will produce in this step. Assemble itself will
749     /// take care of ensuring that the necessary prerequisites to do so exist,
750     /// that is, this target can be a stage2 compiler and Assemble will build
751     /// previous stages for you.
752     pub target_compiler: Compiler,
753 }
754
755 impl Step for Assemble {
756     type Output = Compiler;
757
758     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
759         run.never()
760     }
761
762     /// Prepare a new compiler from the artifacts in `stage`
763     ///
764     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
765     /// must have been previously produced by the `stage - 1` builder.build
766     /// compiler.
767     fn run(self, builder: &Builder<'_>) -> Compiler {
768         let target_compiler = self.target_compiler;
769
770         if target_compiler.stage == 0 {
771             assert_eq!(
772                 builder.config.build, target_compiler.host,
773                 "Cannot obtain compiler for non-native build triple at stage 0"
774             );
775             // The stage 0 compiler for the build triple is always pre-built.
776             return target_compiler;
777         }
778
779         // Get the compiler that we'll use to bootstrap ourselves.
780         //
781         // Note that this is where the recursive nature of the bootstrap
782         // happens, as this will request the previous stage's compiler on
783         // downwards to stage 0.
784         //
785         // Also note that we're building a compiler for the host platform. We
786         // only assume that we can run `build` artifacts, which means that to
787         // produce some other architecture compiler we need to start from
788         // `build` to get there.
789         //
790         // FIXME: Perhaps we should download those libraries?
791         //        It would make builds faster...
792         //
793         // FIXME: It may be faster if we build just a stage 1 compiler and then
794         //        use that to bootstrap this compiler forward.
795         let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
796
797         // Build the libraries for this compiler to link to (i.e., the libraries
798         // it uses at runtime). NOTE: Crates the target compiler compiles don't
799         // link to these. (FIXME: Is that correct? It seems to be correct most
800         // of the time but I think we do link to these for stage2/bin compilers
801         // when not performing a full bootstrap).
802         builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
803
804         let lld_install = if builder.config.lld_enabled {
805             Some(builder.ensure(native::Lld { target: target_compiler.host }))
806         } else {
807             None
808         };
809
810         let stage = target_compiler.stage;
811         let host = target_compiler.host;
812         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
813
814         // Link in all dylibs to the libdir
815         let sysroot = builder.sysroot(target_compiler);
816         let rustc_libdir = builder.rustc_libdir(target_compiler);
817         t!(fs::create_dir_all(&rustc_libdir));
818         let src_libdir = builder.sysroot_libdir(build_compiler, host);
819         for f in builder.read_dir(&src_libdir) {
820             let filename = f.file_name().into_string().unwrap();
821             if is_dylib(&filename) {
822                 builder.copy(&f.path(), &rustc_libdir.join(&filename));
823             }
824         }
825
826         let libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
827         if let Some(lld_install) = lld_install {
828             let src_exe = exe("lld", &target_compiler.host);
829             let dst_exe = exe("rust-lld", &target_compiler.host);
830             // we prepend this bin directory to the user PATH when linking Rust binaries. To
831             // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
832             let dst = libdir.parent().unwrap().join("bin");
833             t!(fs::create_dir_all(&dst));
834             builder.copy(&lld_install.join("bin").join(&src_exe), &dst.join(&dst_exe));
835         }
836
837         // Ensure that `libLLVM.so` ends up in the newly build compiler directory,
838         // so that it can be found when the newly built `rustc` is run.
839         dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
840         dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
841
842         // Link the compiler binary itself into place
843         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
844         let rustc = out_dir.join(exe("rustc_binary", &*host));
845         let bindir = sysroot.join("bin");
846         t!(fs::create_dir_all(&bindir));
847         let compiler = builder.rustc(target_compiler);
848         builder.copy(&rustc, &compiler);
849
850         target_compiler
851     }
852 }
853
854 /// Link some files into a rustc sysroot.
855 ///
856 /// For a particular stage this will link the file listed in `stamp` into the
857 /// `sysroot_dst` provided.
858 pub fn add_to_sysroot(
859     builder: &Builder<'_>,
860     sysroot_dst: &Path,
861     sysroot_host_dst: &Path,
862     stamp: &Path,
863 ) {
864     let self_contained_dst = &sysroot_dst.join("self-contained");
865     t!(fs::create_dir_all(&sysroot_dst));
866     t!(fs::create_dir_all(&sysroot_host_dst));
867     t!(fs::create_dir_all(&self_contained_dst));
868     for (path, dependency_type) in builder.read_stamp_file(stamp) {
869         let dst = match dependency_type {
870             DependencyType::Host => sysroot_host_dst,
871             DependencyType::Target => sysroot_dst,
872             DependencyType::TargetSelfContained => self_contained_dst,
873         };
874         builder.copy(&path, &dst.join(path.file_name().unwrap()));
875     }
876 }
877
878 pub fn run_cargo(
879     builder: &Builder<'_>,
880     cargo: Cargo,
881     tail_args: Vec<String>,
882     stamp: &Path,
883     additional_target_deps: Vec<(PathBuf, DependencyType)>,
884     is_check: bool,
885 ) -> Vec<PathBuf> {
886     if builder.config.dry_run {
887         return Vec::new();
888     }
889
890     // `target_root_dir` looks like $dir/$target/release
891     let target_root_dir = stamp.parent().unwrap();
892     // `target_deps_dir` looks like $dir/$target/release/deps
893     let target_deps_dir = target_root_dir.join("deps");
894     // `host_root_dir` looks like $dir/release
895     let host_root_dir = target_root_dir
896         .parent()
897         .unwrap() // chop off `release`
898         .parent()
899         .unwrap() // chop off `$target`
900         .join(target_root_dir.file_name().unwrap());
901
902     // Spawn Cargo slurping up its JSON output. We'll start building up the
903     // `deps` array of all files it generated along with a `toplevel` array of
904     // files we need to probe for later.
905     let mut deps = Vec::new();
906     let mut toplevel = Vec::new();
907     let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
908         let (filenames, crate_types) = match msg {
909             CargoMessage::CompilerArtifact {
910                 filenames,
911                 target: CargoTarget { crate_types },
912                 ..
913             } => (filenames, crate_types),
914             _ => return,
915         };
916         for filename in filenames {
917             // Skip files like executables
918             if !(filename.ends_with(".rlib")
919                 || filename.ends_with(".lib")
920                 || filename.ends_with(".a")
921                 || is_dylib(&filename)
922                 || (is_check && filename.ends_with(".rmeta")))
923             {
924                 continue;
925             }
926
927             let filename = Path::new(&*filename);
928
929             // If this was an output file in the "host dir" we don't actually
930             // worry about it, it's not relevant for us
931             if filename.starts_with(&host_root_dir) {
932                 // Unless it's a proc macro used in the compiler
933                 if crate_types.iter().any(|t| t == "proc-macro") {
934                     deps.push((filename.to_path_buf(), DependencyType::Host));
935                 }
936                 continue;
937             }
938
939             // If this was output in the `deps` dir then this is a precise file
940             // name (hash included) so we start tracking it.
941             if filename.starts_with(&target_deps_dir) {
942                 deps.push((filename.to_path_buf(), DependencyType::Target));
943                 continue;
944             }
945
946             // Otherwise this was a "top level artifact" which right now doesn't
947             // have a hash in the name, but there's a version of this file in
948             // the `deps` folder which *does* have a hash in the name. That's
949             // the one we'll want to we'll probe for it later.
950             //
951             // We do not use `Path::file_stem` or `Path::extension` here,
952             // because some generated files may have multiple extensions e.g.
953             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
954             // split the file name by the last extension (`.lib`) while we need
955             // to split by all extensions (`.dll.lib`).
956             let expected_len = t!(filename.metadata()).len();
957             let filename = filename.file_name().unwrap().to_str().unwrap();
958             let mut parts = filename.splitn(2, '.');
959             let file_stem = parts.next().unwrap().to_owned();
960             let extension = parts.next().unwrap().to_owned();
961
962             toplevel.push((file_stem, extension, expected_len));
963         }
964     });
965
966     if !ok {
967         exit(1);
968     }
969
970     // Ok now we need to actually find all the files listed in `toplevel`. We've
971     // got a list of prefix/extensions and we basically just need to find the
972     // most recent file in the `deps` folder corresponding to each one.
973     let contents = t!(target_deps_dir.read_dir())
974         .map(|e| t!(e))
975         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
976         .collect::<Vec<_>>();
977     for (prefix, extension, expected_len) in toplevel {
978         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
979             filename.starts_with(&prefix[..])
980                 && filename[prefix.len()..].starts_with('-')
981                 && filename.ends_with(&extension[..])
982                 && meta.len() == expected_len
983         });
984         let max = candidates
985             .max_by_key(|&&(_, _, ref metadata)| FileTime::from_last_modification_time(metadata));
986         let path_to_add = match max {
987             Some(triple) => triple.0.to_str().unwrap(),
988             None => panic!("no output generated for {:?} {:?}", prefix, extension),
989         };
990         if is_dylib(path_to_add) {
991             let candidate = format!("{}.lib", path_to_add);
992             let candidate = PathBuf::from(candidate);
993             if candidate.exists() {
994                 deps.push((candidate, DependencyType::Target));
995             }
996         }
997         deps.push((path_to_add.into(), DependencyType::Target));
998     }
999
1000     deps.extend(additional_target_deps);
1001     deps.sort();
1002     let mut new_contents = Vec::new();
1003     for (dep, dependency_type) in deps.iter() {
1004         new_contents.extend(match *dependency_type {
1005             DependencyType::Host => b"h",
1006             DependencyType::Target => b"t",
1007             DependencyType::TargetSelfContained => b"s",
1008         });
1009         new_contents.extend(dep.to_str().unwrap().as_bytes());
1010         new_contents.extend(b"\0");
1011     }
1012     t!(fs::write(&stamp, &new_contents));
1013     deps.into_iter().map(|(d, _)| d).collect()
1014 }
1015
1016 pub fn stream_cargo(
1017     builder: &Builder<'_>,
1018     cargo: Cargo,
1019     tail_args: Vec<String>,
1020     cb: &mut dyn FnMut(CargoMessage<'_>),
1021 ) -> bool {
1022     let mut cargo = Command::from(cargo);
1023     if builder.config.dry_run {
1024         return true;
1025     }
1026     // Instruct Cargo to give us json messages on stdout, critically leaving
1027     // stderr as piped so we can get those pretty colors.
1028     let mut message_format = if builder.config.json_output {
1029         String::from("json")
1030     } else {
1031         String::from("json-render-diagnostics")
1032     };
1033     if let Some(s) = &builder.config.rustc_error_format {
1034         message_format.push_str(",json-diagnostic-");
1035         message_format.push_str(s);
1036     }
1037     cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
1038
1039     for arg in tail_args {
1040         cargo.arg(arg);
1041     }
1042
1043     builder.verbose(&format!("running: {:?}", cargo));
1044     let mut child = match cargo.spawn() {
1045         Ok(child) => child,
1046         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1047     };
1048
1049     // Spawn Cargo slurping up its JSON output. We'll start building up the
1050     // `deps` array of all files it generated along with a `toplevel` array of
1051     // files we need to probe for later.
1052     let stdout = BufReader::new(child.stdout.take().unwrap());
1053     for line in stdout.lines() {
1054         let line = t!(line);
1055         match serde_json::from_str::<CargoMessage<'_>>(&line) {
1056             Ok(msg) => {
1057                 if builder.config.json_output {
1058                     // Forward JSON to stdout.
1059                     println!("{}", line);
1060                 }
1061                 cb(msg)
1062             }
1063             // If this was informational, just print it out and continue
1064             Err(_) => println!("{}", line),
1065         }
1066     }
1067
1068     // Make sure Cargo actually succeeded after we read all of its stdout.
1069     let status = t!(child.wait());
1070     if !status.success() {
1071         eprintln!(
1072             "command did not execute successfully: {:?}\n\
1073                   expected success, got: {}",
1074             cargo, status
1075         );
1076     }
1077     status.success()
1078 }
1079
1080 #[derive(Deserialize)]
1081 pub struct CargoTarget<'a> {
1082     crate_types: Vec<Cow<'a, str>>,
1083 }
1084
1085 #[derive(Deserialize)]
1086 #[serde(tag = "reason", rename_all = "kebab-case")]
1087 pub enum CargoMessage<'a> {
1088     CompilerArtifact {
1089         package_id: Cow<'a, str>,
1090         features: Vec<Cow<'a, str>>,
1091         filenames: Vec<Cow<'a, str>>,
1092         target: CargoTarget<'a>,
1093     },
1094     BuildScriptExecuted {
1095         package_id: Cow<'a, str>,
1096     },
1097     BuildFinished {
1098         success: bool,
1099     },
1100 }