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