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