]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Merge pull request #3 from rust-lang/master
[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::prelude::*;
13 use std::io::BufReader;
14 use std::path::{Path, PathBuf};
15 use std::process::{exit, Command, Stdio};
16 use std::str;
17
18 use build_helper::{output, t, up_to_date};
19 use filetime::FileTime;
20 use serde::Deserialize;
21
22 use crate::builder::Cargo;
23 use crate::dist;
24 use crate::native;
25 use crate::util::{exe, is_dylib, symlink_dir};
26 use crate::{Compiler, GitRepo, Mode};
27
28 use crate::builder::{Builder, Kind, RunConfig, ShouldRun, Step};
29 use crate::cache::{Interned, INTERNER};
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("test")
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 { compiler, target_compiler: compiler, target });
64             return;
65         }
66
67         let mut target_deps = builder.ensure(StartupObjects { compiler, target });
68
69         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
70         if compiler_to_use != compiler {
71             builder.ensure(Std { compiler: compiler_to_use, target });
72             builder.info(&format!("Uplifting stage1 std ({} -> {})", compiler_to_use.host, target));
73
74             // Even if we're not building std this stage, the new sysroot must
75             // still contain the third party objects needed by various targets.
76             copy_third_party_objects(builder, &compiler, target);
77
78             builder.ensure(StdLink {
79                 compiler: compiler_to_use,
80                 target_compiler: compiler,
81                 target,
82             });
83             return;
84         }
85
86         target_deps.extend(copy_third_party_objects(builder, &compiler, target).into_iter());
87
88         let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
89         std_cargo(builder, target, compiler.stage, &mut cargo);
90
91         builder.info(&format!(
92             "Building stage{} std artifacts ({} -> {})",
93             compiler.stage, &compiler.host, target
94         ));
95         run_cargo(
96             builder,
97             cargo,
98             vec![],
99             &libstd_stamp(builder, compiler, target),
100             target_deps,
101             false,
102         );
103
104         builder.ensure(StdLink {
105             compiler: builder.compiler(compiler.stage, builder.config.build),
106             target_compiler: compiler,
107             target,
108         });
109     }
110 }
111
112 /// Copies third party objects needed by various targets.
113 fn copy_third_party_objects(
114     builder: &Builder<'_>,
115     compiler: &Compiler,
116     target: Interned<String>,
117 ) -> Vec<PathBuf> {
118     let libdir = builder.sysroot_libdir(*compiler, target);
119
120     let mut target_deps = vec![];
121
122     let mut copy_and_stamp = |sourcedir: &Path, name: &str| {
123         let target = libdir.join(name);
124         builder.copy(&sourcedir.join(name), &target);
125         target_deps.push(target);
126     };
127
128     // Copies the CRT objects.
129     //
130     // rustc historically provides a more self-contained installation for musl targets
131     // not requiring the presence of a native musl toolchain. For example, it can fall back
132     // to using gcc from a glibc-targeting toolchain for linking.
133     // To do that we have to distribute musl startup objects as a part of Rust toolchain
134     // and link with them manually in the self-contained mode.
135     if target.contains("musl") {
136         let srcdir = builder.musl_root(target).unwrap().join("lib");
137         for &obj in &["crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
138             copy_and_stamp(&srcdir, obj);
139         }
140     } else if target.ends_with("-wasi") {
141         let srcdir = builder.wasi_root(target).unwrap().join("lib/wasm32-wasi");
142         copy_and_stamp(&srcdir, "crt1.o");
143     }
144
145     // Copies libunwind.a compiled to be linked with x86_64-fortanix-unknown-sgx.
146     //
147     // This target needs to be linked to Fortanix's port of llvm's libunwind.
148     // libunwind requires support for rwlock and printing to stderr,
149     // which is provided by std for this target.
150     if target == "x86_64-fortanix-unknown-sgx" {
151         let src_path_env = "X86_FORTANIX_SGX_LIBS";
152         let src =
153             env::var(src_path_env).unwrap_or_else(|_| panic!("{} not found in env", src_path_env));
154         copy_and_stamp(Path::new(&src), "libunwind.a");
155     }
156
157     if builder.config.sanitizers && compiler.stage != 0 {
158         // The sanitizers are only copied in stage1 or above,
159         // to avoid creating dependency on LLVM.
160         target_deps.extend(copy_sanitizers(builder, &compiler, target));
161     }
162
163     target_deps
164 }
165
166 /// Configure cargo to compile the standard library, adding appropriate env vars
167 /// and such.
168 pub fn std_cargo(builder: &Builder<'_>, target: Interned<String>, stage: u32, cargo: &mut Cargo) {
169     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
170         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
171     }
172
173     // Determine if we're going to compile in optimized C intrinsics to
174     // the `compiler-builtins` crate. These intrinsics live in LLVM's
175     // `compiler-rt` repository, but our `src/llvm-project` submodule isn't
176     // always checked out, so we need to conditionally look for this. (e.g. if
177     // an external LLVM is used we skip the LLVM submodule checkout).
178     //
179     // Note that this shouldn't affect the correctness of `compiler-builtins`,
180     // but only its speed. Some intrinsics in C haven't been translated to Rust
181     // yet but that's pretty rare. Other intrinsics have optimized
182     // implementations in C which have only had slower versions ported to Rust,
183     // so we favor the C version where we can, but it's not critical.
184     //
185     // If `compiler-rt` is available ensure that the `c` feature of the
186     // `compiler-builtins` crate is enabled and it's configured to learn where
187     // `compiler-rt` is located.
188     let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
189     let compiler_builtins_c_feature = if compiler_builtins_root.exists() {
190         // Note that `libprofiler_builtins/build.rs` also computes this so if
191         // you're changing something here please also change that.
192         cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
193         " compiler-builtins-c".to_string()
194     } else {
195         String::new()
196     };
197
198     if builder.no_std(target) == Some(true) {
199         let mut features = "compiler-builtins-mem".to_string();
200         features.push_str(&compiler_builtins_c_feature);
201
202         // for no-std targets we only compile a few no_std crates
203         cargo
204             .args(&["-p", "alloc"])
205             .arg("--manifest-path")
206             .arg(builder.src.join("src/liballoc/Cargo.toml"))
207             .arg("--features")
208             .arg("compiler-builtins-mem compiler-builtins-c");
209     } else {
210         let mut features = builder.std_features();
211         features.push_str(&compiler_builtins_c_feature);
212
213         cargo
214             .arg("--features")
215             .arg(features)
216             .arg("--manifest-path")
217             .arg(builder.src.join("src/libtest/Cargo.toml"));
218
219         // Help the libc crate compile by assisting it in finding various
220         // sysroot native libraries.
221         if target.contains("musl") {
222             if let Some(p) = builder.musl_root(target) {
223                 let root = format!("native={}/lib", p.to_str().unwrap());
224                 cargo.rustflag("-L").rustflag(&root);
225             }
226         }
227
228         if target.ends_with("-wasi") {
229             if let Some(p) = builder.wasi_root(target) {
230                 let root = format!("native={}/lib/wasm32-wasi", p.to_str().unwrap());
231                 cargo.rustflag("-L").rustflag(&root);
232             }
233         }
234     }
235
236     // By default, rustc uses `-Cembed-bitcode=yes`, and Cargo overrides that
237     // with `-Cembed-bitcode=no` for non-LTO builds. However, libstd must be
238     // built with bitcode so that the produced rlibs can be used for both LTO
239     // builds (which use bitcode) and non-LTO builds (which use object code).
240     // So we override the override here!
241     //
242     // But we don't bother for the stage 0 compiler because it's never used
243     // with LTO.
244     if stage >= 1 {
245         cargo.rustflag("-Cembed-bitcode=yes");
246     }
247 }
248
249 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
250 struct StdLink {
251     pub compiler: Compiler,
252     pub target_compiler: Compiler,
253     pub target: Interned<String>,
254 }
255
256 impl Step for StdLink {
257     type Output = ();
258
259     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
260         run.never()
261     }
262
263     /// Link all libstd rlibs/dylibs into the sysroot location.
264     ///
265     /// Links those artifacts generated by `compiler` to the `stage` compiler's
266     /// sysroot for the specified `host` and `target`.
267     ///
268     /// Note that this assumes that `compiler` has already generated the libstd
269     /// libraries for `target`, and this method will find them in the relevant
270     /// output directory.
271     fn run(self, builder: &Builder<'_>) {
272         let compiler = self.compiler;
273         let target_compiler = self.target_compiler;
274         let target = self.target;
275         builder.info(&format!(
276             "Copying stage{} std from stage{} ({} -> {} / {})",
277             target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
278         ));
279         let libdir = builder.sysroot_libdir(target_compiler, target);
280         let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
281         add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
282     }
283 }
284
285 /// Copies sanitizer runtime libraries into target libdir.
286 fn copy_sanitizers(
287     builder: &Builder<'_>,
288     compiler: &Compiler,
289     target: Interned<String>,
290 ) -> Vec<PathBuf> {
291     let runtimes: Vec<native::SanitizerRuntime> = builder.ensure(native::Sanitizers { target });
292
293     if builder.config.dry_run {
294         return Vec::new();
295     }
296
297     let mut target_deps = Vec::new();
298     let libdir = builder.sysroot_libdir(*compiler, target);
299
300     for runtime in &runtimes {
301         let dst = libdir.join(&runtime.name);
302         builder.copy(&runtime.path, &dst);
303
304         if target == "x86_64-apple-darwin" {
305             // Update the library install name reflect the fact it has been renamed.
306             let status = Command::new("install_name_tool")
307                 .arg("-id")
308                 .arg(format!("@rpath/{}", runtime.name))
309                 .arg(&dst)
310                 .status()
311                 .expect("failed to execute `install_name_tool`");
312             assert!(status.success());
313         }
314
315         target_deps.push(dst);
316     }
317
318     target_deps
319 }
320
321 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
322 pub struct StartupObjects {
323     pub compiler: Compiler,
324     pub target: Interned<String>,
325 }
326
327 impl Step for StartupObjects {
328     type Output = Vec<PathBuf>;
329
330     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
331         run.path("src/rtstartup")
332     }
333
334     fn make_run(run: RunConfig<'_>) {
335         run.builder.ensure(StartupObjects {
336             compiler: run.builder.compiler(run.builder.top_stage, run.host),
337             target: run.target,
338         });
339     }
340
341     /// Builds and prepare startup objects like rsbegin.o and rsend.o
342     ///
343     /// These are primarily used on Windows right now for linking executables/dlls.
344     /// They don't require any library support as they're just plain old object
345     /// files, so we just use the nightly snapshot compiler to always build them (as
346     /// no other compilers are guaranteed to be available).
347     fn run(self, builder: &Builder<'_>) -> Vec<PathBuf> {
348         let for_compiler = self.compiler;
349         let target = self.target;
350         if !target.contains("windows-gnu") {
351             return vec![];
352         }
353
354         let mut target_deps = vec![];
355
356         let src_dir = &builder.src.join("src/rtstartup");
357         let dst_dir = &builder.native_dir(target).join("rtstartup");
358         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
359         t!(fs::create_dir_all(dst_dir));
360
361         for file in &["rsbegin", "rsend"] {
362             let src_file = &src_dir.join(file.to_string() + ".rs");
363             let dst_file = &dst_dir.join(file.to_string() + ".o");
364             if !up_to_date(src_file, dst_file) {
365                 let mut cmd = Command::new(&builder.initial_rustc);
366                 builder.run(
367                     cmd.env("RUSTC_BOOTSTRAP", "1")
368                         .arg("--cfg")
369                         .arg("bootstrap")
370                         .arg("--target")
371                         .arg(target)
372                         .arg("--emit=obj")
373                         .arg("-o")
374                         .arg(dst_file)
375                         .arg(src_file),
376                 );
377             }
378
379             let target = sysroot_dir.join((*file).to_string() + ".o");
380             builder.copy(dst_file, &target);
381             target_deps.push(target);
382         }
383
384         for obj in ["crt2.o", "dllcrt2.o"].iter() {
385             let src = compiler_file(builder, builder.cc(target), target, obj);
386             let target = sysroot_dir.join(obj);
387             builder.copy(&src, &target);
388             target_deps.push(target);
389         }
390
391         target_deps
392     }
393 }
394
395 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
396 pub struct Rustc {
397     pub target: Interned<String>,
398     pub compiler: Compiler,
399 }
400
401 impl Step for Rustc {
402     type Output = ();
403     const ONLY_HOSTS: bool = true;
404     const DEFAULT: bool = true;
405
406     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
407         run.all_krates("rustc-main")
408     }
409
410     fn make_run(run: RunConfig<'_>) {
411         run.builder.ensure(Rustc {
412             compiler: run.builder.compiler(run.builder.top_stage, run.host),
413             target: run.target,
414         });
415     }
416
417     /// Builds the compiler.
418     ///
419     /// This will build the compiler for a particular stage of the build using
420     /// the `compiler` targeting the `target` architecture. The artifacts
421     /// created will also be linked into the sysroot directory.
422     fn run(self, builder: &Builder<'_>) {
423         let compiler = self.compiler;
424         let target = self.target;
425
426         builder.ensure(Std { compiler, target });
427
428         if builder.config.keep_stage.contains(&compiler.stage) {
429             builder.info("Warning: Using a potentially old librustc. This may not behave well.");
430             builder.ensure(RustcLink { compiler, target_compiler: compiler, target });
431             return;
432         }
433
434         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
435         if compiler_to_use != compiler {
436             builder.ensure(Rustc { compiler: compiler_to_use, target });
437             builder
438                 .info(&format!("Uplifting stage1 rustc ({} -> {})", builder.config.build, target));
439             builder.ensure(RustcLink {
440                 compiler: compiler_to_use,
441                 target_compiler: compiler,
442                 target,
443             });
444             return;
445         }
446
447         // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
448         builder.ensure(Std {
449             compiler: builder.compiler(self.compiler.stage, builder.config.build),
450             target: builder.config.build,
451         });
452
453         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
454         rustc_cargo(builder, &mut cargo, target);
455
456         builder.info(&format!(
457             "Building stage{} compiler artifacts ({} -> {})",
458             compiler.stage, &compiler.host, target
459         ));
460         run_cargo(
461             builder,
462             cargo,
463             vec![],
464             &librustc_stamp(builder, compiler, target),
465             vec![],
466             false,
467         );
468
469         builder.ensure(RustcLink {
470             compiler: builder.compiler(compiler.stage, builder.config.build),
471             target_compiler: compiler,
472             target,
473         });
474     }
475 }
476
477 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
478     cargo
479         .arg("--features")
480         .arg(builder.rustc_features())
481         .arg("--manifest-path")
482         .arg(builder.src.join("src/rustc/Cargo.toml"));
483     rustc_cargo_env(builder, cargo, target);
484 }
485
486 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
487     // Set some configuration variables picked up by build scripts and
488     // the compiler alike
489     cargo
490         .env("CFG_RELEASE", builder.rust_release())
491         .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
492         .env("CFG_VERSION", builder.rust_version())
493         .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default());
494
495     let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
496     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
497
498     if let Some(ref ver_date) = builder.rust_info.commit_date() {
499         cargo.env("CFG_VER_DATE", ver_date);
500     }
501     if let Some(ref ver_hash) = builder.rust_info.sha() {
502         cargo.env("CFG_VER_HASH", ver_hash);
503     }
504     if !builder.unstable_features() {
505         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
506     }
507     if let Some(ref s) = builder.config.rustc_default_linker {
508         cargo.env("CFG_DEFAULT_LINKER", s);
509     }
510     if builder.config.rustc_parallel {
511         cargo.rustflag("--cfg=parallel_compiler");
512     }
513     if builder.config.rust_verify_llvm_ir {
514         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
515     }
516
517     // Pass down configuration from the LLVM build into the build of
518     // librustc_llvm and librustc_codegen_llvm.
519     //
520     // Note that this is disabled if LLVM itself is disabled or we're in a check
521     // build. If we are in a check build we still go ahead here presuming we've
522     // detected that LLVM is alreay built and good to go which helps prevent
523     // busting caches (e.g. like #71152).
524     if builder.config.llvm_enabled()
525         && (builder.kind != Kind::Check
526             || crate::native::prebuilt_llvm_config(builder, target).is_ok())
527     {
528         if builder.is_rust_llvm(target) {
529             cargo.env("LLVM_RUSTLLVM", "1");
530         }
531         let llvm_config = builder.ensure(native::Llvm { target });
532         cargo.env("LLVM_CONFIG", &llvm_config);
533         let target_config = builder.config.target_config.get(&target);
534         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
535             cargo.env("CFG_LLVM_ROOT", s);
536         }
537         // Some LLVM linker flags (-L and -l) may be needed to link librustc_llvm.
538         if let Some(ref s) = builder.config.llvm_ldflags {
539             cargo.env("LLVM_LINKER_FLAGS", s);
540         }
541         // Building with a static libstdc++ is only supported on linux right now,
542         // not for MSVC or macOS
543         if builder.config.llvm_static_stdcpp
544             && !target.contains("freebsd")
545             && !target.contains("msvc")
546             && !target.contains("apple")
547         {
548             let file = compiler_file(builder, builder.cxx(target).unwrap(), target, "libstdc++.a");
549             cargo.env("LLVM_STATIC_STDCPP", file);
550         }
551         if builder.config.llvm_link_shared || builder.config.llvm_thin_lto {
552             cargo.env("LLVM_LINK_SHARED", "1");
553         }
554         if builder.config.llvm_use_libcxx {
555             cargo.env("LLVM_USE_LIBCXX", "1");
556         }
557         if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
558             cargo.env("LLVM_NDEBUG", "1");
559         }
560     }
561 }
562
563 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
564 struct RustcLink {
565     pub compiler: Compiler,
566     pub target_compiler: Compiler,
567     pub target: Interned<String>,
568 }
569
570 impl Step for RustcLink {
571     type Output = ();
572
573     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
574         run.never()
575     }
576
577     /// Same as `std_link`, only for librustc
578     fn run(self, builder: &Builder<'_>) {
579         let compiler = self.compiler;
580         let target_compiler = self.target_compiler;
581         let target = self.target;
582         builder.info(&format!(
583             "Copying stage{} rustc from stage{} ({} -> {} / {})",
584             target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
585         ));
586         add_to_sysroot(
587             builder,
588             &builder.sysroot_libdir(target_compiler, target),
589             &builder.sysroot_libdir(target_compiler, compiler.host),
590             &librustc_stamp(builder, compiler, target),
591         );
592     }
593 }
594
595 /// Cargo's output path for the standard library in a given stage, compiled
596 /// by a particular compiler for the specified target.
597 pub fn libstd_stamp(
598     builder: &Builder<'_>,
599     compiler: Compiler,
600     target: Interned<String>,
601 ) -> PathBuf {
602     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
603 }
604
605 /// Cargo's output path for librustc in a given stage, compiled by a particular
606 /// compiler for the specified target.
607 pub fn librustc_stamp(
608     builder: &Builder<'_>,
609     compiler: Compiler,
610     target: Interned<String>,
611 ) -> PathBuf {
612     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
613 }
614
615 pub fn compiler_file(
616     builder: &Builder<'_>,
617     compiler: &Path,
618     target: Interned<String>,
619     file: &str,
620 ) -> PathBuf {
621     let mut cmd = Command::new(compiler);
622     cmd.args(builder.cflags(target, GitRepo::Rustc));
623     cmd.arg(format!("-print-file-name={}", file));
624     let out = output(&mut cmd);
625     PathBuf::from(out.trim())
626 }
627
628 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
629 pub struct Sysroot {
630     pub compiler: Compiler,
631 }
632
633 impl Step for Sysroot {
634     type Output = Interned<PathBuf>;
635
636     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
637         run.never()
638     }
639
640     /// Returns the sysroot for the `compiler` specified that *this build system
641     /// generates*.
642     ///
643     /// That is, the sysroot for the stage0 compiler is not what the compiler
644     /// thinks it is by default, but it's the same as the default for stages
645     /// 1-3.
646     fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
647         let compiler = self.compiler;
648         let sysroot = if compiler.stage == 0 {
649             builder.out.join(&compiler.host).join("stage0-sysroot")
650         } else {
651             builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
652         };
653         let _ = fs::remove_dir_all(&sysroot);
654         t!(fs::create_dir_all(&sysroot));
655
656         // Symlink the source root into the same location inside the sysroot,
657         // where `rust-src` component would go (`$sysroot/lib/rustlib/src/rust`),
658         // so that any tools relying on `rust-src` also work for local builds,
659         // and also for translating the virtual `/rustc/$hash` back to the real
660         // directory (for running tests with `rust.remap-debuginfo = true`).
661         let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
662         t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
663         let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
664         if let Err(e) = symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust) {
665             eprintln!(
666                 "warning: creating symbolic link `{}` to `{}` failed with {}",
667                 sysroot_lib_rustlib_src_rust.display(),
668                 builder.src.display(),
669                 e,
670             );
671             if builder.config.rust_remap_debuginfo {
672                 eprintln!(
673                     "warning: some `src/test/ui` tests will fail when lacking `{}`",
674                     sysroot_lib_rustlib_src_rust.display(),
675                 );
676             }
677         }
678
679         INTERNER.intern_path(sysroot)
680     }
681 }
682
683 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
684 pub struct Assemble {
685     /// The compiler which we will produce in this step. Assemble itself will
686     /// take care of ensuring that the necessary prerequisites to do so exist,
687     /// that is, this target can be a stage2 compiler and Assemble will build
688     /// previous stages for you.
689     pub target_compiler: Compiler,
690 }
691
692 impl Step for Assemble {
693     type Output = Compiler;
694
695     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
696         run.never()
697     }
698
699     /// Prepare a new compiler from the artifacts in `stage`
700     ///
701     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
702     /// must have been previously produced by the `stage - 1` builder.build
703     /// compiler.
704     fn run(self, builder: &Builder<'_>) -> Compiler {
705         let target_compiler = self.target_compiler;
706
707         if target_compiler.stage == 0 {
708             assert_eq!(
709                 builder.config.build, target_compiler.host,
710                 "Cannot obtain compiler for non-native build triple at stage 0"
711             );
712             // The stage 0 compiler for the build triple is always pre-built.
713             return target_compiler;
714         }
715
716         // Get the compiler that we'll use to bootstrap ourselves.
717         //
718         // Note that this is where the recursive nature of the bootstrap
719         // happens, as this will request the previous stage's compiler on
720         // downwards to stage 0.
721         //
722         // Also note that we're building a compiler for the host platform. We
723         // only assume that we can run `build` artifacts, which means that to
724         // produce some other architecture compiler we need to start from
725         // `build` to get there.
726         //
727         // FIXME: Perhaps we should download those libraries?
728         //        It would make builds faster...
729         //
730         // FIXME: It may be faster if we build just a stage 1 compiler and then
731         //        use that to bootstrap this compiler forward.
732         let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
733
734         // Build the libraries for this compiler to link to (i.e., the libraries
735         // it uses at runtime). NOTE: Crates the target compiler compiles don't
736         // link to these. (FIXME: Is that correct? It seems to be correct most
737         // of the time but I think we do link to these for stage2/bin compilers
738         // when not performing a full bootstrap).
739         builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
740
741         let lld_install = if builder.config.lld_enabled {
742             Some(builder.ensure(native::Lld { target: target_compiler.host }))
743         } else {
744             None
745         };
746
747         let stage = target_compiler.stage;
748         let host = target_compiler.host;
749         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
750
751         // Link in all dylibs to the libdir
752         let sysroot = builder.sysroot(target_compiler);
753         let rustc_libdir = builder.rustc_libdir(target_compiler);
754         t!(fs::create_dir_all(&rustc_libdir));
755         let src_libdir = builder.sysroot_libdir(build_compiler, host);
756         for f in builder.read_dir(&src_libdir) {
757             let filename = f.file_name().into_string().unwrap();
758             if is_dylib(&filename) {
759                 builder.copy(&f.path(), &rustc_libdir.join(&filename));
760             }
761         }
762
763         let libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
764         if let Some(lld_install) = lld_install {
765             let src_exe = exe("lld", &target_compiler.host);
766             let dst_exe = exe("rust-lld", &target_compiler.host);
767             // we prepend this bin directory to the user PATH when linking Rust binaries. To
768             // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
769             let dst = libdir.parent().unwrap().join("bin");
770             t!(fs::create_dir_all(&dst));
771             builder.copy(&lld_install.join("bin").join(&src_exe), &dst.join(&dst_exe));
772         }
773
774         // Ensure that `libLLVM.so` ends up in the newly build compiler directory,
775         // so that it can be found when the newly built `rustc` is run.
776         dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
777         dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
778
779         // Link the compiler binary itself into place
780         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
781         let rustc = out_dir.join(exe("rustc_binary", &*host));
782         let bindir = sysroot.join("bin");
783         t!(fs::create_dir_all(&bindir));
784         let compiler = builder.rustc(target_compiler);
785         builder.copy(&rustc, &compiler);
786
787         target_compiler
788     }
789 }
790
791 /// Link some files into a rustc sysroot.
792 ///
793 /// For a particular stage this will link the file listed in `stamp` into the
794 /// `sysroot_dst` provided.
795 pub fn add_to_sysroot(
796     builder: &Builder<'_>,
797     sysroot_dst: &Path,
798     sysroot_host_dst: &Path,
799     stamp: &Path,
800 ) {
801     t!(fs::create_dir_all(&sysroot_dst));
802     t!(fs::create_dir_all(&sysroot_host_dst));
803     for (path, host) in builder.read_stamp_file(stamp) {
804         if host {
805             builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
806         } else {
807             builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
808         }
809     }
810 }
811
812 pub fn run_cargo(
813     builder: &Builder<'_>,
814     cargo: Cargo,
815     tail_args: Vec<String>,
816     stamp: &Path,
817     additional_target_deps: Vec<PathBuf>,
818     is_check: bool,
819 ) -> Vec<PathBuf> {
820     if builder.config.dry_run {
821         return Vec::new();
822     }
823
824     // `target_root_dir` looks like $dir/$target/release
825     let target_root_dir = stamp.parent().unwrap();
826     // `target_deps_dir` looks like $dir/$target/release/deps
827     let target_deps_dir = target_root_dir.join("deps");
828     // `host_root_dir` looks like $dir/release
829     let host_root_dir = target_root_dir
830         .parent()
831         .unwrap() // chop off `release`
832         .parent()
833         .unwrap() // chop off `$target`
834         .join(target_root_dir.file_name().unwrap());
835
836     // Spawn Cargo slurping up its JSON output. We'll start building up the
837     // `deps` array of all files it generated along with a `toplevel` array of
838     // files we need to probe for later.
839     let mut deps = Vec::new();
840     let mut toplevel = Vec::new();
841     let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
842         let (filenames, crate_types) = match msg {
843             CargoMessage::CompilerArtifact {
844                 filenames,
845                 target: CargoTarget { crate_types },
846                 ..
847             } => (filenames, crate_types),
848             _ => return,
849         };
850         for filename in filenames {
851             // Skip files like executables
852             if !(filename.ends_with(".rlib")
853                 || filename.ends_with(".lib")
854                 || filename.ends_with(".a")
855                 || is_dylib(&filename)
856                 || (is_check && filename.ends_with(".rmeta")))
857             {
858                 continue;
859             }
860
861             let filename = Path::new(&*filename);
862
863             // If this was an output file in the "host dir" we don't actually
864             // worry about it, it's not relevant for us
865             if filename.starts_with(&host_root_dir) {
866                 // Unless it's a proc macro used in the compiler
867                 if crate_types.iter().any(|t| t == "proc-macro") {
868                     deps.push((filename.to_path_buf(), true));
869                 }
870                 continue;
871             }
872
873             // If this was output in the `deps` dir then this is a precise file
874             // name (hash included) so we start tracking it.
875             if filename.starts_with(&target_deps_dir) {
876                 deps.push((filename.to_path_buf(), false));
877                 continue;
878             }
879
880             // Otherwise this was a "top level artifact" which right now doesn't
881             // have a hash in the name, but there's a version of this file in
882             // the `deps` folder which *does* have a hash in the name. That's
883             // the one we'll want to we'll probe for it later.
884             //
885             // We do not use `Path::file_stem` or `Path::extension` here,
886             // because some generated files may have multiple extensions e.g.
887             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
888             // split the file name by the last extension (`.lib`) while we need
889             // to split by all extensions (`.dll.lib`).
890             let expected_len = t!(filename.metadata()).len();
891             let filename = filename.file_name().unwrap().to_str().unwrap();
892             let mut parts = filename.splitn(2, '.');
893             let file_stem = parts.next().unwrap().to_owned();
894             let extension = parts.next().unwrap().to_owned();
895
896             toplevel.push((file_stem, extension, expected_len));
897         }
898     });
899
900     if !ok {
901         exit(1);
902     }
903
904     // Ok now we need to actually find all the files listed in `toplevel`. We've
905     // got a list of prefix/extensions and we basically just need to find the
906     // most recent file in the `deps` folder corresponding to each one.
907     let contents = t!(target_deps_dir.read_dir())
908         .map(|e| t!(e))
909         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
910         .collect::<Vec<_>>();
911     for (prefix, extension, expected_len) in toplevel {
912         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
913             filename.starts_with(&prefix[..])
914                 && filename[prefix.len()..].starts_with('-')
915                 && filename.ends_with(&extension[..])
916                 && meta.len() == expected_len
917         });
918         let max = candidates
919             .max_by_key(|&&(_, _, ref metadata)| FileTime::from_last_modification_time(metadata));
920         let path_to_add = match max {
921             Some(triple) => triple.0.to_str().unwrap(),
922             None => panic!("no output generated for {:?} {:?}", prefix, extension),
923         };
924         if is_dylib(path_to_add) {
925             let candidate = format!("{}.lib", path_to_add);
926             let candidate = PathBuf::from(candidate);
927             if candidate.exists() {
928                 deps.push((candidate, false));
929             }
930         }
931         deps.push((path_to_add.into(), false));
932     }
933
934     deps.extend(additional_target_deps.into_iter().map(|d| (d, false)));
935     deps.sort();
936     let mut new_contents = Vec::new();
937     for (dep, proc_macro) in deps.iter() {
938         new_contents.extend(if *proc_macro { b"h" } else { b"t" });
939         new_contents.extend(dep.to_str().unwrap().as_bytes());
940         new_contents.extend(b"\0");
941     }
942     t!(fs::write(&stamp, &new_contents));
943     deps.into_iter().map(|(d, _)| d).collect()
944 }
945
946 pub fn stream_cargo(
947     builder: &Builder<'_>,
948     cargo: Cargo,
949     tail_args: Vec<String>,
950     cb: &mut dyn FnMut(CargoMessage<'_>),
951 ) -> bool {
952     let mut cargo = Command::from(cargo);
953     if builder.config.dry_run {
954         return true;
955     }
956     // Instruct Cargo to give us json messages on stdout, critically leaving
957     // stderr as piped so we can get those pretty colors.
958     let mut message_format = if builder.config.json_output {
959         String::from("json")
960     } else {
961         String::from("json-render-diagnostics")
962     };
963     if let Some(s) = &builder.config.rustc_error_format {
964         message_format.push_str(",json-diagnostic-");
965         message_format.push_str(s);
966     }
967     cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
968
969     for arg in tail_args {
970         cargo.arg(arg);
971     }
972
973     builder.verbose(&format!("running: {:?}", cargo));
974     let mut child = match cargo.spawn() {
975         Ok(child) => child,
976         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
977     };
978
979     // Spawn Cargo slurping up its JSON output. We'll start building up the
980     // `deps` array of all files it generated along with a `toplevel` array of
981     // files we need to probe for later.
982     let stdout = BufReader::new(child.stdout.take().unwrap());
983     for line in stdout.lines() {
984         let line = t!(line);
985         match serde_json::from_str::<CargoMessage<'_>>(&line) {
986             Ok(msg) => {
987                 if builder.config.json_output {
988                     // Forward JSON to stdout.
989                     println!("{}", line);
990                 }
991                 cb(msg)
992             }
993             // If this was informational, just print it out and continue
994             Err(_) => println!("{}", line),
995         }
996     }
997
998     // Make sure Cargo actually succeeded after we read all of its stdout.
999     let status = t!(child.wait());
1000     if !status.success() {
1001         eprintln!(
1002             "command did not execute successfully: {:?}\n\
1003                   expected success, got: {}",
1004             cargo, status
1005         );
1006     }
1007     status.success()
1008 }
1009
1010 #[derive(Deserialize)]
1011 pub struct CargoTarget<'a> {
1012     crate_types: Vec<Cow<'a, str>>,
1013 }
1014
1015 #[derive(Deserialize)]
1016 #[serde(tag = "reason", rename_all = "kebab-case")]
1017 pub enum CargoMessage<'a> {
1018     CompilerArtifact {
1019         package_id: Cow<'a, str>,
1020         features: Vec<Cow<'a, str>>,
1021         filenames: Vec<Cow<'a, str>>,
1022         target: CargoTarget<'a>,
1023     },
1024     BuildScriptExecuted {
1025         package_id: Cow<'a, str>,
1026     },
1027     BuildFinished {
1028         success: bool,
1029     },
1030 }