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