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