]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
rustbuild: Tweak how stage1 compilers are selected
[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::BufReader;
13 use std::io::prelude::*;
14 use std::path::{Path, PathBuf};
15 use std::process::{Command, Stdio, exit};
16 use std::str;
17
18 use build_helper::{output, mtime, t, up_to_date};
19 use filetime::FileTime;
20 use serde::Deserialize;
21 use serde_json;
22
23 use crate::dist;
24 use crate::util::{exe, is_dylib};
25 use crate::{Compiler, Mode, GitRepo};
26 use crate::native;
27
28 use crate::cache::{INTERNER, Interned};
29 use crate::builder::{Step, RunConfig, ShouldRun, Builder};
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("std")
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 {
64                 compiler,
65                 target_compiler: compiler,
66                 target,
67             });
68             return;
69         }
70
71         builder.ensure(StartupObjects { compiler, target });
72
73         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
74         if compiler_to_use != compiler {
75             builder.ensure(Std {
76                 compiler: compiler_to_use,
77                 target,
78             });
79             builder.info(&format!("Uplifting stage1 std ({} -> {})", compiler_to_use.host, target));
80
81             // Even if we're not building std this stage, the new sysroot must
82             // still contain the third party objects needed by various targets.
83             copy_third_party_objects(builder, &compiler, target);
84
85             builder.ensure(StdLink {
86                 compiler: compiler_to_use,
87                 target_compiler: compiler,
88                 target,
89             });
90             return;
91         }
92
93         copy_third_party_objects(builder, &compiler, target);
94
95         let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
96         std_cargo(builder, &compiler, target, &mut cargo);
97
98         let _folder = builder.fold_output(|| format!("stage{}-std", compiler.stage));
99         builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
100                 &compiler.host, target));
101         run_cargo(builder,
102                   &mut cargo,
103                   &libstd_stamp(builder, compiler, target),
104                   false);
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 /// Copies third pary objects needed by various targets.
115 fn copy_third_party_objects(builder: &Builder<'_>, compiler: &Compiler, target: Interned<String>) {
116     let libdir = builder.sysroot_libdir(*compiler, target);
117
118     // Copies the crt(1,i,n).o startup objects
119     //
120     // Since musl supports fully static linking, we can cross link for it even
121     // with a glibc-targeting toolchain, given we have the appropriate startup
122     // files. As those shipped with glibc won't work, copy the ones provided by
123     // musl so we have them on linux-gnu hosts.
124     if target.contains("musl") {
125         for &obj in &["crt1.o", "crti.o", "crtn.o"] {
126             builder.copy(
127                 &builder.musl_root(target).unwrap().join("lib").join(obj),
128                 &libdir.join(obj),
129             );
130         }
131     } else if target.ends_with("-wasi") {
132         for &obj in &["crt1.o"] {
133             builder.copy(
134                 &builder.wasi_root(target).unwrap().join("lib/wasm32-wasi").join(obj),
135                 &libdir.join(obj),
136             );
137         }
138     }
139
140     // Copies libunwind.a compiled to be linked wit x86_64-fortanix-unknown-sgx.
141     //
142     // This target needs to be linked to Fortanix's port of llvm's libunwind.
143     // libunwind requires support for rwlock and printing to stderr,
144     // which is provided by std for this target.
145     if target == "x86_64-fortanix-unknown-sgx" {
146         let src_path_env = "X86_FORTANIX_SGX_LIBS";
147         let obj = "libunwind.a";
148         let src = env::var(src_path_env).expect(&format!("{} not found in env", src_path_env));
149         let src = Path::new(&src).join(obj);
150         builder.copy(&src, &libdir.join(obj));
151     }
152 }
153
154 /// Configure cargo to compile the standard library, adding appropriate env vars
155 /// and such.
156 pub fn std_cargo(builder: &Builder<'_>,
157                  compiler: &Compiler,
158                  target: Interned<String>,
159                  cargo: &mut Command) {
160     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
161         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
162     }
163
164     // Determine if we're going to compile in optimized C intrinsics to
165     // the `compiler-builtins` crate. These intrinsics live in LLVM's
166     // `compiler-rt` repository, but our `src/llvm-project` submodule isn't
167     // always checked out, so we need to conditionally look for this. (e.g. if
168     // an external LLVM is used we skip the LLVM submodule checkout).
169     //
170     // Note that this shouldn't affect the correctness of `compiler-builtins`,
171     // but only its speed. Some intrinsics in C haven't been translated to Rust
172     // yet but that's pretty rare. Other intrinsics have optimized
173     // implementations in C which have only had slower versions ported to Rust,
174     // so we favor the C version where we can, but it's not critical.
175     //
176     // If `compiler-rt` is available ensure that the `c` feature of the
177     // `compiler-builtins` crate is enabled and it's configured to learn where
178     // `compiler-rt` is located.
179     let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
180     let compiler_builtins_c_feature = if compiler_builtins_root.exists() {
181         cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
182         " compiler-builtins-c".to_string()
183     } else {
184         String::new()
185     };
186
187     if builder.no_std(target) == Some(true) {
188         let mut features = "compiler-builtins-mem".to_string();
189         features.push_str(&compiler_builtins_c_feature);
190
191         // for no-std targets we only compile a few no_std crates
192         cargo
193             .args(&["-p", "alloc"])
194             .arg("--manifest-path")
195             .arg(builder.src.join("src/liballoc/Cargo.toml"))
196             .arg("--features")
197             .arg("compiler-builtins-mem compiler-builtins-c");
198     } else {
199         let mut features = builder.std_features();
200         features.push_str(&compiler_builtins_c_feature);
201
202         if compiler.stage != 0 && builder.config.sanitizers {
203             // This variable is used by the sanitizer runtime crates, e.g.
204             // rustc_lsan, to build the sanitizer runtime from C code
205             // When this variable is missing, those crates won't compile the C code,
206             // so we don't set this variable during stage0 where llvm-config is
207             // missing
208             // We also only build the runtimes when --enable-sanitizers (or its
209             // config.toml equivalent) is used
210             let llvm_config = builder.ensure(native::Llvm {
211                 target: builder.config.build,
212                 emscripten: false,
213             });
214             cargo.env("LLVM_CONFIG", llvm_config);
215         }
216
217         cargo.arg("--features").arg(features)
218             .arg("--manifest-path")
219             .arg(builder.src.join("src/libstd/Cargo.toml"));
220
221         if target.contains("musl") {
222             if let Some(p) = builder.musl_root(target) {
223                 cargo.env("MUSL_ROOT", p);
224             }
225         }
226
227         if target.ends_with("-wasi") {
228             if let Some(p) = builder.wasi_root(target) {
229                 cargo.env("WASI_ROOT", p);
230             }
231         }
232     }
233 }
234
235 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
236 struct StdLink {
237     pub compiler: Compiler,
238     pub target_compiler: Compiler,
239     pub target: Interned<String>,
240 }
241
242 impl Step for StdLink {
243     type Output = ();
244
245     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
246         run.never()
247     }
248
249     /// Link all libstd rlibs/dylibs into the sysroot location.
250     ///
251     /// Links those artifacts generated by `compiler` to the `stage` compiler's
252     /// sysroot for the specified `host` and `target`.
253     ///
254     /// Note that this assumes that `compiler` has already generated the libstd
255     /// libraries for `target`, and this method will find them in the relevant
256     /// output directory.
257     fn run(self, builder: &Builder<'_>) {
258         let compiler = self.compiler;
259         let target_compiler = self.target_compiler;
260         let target = self.target;
261         builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
262                 target_compiler.stage,
263                 compiler.stage,
264                 &compiler.host,
265                 target_compiler.host,
266                 target));
267         let libdir = builder.sysroot_libdir(target_compiler, target);
268         let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
269         add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
270
271         if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
272             // The sanitizers are only built in stage1 or above, so the dylibs will
273             // be missing in stage0 and causes panic. See the `std()` function above
274             // for reason why the sanitizers are not built in stage0.
275             copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
276         }
277
278         builder.cargo(target_compiler, Mode::ToolStd, target, "clean");
279     }
280 }
281
282 fn copy_apple_sanitizer_dylibs(
283     builder: &Builder<'_>,
284     native_dir: &Path,
285     platform: &str,
286     into: &Path,
287 ) {
288     for &sanitizer in &["asan", "tsan"] {
289         let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
290         let mut src_path = native_dir.join(sanitizer);
291         src_path.push("build");
292         src_path.push("lib");
293         src_path.push("darwin");
294         src_path.push(&filename);
295         builder.copy(&src_path, &into.join(filename));
296     }
297 }
298
299 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
300 pub struct StartupObjects {
301     pub compiler: Compiler,
302     pub target: Interned<String>,
303 }
304
305 impl Step for StartupObjects {
306     type Output = ();
307
308     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
309         run.path("src/rtstartup")
310     }
311
312     fn make_run(run: RunConfig<'_>) {
313         run.builder.ensure(StartupObjects {
314             compiler: run.builder.compiler(run.builder.top_stage, run.host),
315             target: run.target,
316         });
317     }
318
319     /// Builds and prepare startup objects like rsbegin.o and rsend.o
320     ///
321     /// These are primarily used on Windows right now for linking executables/dlls.
322     /// They don't require any library support as they're just plain old object
323     /// files, so we just use the nightly snapshot compiler to always build them (as
324     /// no other compilers are guaranteed to be available).
325     fn run(self, builder: &Builder<'_>) {
326         let for_compiler = self.compiler;
327         let target = self.target;
328         if !target.contains("pc-windows-gnu") {
329             return
330         }
331
332         let src_dir = &builder.src.join("src/rtstartup");
333         let dst_dir = &builder.native_dir(target).join("rtstartup");
334         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
335         t!(fs::create_dir_all(dst_dir));
336
337         for file in &["rsbegin", "rsend"] {
338             let src_file = &src_dir.join(file.to_string() + ".rs");
339             let dst_file = &dst_dir.join(file.to_string() + ".o");
340             if !up_to_date(src_file, dst_file) {
341                 let mut cmd = Command::new(&builder.initial_rustc);
342                 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
343                             .arg("--cfg").arg("stage0")
344                             .arg("--target").arg(target)
345                             .arg("--emit=obj")
346                             .arg("-o").arg(dst_file)
347                             .arg(src_file));
348             }
349
350             builder.copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
351         }
352
353         for obj in ["crt2.o", "dllcrt2.o"].iter() {
354             let src = compiler_file(builder,
355                                     builder.cc(target),
356                                     target,
357                                     obj);
358             builder.copy(&src, &sysroot_dir.join(obj));
359         }
360     }
361 }
362
363 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
364 pub struct Test {
365     pub target: Interned<String>,
366     pub compiler: Compiler,
367 }
368
369 impl Step for Test {
370     type Output = ();
371     const DEFAULT: bool = true;
372
373     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
374         run.all_krates("test")
375     }
376
377     fn make_run(run: RunConfig<'_>) {
378         run.builder.ensure(Test {
379             compiler: run.builder.compiler(run.builder.top_stage, run.host),
380             target: run.target,
381         });
382     }
383
384     /// Builds libtest.
385     ///
386     /// This will build libtest and supporting libraries for a particular stage of
387     /// the build using the `compiler` targeting the `target` architecture. The
388     /// artifacts created will also be linked into the sysroot directory.
389     fn run(self, builder: &Builder<'_>) {
390         let target = self.target;
391         let compiler = self.compiler;
392
393         builder.ensure(Std { compiler, target });
394
395         if builder.config.keep_stage.contains(&compiler.stage) {
396             builder.info("Warning: Using a potentially old libtest. This may not behave well.");
397             builder.ensure(TestLink {
398                 compiler,
399                 target_compiler: compiler,
400                 target,
401             });
402             return;
403         }
404
405         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
406         if compiler_to_use != compiler {
407             builder.ensure(Test {
408                 compiler: compiler_to_use,
409                 target,
410             });
411             builder.info(
412                 &format!("Uplifting stage1 test ({} -> {})", builder.config.build, target));
413             builder.ensure(TestLink {
414                 compiler: compiler_to_use,
415                 target_compiler: compiler,
416                 target,
417             });
418             return;
419         }
420
421         let mut cargo = builder.cargo(compiler, Mode::Test, target, "build");
422         test_cargo(builder, &compiler, target, &mut cargo);
423
424         let _folder = builder.fold_output(|| format!("stage{}-test", compiler.stage));
425         builder.info(&format!("Building stage{} test artifacts ({} -> {})", compiler.stage,
426                 &compiler.host, target));
427         run_cargo(builder,
428                   &mut cargo,
429                   &libtest_stamp(builder, compiler, target),
430                   false);
431
432         builder.ensure(TestLink {
433             compiler: builder.compiler(compiler.stage, builder.config.build),
434             target_compiler: compiler,
435             target,
436         });
437     }
438 }
439
440 /// Same as `std_cargo`, but for libtest
441 pub fn test_cargo(builder: &Builder<'_>,
442                   _compiler: &Compiler,
443                   _target: Interned<String>,
444                   cargo: &mut Command) {
445     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
446         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
447     }
448     cargo.arg("--manifest-path")
449         .arg(builder.src.join("src/libtest/Cargo.toml"));
450 }
451
452 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
453 pub struct TestLink {
454     pub compiler: Compiler,
455     pub target_compiler: Compiler,
456     pub target: Interned<String>,
457 }
458
459 impl Step for TestLink {
460     type Output = ();
461
462     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
463         run.never()
464     }
465
466     /// Same as `std_link`, only for libtest
467     fn run(self, builder: &Builder<'_>) {
468         let compiler = self.compiler;
469         let target_compiler = self.target_compiler;
470         let target = self.target;
471         builder.info(&format!("Copying stage{} test from stage{} ({} -> {} / {})",
472                 target_compiler.stage,
473                 compiler.stage,
474                 &compiler.host,
475                 target_compiler.host,
476                 target));
477         add_to_sysroot(
478             builder,
479             &builder.sysroot_libdir(target_compiler, target),
480             &builder.sysroot_libdir(target_compiler, compiler.host),
481             &libtest_stamp(builder, compiler, target)
482         );
483
484         builder.cargo(target_compiler, Mode::ToolTest, target, "clean");
485     }
486 }
487
488 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
489 pub struct Rustc {
490     pub target: Interned<String>,
491     pub compiler: Compiler,
492 }
493
494 impl Step for Rustc {
495     type Output = ();
496     const ONLY_HOSTS: bool = true;
497     const DEFAULT: bool = true;
498
499     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
500         run.all_krates("rustc-main")
501     }
502
503     fn make_run(run: RunConfig<'_>) {
504         run.builder.ensure(Rustc {
505             compiler: run.builder.compiler(run.builder.top_stage, run.host),
506             target: run.target,
507         });
508     }
509
510     /// Builds the compiler.
511     ///
512     /// This will build the compiler for a particular stage of the build using
513     /// the `compiler` targeting the `target` architecture. The artifacts
514     /// created will also be linked into the sysroot directory.
515     fn run(self, builder: &Builder<'_>) {
516         let compiler = self.compiler;
517         let target = self.target;
518
519         builder.ensure(Test { compiler, target });
520
521         if builder.config.keep_stage.contains(&compiler.stage) {
522             builder.info("Warning: Using a potentially old librustc. This may not behave well.");
523             builder.ensure(RustcLink {
524                 compiler,
525                 target_compiler: compiler,
526                 target,
527             });
528             return;
529         }
530
531         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
532         if compiler_to_use != compiler {
533             builder.ensure(Rustc {
534                 compiler: compiler_to_use,
535                 target,
536             });
537             builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
538                 builder.config.build, target));
539             builder.ensure(RustcLink {
540                 compiler: compiler_to_use,
541                 target_compiler: compiler,
542                 target,
543             });
544             return;
545         }
546
547         // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
548         builder.ensure(Test {
549             compiler: builder.compiler(self.compiler.stage, builder.config.build),
550             target: builder.config.build,
551         });
552
553         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
554         rustc_cargo(builder, &mut cargo);
555
556         let _folder = builder.fold_output(|| format!("stage{}-rustc", compiler.stage));
557         builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
558                  compiler.stage, &compiler.host, target));
559         run_cargo(builder,
560                   &mut cargo,
561                   &librustc_stamp(builder, compiler, target),
562                   false);
563
564         builder.ensure(RustcLink {
565             compiler: builder.compiler(compiler.stage, builder.config.build),
566             target_compiler: compiler,
567             target,
568         });
569     }
570 }
571
572 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Command) {
573     cargo.arg("--features").arg(builder.rustc_features())
574          .arg("--manifest-path")
575          .arg(builder.src.join("src/rustc/Cargo.toml"));
576     rustc_cargo_env(builder, cargo);
577 }
578
579 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Command) {
580     // Set some configuration variables picked up by build scripts and
581     // the compiler alike
582     cargo.env("CFG_RELEASE", builder.rust_release())
583          .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
584          .env("CFG_VERSION", builder.rust_version())
585          .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default())
586          .env("CFG_CODEGEN_BACKENDS_DIR", &builder.config.rust_codegen_backends_dir);
587
588     let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
589     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
590
591     // If we're not building a compiler with debugging information then remove
592     // these two env vars which would be set otherwise.
593     if builder.config.rust_debuginfo_only_std {
594         cargo.env_remove("RUSTC_DEBUGINFO");
595         cargo.env_remove("RUSTC_DEBUGINFO_LINES");
596     }
597
598     if let Some(ref ver_date) = builder.rust_info.commit_date() {
599         cargo.env("CFG_VER_DATE", ver_date);
600     }
601     if let Some(ref ver_hash) = builder.rust_info.sha() {
602         cargo.env("CFG_VER_HASH", ver_hash);
603     }
604     if !builder.unstable_features() {
605         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
606     }
607     if let Some(ref s) = builder.config.rustc_default_linker {
608         cargo.env("CFG_DEFAULT_LINKER", s);
609     }
610     if builder.config.rustc_parallel {
611         cargo.env("RUSTC_PARALLEL_COMPILER", "1");
612     }
613     if builder.config.rust_verify_llvm_ir {
614         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
615     }
616 }
617
618 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
619 struct RustcLink {
620     pub compiler: Compiler,
621     pub target_compiler: Compiler,
622     pub target: Interned<String>,
623 }
624
625 impl Step for RustcLink {
626     type Output = ();
627
628     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
629         run.never()
630     }
631
632     /// Same as `std_link`, only for librustc
633     fn run(self, builder: &Builder<'_>) {
634         let compiler = self.compiler;
635         let target_compiler = self.target_compiler;
636         let target = self.target;
637         builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
638                  target_compiler.stage,
639                  compiler.stage,
640                  &compiler.host,
641                  target_compiler.host,
642                  target));
643         add_to_sysroot(
644             builder,
645             &builder.sysroot_libdir(target_compiler, target),
646             &builder.sysroot_libdir(target_compiler, compiler.host),
647             &librustc_stamp(builder, compiler, target)
648         );
649         builder.cargo(target_compiler, Mode::ToolRustc, target, "clean");
650     }
651 }
652
653 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
654 pub struct CodegenBackend {
655     pub compiler: Compiler,
656     pub target: Interned<String>,
657     pub backend: Interned<String>,
658 }
659
660 impl Step for CodegenBackend {
661     type Output = ();
662     const ONLY_HOSTS: bool = true;
663     const DEFAULT: bool = true;
664
665     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
666         run.all_krates("rustc_codegen_llvm")
667     }
668
669     fn make_run(run: RunConfig<'_>) {
670         let backend = run.builder.config.rust_codegen_backends.get(0);
671         let backend = backend.cloned().unwrap_or_else(|| {
672             INTERNER.intern_str("llvm")
673         });
674         run.builder.ensure(CodegenBackend {
675             compiler: run.builder.compiler(run.builder.top_stage, run.host),
676             target: run.target,
677             backend,
678         });
679     }
680
681     fn run(self, builder: &Builder<'_>) {
682         let compiler = self.compiler;
683         let target = self.target;
684         let backend = self.backend;
685
686         builder.ensure(Rustc { compiler, target });
687
688         if builder.config.keep_stage.contains(&compiler.stage) {
689             builder.info("Warning: Using a potentially old codegen backend. \
690                 This may not behave well.");
691             // Codegen backends are linked separately from this step today, so we don't do
692             // anything here.
693             return;
694         }
695
696         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
697         if compiler_to_use != compiler {
698             builder.ensure(CodegenBackend {
699                 compiler: compiler_to_use,
700                 target,
701                 backend,
702             });
703             return;
704         }
705
706         let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
707
708         let mut cargo = builder.cargo(compiler, Mode::Codegen, target, "build");
709         cargo.arg("--manifest-path")
710             .arg(builder.src.join("src/librustc_codegen_llvm/Cargo.toml"));
711         rustc_cargo_env(builder, &mut cargo);
712
713         let features = build_codegen_backend(&builder, &mut cargo, &compiler, target, backend);
714
715         let tmp_stamp = out_dir.join(".tmp.stamp");
716
717         let _folder = builder.fold_output(|| format!("stage{}-rustc_codegen_llvm", compiler.stage));
718         let files = run_cargo(builder,
719                               cargo.arg("--features").arg(features),
720                               &tmp_stamp,
721                               false);
722         if builder.config.dry_run {
723             return;
724         }
725         let mut files = files.into_iter()
726             .filter(|f| {
727                 let filename = f.file_name().unwrap().to_str().unwrap();
728                 is_dylib(filename) && filename.contains("rustc_codegen_llvm-")
729             });
730         let codegen_backend = match files.next() {
731             Some(f) => f,
732             None => panic!("no dylibs built for codegen backend?"),
733         };
734         if let Some(f) = files.next() {
735             panic!("codegen backend built two dylibs:\n{}\n{}",
736                    codegen_backend.display(),
737                    f.display());
738         }
739         let stamp = codegen_backend_stamp(builder, compiler, target, backend);
740         let codegen_backend = codegen_backend.to_str().unwrap();
741         t!(fs::write(&stamp, &codegen_backend));
742     }
743 }
744
745 pub fn build_codegen_backend(builder: &Builder<'_>,
746                              cargo: &mut Command,
747                              compiler: &Compiler,
748                              target: Interned<String>,
749                              backend: Interned<String>) -> String {
750     let mut features = String::new();
751
752     match &*backend {
753         "llvm" | "emscripten" => {
754             // Build LLVM for our target. This will implicitly build the
755             // host LLVM if necessary.
756             let llvm_config = builder.ensure(native::Llvm {
757                 target,
758                 emscripten: backend == "emscripten",
759             });
760
761             if backend == "emscripten" {
762                 features.push_str(" emscripten");
763             }
764
765             builder.info(&format!("Building stage{} codegen artifacts ({} -> {}, {})",
766                      compiler.stage, &compiler.host, target, backend));
767
768             // Pass down configuration from the LLVM build into the build of
769             // librustc_llvm and librustc_codegen_llvm.
770             if builder.is_rust_llvm(target) && backend != "emscripten" {
771                 cargo.env("LLVM_RUSTLLVM", "1");
772             }
773
774             cargo.env("LLVM_CONFIG", &llvm_config);
775             if backend != "emscripten" {
776                 let target_config = builder.config.target_config.get(&target);
777                 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
778                     cargo.env("CFG_LLVM_ROOT", s);
779                 }
780             }
781             // Building with a static libstdc++ is only supported on linux right now,
782             // not for MSVC or macOS
783             if builder.config.llvm_static_stdcpp &&
784                !target.contains("freebsd") &&
785                !target.contains("windows") &&
786                !target.contains("apple") {
787                 let file = compiler_file(builder,
788                                          builder.cxx(target).unwrap(),
789                                          target,
790                                          "libstdc++.a");
791                 cargo.env("LLVM_STATIC_STDCPP", file);
792             }
793             if builder.config.llvm_link_shared ||
794                 (builder.config.llvm_thin_lto && backend != "emscripten")
795             {
796                 cargo.env("LLVM_LINK_SHARED", "1");
797             }
798             if builder.config.llvm_use_libcxx {
799                 cargo.env("LLVM_USE_LIBCXX", "1");
800             }
801         }
802         _ => panic!("unknown backend: {}", backend),
803     }
804
805     features
806 }
807
808 /// Creates the `codegen-backends` folder for a compiler that's about to be
809 /// assembled as a complete compiler.
810 ///
811 /// This will take the codegen artifacts produced by `compiler` and link them
812 /// into an appropriate location for `target_compiler` to be a functional
813 /// compiler.
814 fn copy_codegen_backends_to_sysroot(builder: &Builder<'_>,
815                                     compiler: Compiler,
816                                     target_compiler: Compiler) {
817     let target = target_compiler.host;
818
819     // Note that this step is different than all the other `*Link` steps in
820     // that it's not assembling a bunch of libraries but rather is primarily
821     // moving the codegen backend into place. The codegen backend of rustc is
822     // not linked into the main compiler by default but is rather dynamically
823     // selected at runtime for inclusion.
824     //
825     // Here we're looking for the output dylib of the `CodegenBackend` step and
826     // we're copying that into the `codegen-backends` folder.
827     let dst = builder.sysroot_codegen_backends(target_compiler);
828     t!(fs::create_dir_all(&dst));
829
830     if builder.config.dry_run {
831         return;
832     }
833
834     for backend in builder.config.rust_codegen_backends.iter() {
835         let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
836         let dylib = t!(fs::read_to_string(&stamp));
837         let file = Path::new(&dylib);
838         let filename = file.file_name().unwrap().to_str().unwrap();
839         // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
840         let target_filename = {
841             let dash = filename.find('-').unwrap();
842             let dot = filename.find('.').unwrap();
843             format!("{}-{}{}",
844                     &filename[..dash],
845                     backend,
846                     &filename[dot..])
847         };
848         builder.copy(&file, &dst.join(target_filename));
849     }
850 }
851
852 fn copy_lld_to_sysroot(builder: &Builder<'_>,
853                        target_compiler: Compiler,
854                        lld_install_root: &Path) {
855     let target = target_compiler.host;
856
857     let dst = builder.sysroot_libdir(target_compiler, target)
858         .parent()
859         .unwrap()
860         .join("bin");
861     t!(fs::create_dir_all(&dst));
862
863     let src_exe = exe("lld", &target);
864     let dst_exe = exe("rust-lld", &target);
865     // we prepend this bin directory to the user PATH when linking Rust binaries. To
866     // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
867     builder.copy(&lld_install_root.join("bin").join(&src_exe), &dst.join(&dst_exe));
868 }
869
870 /// Cargo's output path for the standard library in a given stage, compiled
871 /// by a particular compiler for the specified target.
872 pub fn libstd_stamp(
873     builder: &Builder<'_>,
874     compiler: Compiler,
875     target: Interned<String>,
876 ) -> PathBuf {
877     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
878 }
879
880 /// Cargo's output path for libtest in a given stage, compiled by a particular
881 /// compiler for the specified target.
882 pub fn libtest_stamp(
883     builder: &Builder<'_>,
884     compiler: Compiler,
885     target: Interned<String>,
886 ) -> PathBuf {
887     builder.cargo_out(compiler, Mode::Test, target).join(".libtest.stamp")
888 }
889
890 /// Cargo's output path for librustc in a given stage, compiled by a particular
891 /// compiler for the specified target.
892 pub fn librustc_stamp(
893     builder: &Builder<'_>,
894     compiler: Compiler,
895     target: Interned<String>,
896 ) -> PathBuf {
897     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
898 }
899
900 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
901 /// compiler for the specified target and backend.
902 fn codegen_backend_stamp(builder: &Builder<'_>,
903                          compiler: Compiler,
904                          target: Interned<String>,
905                          backend: Interned<String>) -> PathBuf {
906     builder.cargo_out(compiler, Mode::Codegen, target)
907         .join(format!(".librustc_codegen_llvm-{}.stamp", backend))
908 }
909
910 pub fn compiler_file(
911     builder: &Builder<'_>,
912     compiler: &Path,
913     target: Interned<String>,
914     file: &str,
915 ) -> PathBuf {
916     let mut cmd = Command::new(compiler);
917     cmd.args(builder.cflags(target, GitRepo::Rustc));
918     cmd.arg(format!("-print-file-name={}", file));
919     let out = output(&mut cmd);
920     PathBuf::from(out.trim())
921 }
922
923 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
924 pub struct Sysroot {
925     pub compiler: Compiler,
926 }
927
928 impl Step for Sysroot {
929     type Output = Interned<PathBuf>;
930
931     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
932         run.never()
933     }
934
935     /// Returns the sysroot for the `compiler` specified that *this build system
936     /// generates*.
937     ///
938     /// That is, the sysroot for the stage0 compiler is not what the compiler
939     /// thinks it is by default, but it's the same as the default for stages
940     /// 1-3.
941     fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
942         let compiler = self.compiler;
943         let sysroot = if compiler.stage == 0 {
944             builder.out.join(&compiler.host).join("stage0-sysroot")
945         } else {
946             builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
947         };
948         let _ = fs::remove_dir_all(&sysroot);
949         t!(fs::create_dir_all(&sysroot));
950         INTERNER.intern_path(sysroot)
951     }
952 }
953
954 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
955 pub struct Assemble {
956     /// The compiler which we will produce in this step. Assemble itself will
957     /// take care of ensuring that the necessary prerequisites to do so exist,
958     /// that is, this target can be a stage2 compiler and Assemble will build
959     /// previous stages for you.
960     pub target_compiler: Compiler,
961 }
962
963 impl Step for Assemble {
964     type Output = Compiler;
965
966     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
967         run.never()
968     }
969
970     /// Prepare a new compiler from the artifacts in `stage`
971     ///
972     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
973     /// must have been previously produced by the `stage - 1` builder.build
974     /// compiler.
975     fn run(self, builder: &Builder<'_>) -> Compiler {
976         let target_compiler = self.target_compiler;
977
978         if target_compiler.stage == 0 {
979             assert_eq!(builder.config.build, target_compiler.host,
980                 "Cannot obtain compiler for non-native build triple at stage 0");
981             // The stage 0 compiler for the build triple is always pre-built.
982             return target_compiler;
983         }
984
985         // Get the compiler that we'll use to bootstrap ourselves.
986         //
987         // Note that this is where the recursive nature of the bootstrap
988         // happens, as this will request the previous stage's compiler on
989         // downwards to stage 0.
990         //
991         // Also note that we're building a compiler for the host platform. We
992         // only assume that we can run `build` artifacts, which means that to
993         // produce some other architecture compiler we need to start from
994         // `build` to get there.
995         //
996         // FIXME: Perhaps we should download those libraries?
997         //        It would make builds faster...
998         //
999         // FIXME: It may be faster if we build just a stage 1 compiler and then
1000         //        use that to bootstrap this compiler forward.
1001         let build_compiler =
1002             builder.compiler(target_compiler.stage - 1, builder.config.build);
1003
1004         // Build the libraries for this compiler to link to (i.e., the libraries
1005         // it uses at runtime). NOTE: Crates the target compiler compiles don't
1006         // link to these. (FIXME: Is that correct? It seems to be correct most
1007         // of the time but I think we do link to these for stage2/bin compilers
1008         // when not performing a full bootstrap).
1009         builder.ensure(Rustc {
1010             compiler: build_compiler,
1011             target: target_compiler.host,
1012         });
1013         for &backend in builder.config.rust_codegen_backends.iter() {
1014             builder.ensure(CodegenBackend {
1015                 compiler: build_compiler,
1016                 target: target_compiler.host,
1017                 backend,
1018             });
1019         }
1020
1021         let lld_install = if builder.config.lld_enabled {
1022             Some(builder.ensure(native::Lld {
1023                 target: target_compiler.host,
1024             }))
1025         } else {
1026             None
1027         };
1028
1029         let stage = target_compiler.stage;
1030         let host = target_compiler.host;
1031         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
1032
1033         // Link in all dylibs to the libdir
1034         let sysroot = builder.sysroot(target_compiler);
1035         let rustc_libdir = builder.rustc_libdir(target_compiler);
1036         t!(fs::create_dir_all(&rustc_libdir));
1037         let src_libdir = builder.sysroot_libdir(build_compiler, host);
1038         for f in builder.read_dir(&src_libdir) {
1039             let filename = f.file_name().into_string().unwrap();
1040             if is_dylib(&filename) {
1041                 builder.copy(&f.path(), &rustc_libdir.join(&filename));
1042             }
1043         }
1044
1045         copy_codegen_backends_to_sysroot(builder,
1046                                          build_compiler,
1047                                          target_compiler);
1048         if let Some(lld_install) = lld_install {
1049             copy_lld_to_sysroot(builder, target_compiler, &lld_install);
1050         }
1051
1052         dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
1053
1054         // Link the compiler binary itself into place
1055         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
1056         let rustc = out_dir.join(exe("rustc_binary", &*host));
1057         let bindir = sysroot.join("bin");
1058         t!(fs::create_dir_all(&bindir));
1059         let compiler = builder.rustc(target_compiler);
1060         let _ = fs::remove_file(&compiler);
1061         builder.copy(&rustc, &compiler);
1062
1063         target_compiler
1064     }
1065 }
1066
1067 /// Link some files into a rustc sysroot.
1068 ///
1069 /// For a particular stage this will link the file listed in `stamp` into the
1070 /// `sysroot_dst` provided.
1071 pub fn add_to_sysroot(
1072     builder: &Builder<'_>,
1073     sysroot_dst: &Path,
1074     sysroot_host_dst: &Path,
1075     stamp: &Path
1076 ) {
1077     t!(fs::create_dir_all(&sysroot_dst));
1078     t!(fs::create_dir_all(&sysroot_host_dst));
1079     for (path, host) in builder.read_stamp_file(stamp) {
1080         if host {
1081             builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
1082         } else {
1083             builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
1084         }
1085     }
1086 }
1087
1088 pub fn run_cargo(builder: &Builder<'_>,
1089                  cargo: &mut Command,
1090                  stamp: &Path,
1091                  is_check: bool)
1092     -> Vec<PathBuf>
1093 {
1094     if builder.config.dry_run {
1095         return Vec::new();
1096     }
1097
1098     // `target_root_dir` looks like $dir/$target/release
1099     let target_root_dir = stamp.parent().unwrap();
1100     // `target_deps_dir` looks like $dir/$target/release/deps
1101     let target_deps_dir = target_root_dir.join("deps");
1102     // `host_root_dir` looks like $dir/release
1103     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
1104                                        .parent().unwrap() // chop off `$target`
1105                                        .join(target_root_dir.file_name().unwrap());
1106
1107     // Spawn Cargo slurping up its JSON output. We'll start building up the
1108     // `deps` array of all files it generated along with a `toplevel` array of
1109     // files we need to probe for later.
1110     let mut deps = Vec::new();
1111     let mut toplevel = Vec::new();
1112     let ok = stream_cargo(builder, cargo, &mut |msg| {
1113         let (filenames, crate_types) = match msg {
1114             CargoMessage::CompilerArtifact {
1115                 filenames,
1116                 target: CargoTarget {
1117                     crate_types,
1118                 },
1119                 ..
1120             } => (filenames, crate_types),
1121             _ => return,
1122         };
1123         for filename in filenames {
1124             // Skip files like executables
1125             if !filename.ends_with(".rlib") &&
1126                !filename.ends_with(".lib") &&
1127                !is_dylib(&filename) &&
1128                !(is_check && filename.ends_with(".rmeta")) {
1129                 continue;
1130             }
1131
1132             let filename = Path::new(&*filename);
1133
1134             // If this was an output file in the "host dir" we don't actually
1135             // worry about it, it's not relevant for us
1136             if filename.starts_with(&host_root_dir) {
1137                 // Unless it's a proc macro used in the compiler
1138                 if crate_types.iter().any(|t| t == "proc-macro") {
1139                     deps.push((filename.to_path_buf(), true));
1140                 }
1141                 continue;
1142             }
1143
1144             // If this was output in the `deps` dir then this is a precise file
1145             // name (hash included) so we start tracking it.
1146             if filename.starts_with(&target_deps_dir) {
1147                 deps.push((filename.to_path_buf(), false));
1148                 continue;
1149             }
1150
1151             // Otherwise this was a "top level artifact" which right now doesn't
1152             // have a hash in the name, but there's a version of this file in
1153             // the `deps` folder which *does* have a hash in the name. That's
1154             // the one we'll want to we'll probe for it later.
1155             //
1156             // We do not use `Path::file_stem` or `Path::extension` here,
1157             // because some generated files may have multiple extensions e.g.
1158             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1159             // split the file name by the last extension (`.lib`) while we need
1160             // to split by all extensions (`.dll.lib`).
1161             let expected_len = t!(filename.metadata()).len();
1162             let filename = filename.file_name().unwrap().to_str().unwrap();
1163             let mut parts = filename.splitn(2, '.');
1164             let file_stem = parts.next().unwrap().to_owned();
1165             let extension = parts.next().unwrap().to_owned();
1166
1167             toplevel.push((file_stem, extension, expected_len));
1168         }
1169     });
1170
1171     if !ok {
1172         exit(1);
1173     }
1174
1175     // Ok now we need to actually find all the files listed in `toplevel`. We've
1176     // got a list of prefix/extensions and we basically just need to find the
1177     // most recent file in the `deps` folder corresponding to each one.
1178     let contents = t!(target_deps_dir.read_dir())
1179         .map(|e| t!(e))
1180         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1181         .collect::<Vec<_>>();
1182     for (prefix, extension, expected_len) in toplevel {
1183         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1184             filename.starts_with(&prefix[..]) &&
1185                 filename[prefix.len()..].starts_with("-") &&
1186                 filename.ends_with(&extension[..]) &&
1187                 meta.len() == expected_len
1188         });
1189         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1190             FileTime::from_last_modification_time(metadata)
1191         });
1192         let path_to_add = match max {
1193             Some(triple) => triple.0.to_str().unwrap(),
1194             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1195         };
1196         if is_dylib(path_to_add) {
1197             let candidate = format!("{}.lib", path_to_add);
1198             let candidate = PathBuf::from(candidate);
1199             if candidate.exists() {
1200                 deps.push((candidate, false));
1201             }
1202         }
1203         deps.push((path_to_add.into(), false));
1204     }
1205
1206     // Now we want to update the contents of the stamp file, if necessary. First
1207     // we read off the previous contents along with its mtime. If our new
1208     // contents (the list of files to copy) is different or if any dep's mtime
1209     // is newer then we rewrite the stamp file.
1210     deps.sort();
1211     let stamp_contents = fs::read(stamp);
1212     let stamp_mtime = mtime(&stamp);
1213     let mut new_contents = Vec::new();
1214     let mut max = None;
1215     let mut max_path = None;
1216     for (dep, proc_macro) in deps.iter() {
1217         let mtime = mtime(dep);
1218         if Some(mtime) > max {
1219             max = Some(mtime);
1220             max_path = Some(dep.clone());
1221         }
1222         new_contents.extend(if *proc_macro { b"h" } else { b"t" });
1223         new_contents.extend(dep.to_str().unwrap().as_bytes());
1224         new_contents.extend(b"\0");
1225     }
1226     let max = max.unwrap();
1227     let max_path = max_path.unwrap();
1228     let contents_equal = stamp_contents
1229         .map(|contents| contents == new_contents)
1230         .unwrap_or_default();
1231     if contents_equal && max <= stamp_mtime {
1232         builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}",
1233                 stamp, max, stamp_mtime));
1234         return deps.into_iter().map(|(d, _)| d).collect()
1235     }
1236     if max > stamp_mtime {
1237         builder.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1238     } else {
1239         builder.verbose(&format!("updating {:?} as deps changed", stamp));
1240     }
1241     t!(fs::write(&stamp, &new_contents));
1242     deps.into_iter().map(|(d, _)| d).collect()
1243 }
1244
1245 pub fn stream_cargo(
1246     builder: &Builder<'_>,
1247     cargo: &mut Command,
1248     cb: &mut dyn FnMut(CargoMessage<'_>),
1249 ) -> bool {
1250     if builder.config.dry_run {
1251         return true;
1252     }
1253     // Instruct Cargo to give us json messages on stdout, critically leaving
1254     // stderr as piped so we can get those pretty colors.
1255     cargo.arg("--message-format").arg("json")
1256          .stdout(Stdio::piped());
1257
1258     builder.verbose(&format!("running: {:?}", cargo));
1259     let mut child = match cargo.spawn() {
1260         Ok(child) => child,
1261         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1262     };
1263
1264     // Spawn Cargo slurping up its JSON output. We'll start building up the
1265     // `deps` array of all files it generated along with a `toplevel` array of
1266     // files we need to probe for later.
1267     let stdout = BufReader::new(child.stdout.take().unwrap());
1268     for line in stdout.lines() {
1269         let line = t!(line);
1270         match serde_json::from_str::<CargoMessage<'_>>(&line) {
1271             Ok(msg) => cb(msg),
1272             // If this was informational, just print it out and continue
1273             Err(_) => println!("{}", line)
1274         }
1275     }
1276
1277     // Make sure Cargo actually succeeded after we read all of its stdout.
1278     let status = t!(child.wait());
1279     if !status.success() {
1280         eprintln!("command did not execute successfully: {:?}\n\
1281                   expected success, got: {}",
1282                  cargo,
1283                  status);
1284     }
1285     status.success()
1286 }
1287
1288 #[derive(Deserialize)]
1289 pub struct CargoTarget<'a> {
1290     crate_types: Vec<Cow<'a, str>>,
1291 }
1292
1293 #[derive(Deserialize)]
1294 #[serde(tag = "reason", rename_all = "kebab-case")]
1295 pub enum CargoMessage<'a> {
1296     CompilerArtifact {
1297         package_id: Cow<'a, str>,
1298         features: Vec<Cow<'a, str>>,
1299         filenames: Vec<Cow<'a, str>>,
1300         target: CargoTarget<'a>,
1301     },
1302     BuildScriptExecuted {
1303         package_id: Cow<'a, str>,
1304     }
1305 }