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