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