]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Auto merge of #60584 - jonas-schievink:ice-panic-hook, r=oli-obk
[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, 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("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 {
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         builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
99                 &compiler.host, target));
100         run_cargo(builder,
101                   &mut cargo,
102                   vec![],
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             cargo.env("RUSTC_BUILD_SANITIZERS", "1");
216         }
217
218         cargo.arg("--features").arg(features)
219             .arg("--manifest-path")
220             .arg(builder.src.join("src/libtest/Cargo.toml"));
221
222         if target.contains("musl") {
223             if let Some(p) = builder.musl_root(target) {
224                 cargo.env("MUSL_ROOT", p);
225             }
226         }
227
228         if target.ends_with("-wasi") {
229             if let Some(p) = builder.wasi_root(target) {
230                 cargo.env("WASI_ROOT", p);
231             }
232         }
233     }
234 }
235
236 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
237 struct StdLink {
238     pub compiler: Compiler,
239     pub target_compiler: Compiler,
240     pub target: Interned<String>,
241 }
242
243 impl Step for StdLink {
244     type Output = ();
245
246     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
247         run.never()
248     }
249
250     /// Link all libstd rlibs/dylibs into the sysroot location.
251     ///
252     /// Links those artifacts generated by `compiler` to the `stage` compiler's
253     /// sysroot for the specified `host` and `target`.
254     ///
255     /// Note that this assumes that `compiler` has already generated the libstd
256     /// libraries for `target`, and this method will find them in the relevant
257     /// output directory.
258     fn run(self, builder: &Builder<'_>) {
259         let compiler = self.compiler;
260         let target_compiler = self.target_compiler;
261         let target = self.target;
262         builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
263                 target_compiler.stage,
264                 compiler.stage,
265                 &compiler.host,
266                 target_compiler.host,
267                 target));
268         let libdir = builder.sysroot_libdir(target_compiler, target);
269         let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
270         add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
271
272         if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
273             // The sanitizers are only built in stage1 or above, so the dylibs will
274             // be missing in stage0 and causes panic. See the `std()` function above
275             // for reason why the sanitizers are not built in stage0.
276             copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
277         }
278     }
279 }
280
281 fn copy_apple_sanitizer_dylibs(
282     builder: &Builder<'_>,
283     native_dir: &Path,
284     platform: &str,
285     into: &Path,
286 ) {
287     for &sanitizer in &["asan", "tsan"] {
288         let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
289         let mut src_path = native_dir.join(sanitizer);
290         src_path.push("build");
291         src_path.push("lib");
292         src_path.push("darwin");
293         src_path.push(&filename);
294         builder.copy(&src_path, &into.join(filename));
295     }
296 }
297
298 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
299 pub struct StartupObjects {
300     pub compiler: Compiler,
301     pub target: Interned<String>,
302 }
303
304 impl Step for StartupObjects {
305     type Output = ();
306
307     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
308         run.path("src/rtstartup")
309     }
310
311     fn make_run(run: RunConfig<'_>) {
312         run.builder.ensure(StartupObjects {
313             compiler: run.builder.compiler(run.builder.top_stage, run.host),
314             target: run.target,
315         });
316     }
317
318     /// Builds and prepare startup objects like rsbegin.o and rsend.o
319     ///
320     /// These are primarily used on Windows right now for linking executables/dlls.
321     /// They don't require any library support as they're just plain old object
322     /// files, so we just use the nightly snapshot compiler to always build them (as
323     /// no other compilers are guaranteed to be available).
324     fn run(self, builder: &Builder<'_>) {
325         let for_compiler = self.compiler;
326         let target = self.target;
327         if !target.contains("windows-gnu") {
328             return
329         }
330
331         let src_dir = &builder.src.join("src/rtstartup");
332         let dst_dir = &builder.native_dir(target).join("rtstartup");
333         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
334         t!(fs::create_dir_all(dst_dir));
335
336         for file in &["rsbegin", "rsend"] {
337             let src_file = &src_dir.join(file.to_string() + ".rs");
338             let dst_file = &dst_dir.join(file.to_string() + ".o");
339             if !up_to_date(src_file, dst_file) {
340                 let mut cmd = Command::new(&builder.initial_rustc);
341                 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
342                             .arg("--cfg").arg("bootstrap")
343                             .arg("--target").arg(target)
344                             .arg("--emit=obj")
345                             .arg("-o").arg(dst_file)
346                             .arg(src_file));
347             }
348
349             builder.copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
350         }
351
352         for obj in ["crt2.o", "dllcrt2.o"].iter() {
353             let src = compiler_file(builder,
354                                     builder.cc(target),
355                                     target,
356                                     obj);
357             builder.copy(&src, &sysroot_dir.join(obj));
358         }
359     }
360 }
361
362 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
363 pub struct Rustc {
364     pub target: Interned<String>,
365     pub compiler: Compiler,
366 }
367
368 impl Step for Rustc {
369     type Output = ();
370     const ONLY_HOSTS: bool = true;
371     const DEFAULT: bool = true;
372
373     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
374         run.all_krates("rustc-main")
375     }
376
377     fn make_run(run: RunConfig<'_>) {
378         run.builder.ensure(Rustc {
379             compiler: run.builder.compiler(run.builder.top_stage, run.host),
380             target: run.target,
381         });
382     }
383
384     /// Builds the compiler.
385     ///
386     /// This will build the compiler for a particular stage of the build using
387     /// the `compiler` targeting the `target` architecture. The artifacts
388     /// created will also be linked into the sysroot directory.
389     fn run(self, builder: &Builder<'_>) {
390         let compiler = self.compiler;
391         let target = self.target;
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 librustc. This may not behave well.");
397             builder.ensure(RustcLink {
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(Rustc {
408                 compiler: compiler_to_use,
409                 target,
410             });
411             builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
412                 builder.config.build, target));
413             builder.ensure(RustcLink {
414                 compiler: compiler_to_use,
415                 target_compiler: compiler,
416                 target,
417             });
418             return;
419         }
420
421         // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
422         builder.ensure(Std {
423             compiler: builder.compiler(self.compiler.stage, builder.config.build),
424             target: builder.config.build,
425         });
426
427         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
428         rustc_cargo(builder, &mut cargo);
429
430         builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
431                  compiler.stage, &compiler.host, target));
432         run_cargo(builder,
433                   &mut cargo,
434                   vec![],
435                   &librustc_stamp(builder, compiler, target),
436                   false);
437
438         builder.ensure(RustcLink {
439             compiler: builder.compiler(compiler.stage, builder.config.build),
440             target_compiler: compiler,
441             target,
442         });
443     }
444 }
445
446 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Command) {
447     cargo.arg("--features").arg(builder.rustc_features())
448          .arg("--manifest-path")
449          .arg(builder.src.join("src/rustc/Cargo.toml"));
450     rustc_cargo_env(builder, cargo);
451 }
452
453 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Command) {
454     // Set some configuration variables picked up by build scripts and
455     // the compiler alike
456     cargo.env("CFG_RELEASE", builder.rust_release())
457          .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
458          .env("CFG_VERSION", builder.rust_version())
459          .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default())
460          .env("CFG_CODEGEN_BACKENDS_DIR", &builder.config.rust_codegen_backends_dir);
461
462     let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
463     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
464
465     if let Some(ref ver_date) = builder.rust_info.commit_date() {
466         cargo.env("CFG_VER_DATE", ver_date);
467     }
468     if let Some(ref ver_hash) = builder.rust_info.sha() {
469         cargo.env("CFG_VER_HASH", ver_hash);
470     }
471     if !builder.unstable_features() {
472         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
473     }
474     if let Some(ref s) = builder.config.rustc_default_linker {
475         cargo.env("CFG_DEFAULT_LINKER", s);
476     }
477     if builder.config.rustc_parallel {
478         cargo.env("RUSTC_PARALLEL_COMPILER", "1");
479     }
480     if builder.config.rust_verify_llvm_ir {
481         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
482     }
483 }
484
485 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
486 struct RustcLink {
487     pub compiler: Compiler,
488     pub target_compiler: Compiler,
489     pub target: Interned<String>,
490 }
491
492 impl Step for RustcLink {
493     type Output = ();
494
495     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
496         run.never()
497     }
498
499     /// Same as `std_link`, only for librustc
500     fn run(self, builder: &Builder<'_>) {
501         let compiler = self.compiler;
502         let target_compiler = self.target_compiler;
503         let target = self.target;
504         builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
505                  target_compiler.stage,
506                  compiler.stage,
507                  &compiler.host,
508                  target_compiler.host,
509                  target));
510         add_to_sysroot(
511             builder,
512             &builder.sysroot_libdir(target_compiler, target),
513             &builder.sysroot_libdir(target_compiler, compiler.host),
514             &librustc_stamp(builder, compiler, target)
515         );
516     }
517 }
518
519 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
520 pub struct CodegenBackend {
521     pub compiler: Compiler,
522     pub target: Interned<String>,
523     pub backend: Interned<String>,
524 }
525
526 impl Step for CodegenBackend {
527     type Output = ();
528     const ONLY_HOSTS: bool = true;
529     const DEFAULT: bool = true;
530
531     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
532         run.all_krates("rustc_codegen_llvm")
533     }
534
535     fn make_run(run: RunConfig<'_>) {
536         let backend = run.builder.config.rust_codegen_backends.get(0);
537         let backend = backend.cloned().unwrap_or_else(|| {
538             INTERNER.intern_str("llvm")
539         });
540         run.builder.ensure(CodegenBackend {
541             compiler: run.builder.compiler(run.builder.top_stage, run.host),
542             target: run.target,
543             backend,
544         });
545     }
546
547     fn run(self, builder: &Builder<'_>) {
548         let compiler = self.compiler;
549         let target = self.target;
550         let backend = self.backend;
551
552         builder.ensure(Rustc { compiler, target });
553
554         if builder.config.keep_stage.contains(&compiler.stage) {
555             builder.info("Warning: Using a potentially old codegen backend. \
556                 This may not behave well.");
557             // Codegen backends are linked separately from this step today, so we don't do
558             // anything here.
559             return;
560         }
561
562         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
563         if compiler_to_use != compiler {
564             builder.ensure(CodegenBackend {
565                 compiler: compiler_to_use,
566                 target,
567                 backend,
568             });
569             return;
570         }
571
572         let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
573
574         let mut cargo = builder.cargo(compiler, Mode::Codegen, target, "build");
575         cargo.arg("--manifest-path")
576             .arg(builder.src.join("src/librustc_codegen_llvm/Cargo.toml"));
577         rustc_cargo_env(builder, &mut cargo);
578
579         let features = build_codegen_backend(&builder, &mut cargo, &compiler, target, backend);
580
581         let tmp_stamp = out_dir.join(".tmp.stamp");
582
583         let files = run_cargo(builder,
584                               cargo.arg("--features").arg(features),
585                               vec![],
586                               &tmp_stamp,
587                               false);
588         if builder.config.dry_run {
589             return;
590         }
591         let mut files = files.into_iter()
592             .filter(|f| {
593                 let filename = f.file_name().unwrap().to_str().unwrap();
594                 is_dylib(filename) && filename.contains("rustc_codegen_llvm-")
595             });
596         let codegen_backend = match files.next() {
597             Some(f) => f,
598             None => panic!("no dylibs built for codegen backend?"),
599         };
600         if let Some(f) = files.next() {
601             panic!("codegen backend built two dylibs:\n{}\n{}",
602                    codegen_backend.display(),
603                    f.display());
604         }
605         let stamp = codegen_backend_stamp(builder, compiler, target, backend);
606         let codegen_backend = codegen_backend.to_str().unwrap();
607         t!(fs::write(&stamp, &codegen_backend));
608     }
609 }
610
611 pub fn build_codegen_backend(builder: &Builder<'_>,
612                              cargo: &mut Command,
613                              compiler: &Compiler,
614                              target: Interned<String>,
615                              backend: Interned<String>) -> String {
616     let mut features = String::new();
617
618     match &*backend {
619         "llvm" | "emscripten" => {
620             // Build LLVM for our target. This will implicitly build the
621             // host LLVM if necessary.
622             let llvm_config = builder.ensure(native::Llvm {
623                 target,
624                 emscripten: backend == "emscripten",
625             });
626
627             if backend == "emscripten" {
628                 features.push_str(" emscripten");
629             }
630
631             builder.info(&format!("Building stage{} codegen artifacts ({} -> {}, {})",
632                      compiler.stage, &compiler.host, target, backend));
633
634             // Pass down configuration from the LLVM build into the build of
635             // librustc_llvm and librustc_codegen_llvm.
636             if builder.is_rust_llvm(target) && backend != "emscripten" {
637                 cargo.env("LLVM_RUSTLLVM", "1");
638             }
639
640             cargo.env("LLVM_CONFIG", &llvm_config);
641             if backend != "emscripten" {
642                 let target_config = builder.config.target_config.get(&target);
643                 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
644                     cargo.env("CFG_LLVM_ROOT", s);
645                 }
646             }
647             // Some LLVM linker flags (-L and -l) may be needed to link librustc_llvm.
648             if let Some(ref s) = builder.config.llvm_ldflags {
649                 cargo.env("LLVM_LINKER_FLAGS", s);
650             }
651             // Building with a static libstdc++ is only supported on linux right now,
652             // not for MSVC or macOS
653             if builder.config.llvm_static_stdcpp &&
654                !target.contains("freebsd") &&
655                !target.contains("windows") &&
656                !target.contains("apple") {
657                 let file = compiler_file(builder,
658                                          builder.cxx(target).unwrap(),
659                                          target,
660                                          "libstdc++.a");
661                 cargo.env("LLVM_STATIC_STDCPP", file);
662             }
663             if builder.config.llvm_link_shared ||
664                 (builder.config.llvm_thin_lto && backend != "emscripten")
665             {
666                 cargo.env("LLVM_LINK_SHARED", "1");
667             }
668             if builder.config.llvm_use_libcxx {
669                 cargo.env("LLVM_USE_LIBCXX", "1");
670             }
671             if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
672                 cargo.env("LLVM_NDEBUG", "1");
673             }
674         }
675         _ => panic!("unknown backend: {}", backend),
676     }
677
678     features
679 }
680
681 /// Creates the `codegen-backends` folder for a compiler that's about to be
682 /// assembled as a complete compiler.
683 ///
684 /// This will take the codegen artifacts produced by `compiler` and link them
685 /// into an appropriate location for `target_compiler` to be a functional
686 /// compiler.
687 fn copy_codegen_backends_to_sysroot(builder: &Builder<'_>,
688                                     compiler: Compiler,
689                                     target_compiler: Compiler) {
690     let target = target_compiler.host;
691
692     // Note that this step is different than all the other `*Link` steps in
693     // that it's not assembling a bunch of libraries but rather is primarily
694     // moving the codegen backend into place. The codegen backend of rustc is
695     // not linked into the main compiler by default but is rather dynamically
696     // selected at runtime for inclusion.
697     //
698     // Here we're looking for the output dylib of the `CodegenBackend` step and
699     // we're copying that into the `codegen-backends` folder.
700     let dst = builder.sysroot_codegen_backends(target_compiler);
701     t!(fs::create_dir_all(&dst));
702
703     if builder.config.dry_run {
704         return;
705     }
706
707     for backend in builder.config.rust_codegen_backends.iter() {
708         let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
709         let dylib = t!(fs::read_to_string(&stamp));
710         let file = Path::new(&dylib);
711         let filename = file.file_name().unwrap().to_str().unwrap();
712         // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
713         let target_filename = {
714             let dash = filename.find('-').unwrap();
715             let dot = filename.find('.').unwrap();
716             format!("{}-{}{}",
717                     &filename[..dash],
718                     backend,
719                     &filename[dot..])
720         };
721         builder.copy(&file, &dst.join(target_filename));
722     }
723 }
724
725 fn copy_lld_to_sysroot(builder: &Builder<'_>,
726                        target_compiler: Compiler,
727                        lld_install_root: &Path) {
728     let target = target_compiler.host;
729
730     let dst = builder.sysroot_libdir(target_compiler, target)
731         .parent()
732         .unwrap()
733         .join("bin");
734     t!(fs::create_dir_all(&dst));
735
736     let src_exe = exe("lld", &target);
737     let dst_exe = exe("rust-lld", &target);
738     // we prepend this bin directory to the user PATH when linking Rust binaries. To
739     // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
740     builder.copy(&lld_install_root.join("bin").join(&src_exe), &dst.join(&dst_exe));
741 }
742
743 /// Cargo's output path for the standard library in a given stage, compiled
744 /// by a particular compiler for the specified target.
745 pub fn libstd_stamp(
746     builder: &Builder<'_>,
747     compiler: Compiler,
748     target: Interned<String>,
749 ) -> PathBuf {
750     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
751 }
752
753 /// Cargo's output path for librustc in a given stage, compiled by a particular
754 /// compiler for the specified target.
755 pub fn librustc_stamp(
756     builder: &Builder<'_>,
757     compiler: Compiler,
758     target: Interned<String>,
759 ) -> PathBuf {
760     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
761 }
762
763 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
764 /// compiler for the specified target and backend.
765 fn codegen_backend_stamp(builder: &Builder<'_>,
766                          compiler: Compiler,
767                          target: Interned<String>,
768                          backend: Interned<String>) -> PathBuf {
769     builder.cargo_out(compiler, Mode::Codegen, target)
770         .join(format!(".librustc_codegen_llvm-{}.stamp", backend))
771 }
772
773 pub fn compiler_file(
774     builder: &Builder<'_>,
775     compiler: &Path,
776     target: Interned<String>,
777     file: &str,
778 ) -> PathBuf {
779     let mut cmd = Command::new(compiler);
780     cmd.args(builder.cflags(target, GitRepo::Rustc));
781     cmd.arg(format!("-print-file-name={}", file));
782     let out = output(&mut cmd);
783     PathBuf::from(out.trim())
784 }
785
786 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
787 pub struct Sysroot {
788     pub compiler: Compiler,
789 }
790
791 impl Step for Sysroot {
792     type Output = Interned<PathBuf>;
793
794     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
795         run.never()
796     }
797
798     /// Returns the sysroot for the `compiler` specified that *this build system
799     /// generates*.
800     ///
801     /// That is, the sysroot for the stage0 compiler is not what the compiler
802     /// thinks it is by default, but it's the same as the default for stages
803     /// 1-3.
804     fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
805         let compiler = self.compiler;
806         let sysroot = if compiler.stage == 0 {
807             builder.out.join(&compiler.host).join("stage0-sysroot")
808         } else {
809             builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
810         };
811         let _ = fs::remove_dir_all(&sysroot);
812         t!(fs::create_dir_all(&sysroot));
813         INTERNER.intern_path(sysroot)
814     }
815 }
816
817 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
818 pub struct Assemble {
819     /// The compiler which we will produce in this step. Assemble itself will
820     /// take care of ensuring that the necessary prerequisites to do so exist,
821     /// that is, this target can be a stage2 compiler and Assemble will build
822     /// previous stages for you.
823     pub target_compiler: Compiler,
824 }
825
826 impl Step for Assemble {
827     type Output = Compiler;
828
829     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
830         run.never()
831     }
832
833     /// Prepare a new compiler from the artifacts in `stage`
834     ///
835     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
836     /// must have been previously produced by the `stage - 1` builder.build
837     /// compiler.
838     fn run(self, builder: &Builder<'_>) -> Compiler {
839         let target_compiler = self.target_compiler;
840
841         if target_compiler.stage == 0 {
842             assert_eq!(builder.config.build, target_compiler.host,
843                 "Cannot obtain compiler for non-native build triple at stage 0");
844             // The stage 0 compiler for the build triple is always pre-built.
845             return target_compiler;
846         }
847
848         // Get the compiler that we'll use to bootstrap ourselves.
849         //
850         // Note that this is where the recursive nature of the bootstrap
851         // happens, as this will request the previous stage's compiler on
852         // downwards to stage 0.
853         //
854         // Also note that we're building a compiler for the host platform. We
855         // only assume that we can run `build` artifacts, which means that to
856         // produce some other architecture compiler we need to start from
857         // `build` to get there.
858         //
859         // FIXME: Perhaps we should download those libraries?
860         //        It would make builds faster...
861         //
862         // FIXME: It may be faster if we build just a stage 1 compiler and then
863         //        use that to bootstrap this compiler forward.
864         let build_compiler =
865             builder.compiler(target_compiler.stage - 1, builder.config.build);
866
867         // Build the libraries for this compiler to link to (i.e., the libraries
868         // it uses at runtime). NOTE: Crates the target compiler compiles don't
869         // link to these. (FIXME: Is that correct? It seems to be correct most
870         // of the time but I think we do link to these for stage2/bin compilers
871         // when not performing a full bootstrap).
872         builder.ensure(Rustc {
873             compiler: build_compiler,
874             target: target_compiler.host,
875         });
876         for &backend in builder.config.rust_codegen_backends.iter() {
877             builder.ensure(CodegenBackend {
878                 compiler: build_compiler,
879                 target: target_compiler.host,
880                 backend,
881             });
882         }
883
884         let lld_install = if builder.config.lld_enabled {
885             Some(builder.ensure(native::Lld {
886                 target: target_compiler.host,
887             }))
888         } else {
889             None
890         };
891
892         let stage = target_compiler.stage;
893         let host = target_compiler.host;
894         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
895
896         // Link in all dylibs to the libdir
897         let sysroot = builder.sysroot(target_compiler);
898         let rustc_libdir = builder.rustc_libdir(target_compiler);
899         t!(fs::create_dir_all(&rustc_libdir));
900         let src_libdir = builder.sysroot_libdir(build_compiler, host);
901         for f in builder.read_dir(&src_libdir) {
902             let filename = f.file_name().into_string().unwrap();
903             if is_dylib(&filename) {
904                 builder.copy(&f.path(), &rustc_libdir.join(&filename));
905             }
906         }
907
908         copy_codegen_backends_to_sysroot(builder,
909                                          build_compiler,
910                                          target_compiler);
911         if let Some(lld_install) = lld_install {
912             copy_lld_to_sysroot(builder, target_compiler, &lld_install);
913         }
914
915         dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
916
917         // Link the compiler binary itself into place
918         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
919         let rustc = out_dir.join(exe("rustc_binary", &*host));
920         let bindir = sysroot.join("bin");
921         t!(fs::create_dir_all(&bindir));
922         let compiler = builder.rustc(target_compiler);
923         let _ = fs::remove_file(&compiler);
924         builder.copy(&rustc, &compiler);
925
926         target_compiler
927     }
928 }
929
930 /// Link some files into a rustc sysroot.
931 ///
932 /// For a particular stage this will link the file listed in `stamp` into the
933 /// `sysroot_dst` provided.
934 pub fn add_to_sysroot(
935     builder: &Builder<'_>,
936     sysroot_dst: &Path,
937     sysroot_host_dst: &Path,
938     stamp: &Path
939 ) {
940     t!(fs::create_dir_all(&sysroot_dst));
941     t!(fs::create_dir_all(&sysroot_host_dst));
942     for (path, host) in builder.read_stamp_file(stamp) {
943         if host {
944             builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
945         } else {
946             builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
947         }
948     }
949 }
950
951 pub fn run_cargo(builder: &Builder<'_>,
952                  cargo: &mut Command,
953                  tail_args: Vec<String>,
954                  stamp: &Path,
955                  is_check: bool)
956     -> Vec<PathBuf>
957 {
958     if builder.config.dry_run {
959         return Vec::new();
960     }
961
962     // `target_root_dir` looks like $dir/$target/release
963     let target_root_dir = stamp.parent().unwrap();
964     // `target_deps_dir` looks like $dir/$target/release/deps
965     let target_deps_dir = target_root_dir.join("deps");
966     // `host_root_dir` looks like $dir/release
967     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
968                                        .parent().unwrap() // chop off `$target`
969                                        .join(target_root_dir.file_name().unwrap());
970
971     // Spawn Cargo slurping up its JSON output. We'll start building up the
972     // `deps` array of all files it generated along with a `toplevel` array of
973     // files we need to probe for later.
974     let mut deps = Vec::new();
975     let mut toplevel = Vec::new();
976     let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
977         let (filenames, crate_types) = match msg {
978             CargoMessage::CompilerArtifact {
979                 filenames,
980                 target: CargoTarget {
981                     crate_types,
982                 },
983                 ..
984             } => (filenames, crate_types),
985             _ => return,
986         };
987         for filename in filenames {
988             // Skip files like executables
989             if !filename.ends_with(".rlib") &&
990                !filename.ends_with(".lib") &&
991                !filename.ends_with(".a") &&
992                !is_dylib(&filename) &&
993                !(is_check && filename.ends_with(".rmeta")) {
994                 continue;
995             }
996
997             let filename = Path::new(&*filename);
998
999             // If this was an output file in the "host dir" we don't actually
1000             // worry about it, it's not relevant for us
1001             if filename.starts_with(&host_root_dir) {
1002                 // Unless it's a proc macro used in the compiler
1003                 if crate_types.iter().any(|t| t == "proc-macro") {
1004                     deps.push((filename.to_path_buf(), true));
1005                 }
1006                 continue;
1007             }
1008
1009             // If this was output in the `deps` dir then this is a precise file
1010             // name (hash included) so we start tracking it.
1011             if filename.starts_with(&target_deps_dir) {
1012                 deps.push((filename.to_path_buf(), false));
1013                 continue;
1014             }
1015
1016             // Otherwise this was a "top level artifact" which right now doesn't
1017             // have a hash in the name, but there's a version of this file in
1018             // the `deps` folder which *does* have a hash in the name. That's
1019             // the one we'll want to we'll probe for it later.
1020             //
1021             // We do not use `Path::file_stem` or `Path::extension` here,
1022             // because some generated files may have multiple extensions e.g.
1023             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1024             // split the file name by the last extension (`.lib`) while we need
1025             // to split by all extensions (`.dll.lib`).
1026             let expected_len = t!(filename.metadata()).len();
1027             let filename = filename.file_name().unwrap().to_str().unwrap();
1028             let mut parts = filename.splitn(2, '.');
1029             let file_stem = parts.next().unwrap().to_owned();
1030             let extension = parts.next().unwrap().to_owned();
1031
1032             toplevel.push((file_stem, extension, expected_len));
1033         }
1034     });
1035
1036     if !ok {
1037         exit(1);
1038     }
1039
1040     // Ok now we need to actually find all the files listed in `toplevel`. We've
1041     // got a list of prefix/extensions and we basically just need to find the
1042     // most recent file in the `deps` folder corresponding to each one.
1043     let contents = t!(target_deps_dir.read_dir())
1044         .map(|e| t!(e))
1045         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1046         .collect::<Vec<_>>();
1047     for (prefix, extension, expected_len) in toplevel {
1048         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1049             filename.starts_with(&prefix[..]) &&
1050                 filename[prefix.len()..].starts_with("-") &&
1051                 filename.ends_with(&extension[..]) &&
1052                 meta.len() == expected_len
1053         });
1054         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1055             FileTime::from_last_modification_time(metadata)
1056         });
1057         let path_to_add = match max {
1058             Some(triple) => triple.0.to_str().unwrap(),
1059             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1060         };
1061         if is_dylib(path_to_add) {
1062             let candidate = format!("{}.lib", path_to_add);
1063             let candidate = PathBuf::from(candidate);
1064             if candidate.exists() {
1065                 deps.push((candidate, false));
1066             }
1067         }
1068         deps.push((path_to_add.into(), false));
1069     }
1070
1071     deps.sort();
1072     let mut new_contents = Vec::new();
1073     for (dep, proc_macro) in deps.iter() {
1074         new_contents.extend(if *proc_macro { b"h" } else { b"t" });
1075         new_contents.extend(dep.to_str().unwrap().as_bytes());
1076         new_contents.extend(b"\0");
1077     }
1078     t!(fs::write(&stamp, &new_contents));
1079     deps.into_iter().map(|(d, _)| d).collect()
1080 }
1081
1082 pub fn stream_cargo(
1083     builder: &Builder<'_>,
1084     cargo: &mut Command,
1085     tail_args: Vec<String>,
1086     cb: &mut dyn FnMut(CargoMessage<'_>),
1087 ) -> bool {
1088     if builder.config.dry_run {
1089         return true;
1090     }
1091     // Instruct Cargo to give us json messages on stdout, critically leaving
1092     // stderr as piped so we can get those pretty colors.
1093     let mut message_format = String::from("json-render-diagnostics");
1094     if let Some(s) = &builder.config.rustc_error_format  {
1095         message_format.push_str(",json-diagnostic-");
1096         message_format.push_str(s);
1097     }
1098     cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
1099
1100     for arg in tail_args {
1101         cargo.arg(arg);
1102     }
1103
1104     builder.verbose(&format!("running: {:?}", cargo));
1105     let mut child = match cargo.spawn() {
1106         Ok(child) => child,
1107         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1108     };
1109
1110     // Spawn Cargo slurping up its JSON output. We'll start building up the
1111     // `deps` array of all files it generated along with a `toplevel` array of
1112     // files we need to probe for later.
1113     let stdout = BufReader::new(child.stdout.take().unwrap());
1114     for line in stdout.lines() {
1115         let line = t!(line);
1116         match serde_json::from_str::<CargoMessage<'_>>(&line) {
1117             Ok(msg) => cb(msg),
1118             // If this was informational, just print it out and continue
1119             Err(_) => println!("{}", line)
1120         }
1121     }
1122
1123     // Make sure Cargo actually succeeded after we read all of its stdout.
1124     let status = t!(child.wait());
1125     if !status.success() {
1126         eprintln!("command did not execute successfully: {:?}\n\
1127                   expected success, got: {}",
1128                  cargo,
1129                  status);
1130     }
1131     status.success()
1132 }
1133
1134 #[derive(Deserialize)]
1135 pub struct CargoTarget<'a> {
1136     crate_types: Vec<Cow<'a, str>>,
1137 }
1138
1139 #[derive(Deserialize)]
1140 #[serde(tag = "reason", rename_all = "kebab-case")]
1141 pub enum CargoMessage<'a> {
1142     CompilerArtifact {
1143         package_id: Cow<'a, str>,
1144         features: Vec<Cow<'a, str>>,
1145         filenames: Vec<Cow<'a, str>>,
1146         target: CargoTarget<'a>,
1147     },
1148     BuildScriptExecuted {
1149         package_id: Cow<'a, str>,
1150     },
1151 }