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