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