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