]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/lib.rs
Auto merge of #41577 - Keruspe:master, r=alexcrichton
[rust.git] / src / bootstrap / lib.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Implementation of rustbuild, the Rust build system.
12 //!
13 //! This module, and its descendants, are the implementation of the Rust build
14 //! system. Most of this build system is backed by Cargo but the outer layer
15 //! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
16 //! builds, building artifacts like LLVM, etc. The goals of rustbuild are:
17 //!
18 //! * To be an easily understandable, easily extensible, and maintainable build
19 //!   system.
20 //! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
21 //!   crates.io and Cargo.
22 //! * A standard interface to build across all platforms, including MSVC
23 //!
24 //! ## Architecture
25 //!
26 //! Although this build system defers most of the complicated logic to Cargo
27 //! itself, it still needs to maintain a list of targets and dependencies which
28 //! it can itself perform. Rustbuild is made up of a list of rules with
29 //! dependencies amongst them (created in the `step` module) and then knows how
30 //! to execute each in sequence. Each time rustbuild is invoked, it will simply
31 //! iterate through this list of steps and execute each serially in turn.  For
32 //! each step rustbuild relies on the step internally being incremental and
33 //! parallel. Note, though, that the `-j` parameter to rustbuild gets forwarded
34 //! to appropriate test harnesses and such.
35 //!
36 //! Most of the "meaty" steps that matter are backed by Cargo, which does indeed
37 //! have its own parallelism and incremental management. Later steps, like
38 //! tests, aren't incremental and simply run the entire suite currently.
39 //!
40 //! When you execute `x.py build`, the steps which are executed are:
41 //!
42 //! * First, the python script is run. This will automatically download the
43 //!   stage0 rustc and cargo according to `src/stage0.txt`, or using the cached
44 //!   versions if they're available. These are then used to compile rustbuild
45 //!   itself (using Cargo). Finally, control is then transferred to rustbuild.
46 //!
47 //! * Rustbuild takes over, performs sanity checks, probes the environment,
48 //!   reads configuration, builds up a list of steps, and then starts executing
49 //!   them.
50 //!
51 //! * The stage0 libstd is compiled
52 //! * The stage0 libtest is compiled
53 //! * The stage0 librustc is compiled
54 //! * The stage1 compiler is assembled
55 //! * The stage1 libstd, libtest, librustc are compiled
56 //! * The stage2 compiler is assembled
57 //! * The stage2 libstd, libtest, librustc are compiled
58 //!
59 //! Each step is driven by a separate Cargo project and rustbuild orchestrates
60 //! copying files between steps and otherwise preparing for Cargo to run.
61 //!
62 //! ## Further information
63 //!
64 //! More documentation can be found in each respective module below, and you can
65 //! also check out the `src/bootstrap/README.md` file for more information.
66
67 #![deny(warnings)]
68
69 #[macro_use]
70 extern crate build_helper;
71 extern crate cmake;
72 extern crate filetime;
73 extern crate gcc;
74 extern crate getopts;
75 extern crate num_cpus;
76 extern crate rustc_serialize;
77 extern crate toml;
78
79 use std::cmp;
80 use std::collections::HashMap;
81 use std::env;
82 use std::ffi::OsString;
83 use std::fs::{self, File};
84 use std::io::Read;
85 use std::path::{Component, PathBuf, Path};
86 use std::process::Command;
87
88 use build_helper::{run_silent, run_suppressed, output, mtime};
89
90 use util::{exe, libdir, add_lib_path};
91
92 mod cc;
93 mod channel;
94 mod check;
95 mod clean;
96 mod compile;
97 mod metadata;
98 mod config;
99 mod dist;
100 mod doc;
101 mod flags;
102 mod install;
103 mod native;
104 mod sanity;
105 mod step;
106 pub mod util;
107
108 #[cfg(windows)]
109 mod job;
110
111 #[cfg(not(windows))]
112 mod job {
113     pub unsafe fn setup() {}
114 }
115
116 pub use config::Config;
117 pub use flags::{Flags, Subcommand};
118
119 /// A structure representing a Rust compiler.
120 ///
121 /// Each compiler has a `stage` that it is associated with and a `host` that
122 /// corresponds to the platform the compiler runs on. This structure is used as
123 /// a parameter to many methods below.
124 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
125 pub struct Compiler<'a> {
126     stage: u32,
127     host: &'a str,
128 }
129
130 /// Global configuration for the build system.
131 ///
132 /// This structure transitively contains all configuration for the build system.
133 /// All filesystem-encoded configuration is in `config`, all flags are in
134 /// `flags`, and then parsed or probed information is listed in the keys below.
135 ///
136 /// This structure is a parameter of almost all methods in the build system,
137 /// although most functions are implemented as free functions rather than
138 /// methods specifically on this structure itself (to make it easier to
139 /// organize).
140 pub struct Build {
141     // User-specified configuration via config.toml
142     config: Config,
143
144     // User-specified configuration via CLI flags
145     flags: Flags,
146
147     // Derived properties from the above two configurations
148     cargo: PathBuf,
149     rustc: PathBuf,
150     src: PathBuf,
151     out: PathBuf,
152     rust_info: channel::GitInfo,
153     cargo_info: channel::GitInfo,
154     rls_info: channel::GitInfo,
155     local_rebuild: bool,
156
157     // Probed tools at runtime
158     lldb_version: Option<String>,
159     lldb_python_dir: Option<String>,
160
161     // Runtime state filled in later on
162     cc: HashMap<String, (gcc::Tool, Option<PathBuf>)>,
163     cxx: HashMap<String, gcc::Tool>,
164     crates: HashMap<String, Crate>,
165     is_sudo: bool,
166     src_is_git: bool,
167 }
168
169 #[derive(Debug)]
170 struct Crate {
171     name: String,
172     version: String,
173     deps: Vec<String>,
174     path: PathBuf,
175     doc_step: String,
176     build_step: String,
177     test_step: String,
178     bench_step: String,
179 }
180
181 /// The various "modes" of invoking Cargo.
182 ///
183 /// These entries currently correspond to the various output directories of the
184 /// build system, with each mod generating output in a different directory.
185 #[derive(Clone, Copy, PartialEq, Eq)]
186 pub enum Mode {
187     /// This cargo is going to build the standard library, placing output in the
188     /// "stageN-std" directory.
189     Libstd,
190
191     /// This cargo is going to build libtest, placing output in the
192     /// "stageN-test" directory.
193     Libtest,
194
195     /// This cargo is going to build librustc and compiler libraries, placing
196     /// output in the "stageN-rustc" directory.
197     Librustc,
198
199     /// This cargo is going to some build tool, placing output in the
200     /// "stageN-tools" directory.
201     Tool,
202 }
203
204 impl Build {
205     /// Creates a new set of build configuration from the `flags` on the command
206     /// line and the filesystem `config`.
207     ///
208     /// By default all build output will be placed in the current directory.
209     pub fn new(flags: Flags, config: Config) -> Build {
210         let cwd = t!(env::current_dir());
211         let src = flags.src.clone().or_else(|| {
212             env::var_os("SRC").map(|x| x.into())
213         }).unwrap_or(cwd.clone());
214         let out = cwd.join("build");
215
216         let stage0_root = out.join(&config.build).join("stage0/bin");
217         let rustc = match config.rustc {
218             Some(ref s) => PathBuf::from(s),
219             None => stage0_root.join(exe("rustc", &config.build)),
220         };
221         let cargo = match config.cargo {
222             Some(ref s) => PathBuf::from(s),
223             None => stage0_root.join(exe("cargo", &config.build)),
224         };
225         let local_rebuild = config.local_rebuild;
226
227         let is_sudo = match env::var_os("SUDO_USER") {
228             Some(sudo_user) => {
229                 match env::var_os("USER") {
230                     Some(user) => user != sudo_user,
231                     None => false,
232                 }
233             }
234             None => false,
235         };
236         let rust_info = channel::GitInfo::new(&src);
237         let cargo_info = channel::GitInfo::new(&src.join("cargo"));
238         let rls_info = channel::GitInfo::new(&src.join("rls"));
239         let src_is_git = src.join(".git").exists();
240
241         Build {
242             flags: flags,
243             config: config,
244             cargo: cargo,
245             rustc: rustc,
246             src: src,
247             out: out,
248
249             rust_info: rust_info,
250             cargo_info: cargo_info,
251             rls_info: rls_info,
252             local_rebuild: local_rebuild,
253             cc: HashMap::new(),
254             cxx: HashMap::new(),
255             crates: HashMap::new(),
256             lldb_version: None,
257             lldb_python_dir: None,
258             is_sudo: is_sudo,
259             src_is_git: src_is_git,
260         }
261     }
262
263     /// Executes the entire build, as configured by the flags and configuration.
264     pub fn build(&mut self) {
265         unsafe {
266             job::setup();
267         }
268
269         if let Subcommand::Clean = self.flags.cmd {
270             return clean::clean(self);
271         }
272
273         self.verbose("finding compilers");
274         cc::find(self);
275         self.verbose("running sanity check");
276         sanity::check(self);
277         // If local-rust is the same major.minor as the current version, then force a local-rebuild
278         let local_version_verbose = output(
279             Command::new(&self.rustc).arg("--version").arg("--verbose"));
280         let local_release = local_version_verbose
281             .lines().filter(|x| x.starts_with("release:"))
282             .next().unwrap().trim_left_matches("release:").trim();
283         let my_version = channel::CFG_RELEASE_NUM;
284         if local_release.split('.').take(2).eq(my_version.split('.').take(2)) {
285             self.verbose(&format!("auto-detected local-rebuild {}", local_release));
286             self.local_rebuild = true;
287         }
288         self.verbose("updating submodules");
289         self.update_submodules();
290         self.verbose("learning about cargo");
291         metadata::build(self);
292
293         step::run(self);
294     }
295
296     /// Updates all git submodules that we have.
297     ///
298     /// This will detect if any submodules are out of date an run the necessary
299     /// commands to sync them all with upstream.
300     fn update_submodules(&self) {
301         struct Submodule<'a> {
302             path: &'a Path,
303             state: State,
304         }
305
306         enum State {
307             // The submodule may have staged/unstaged changes
308             MaybeDirty,
309             // Or could be initialized but never updated
310             NotInitialized,
311             // The submodule, itself, has extra commits but those changes haven't been commited to
312             // the (outer) git repository
313             OutOfSync,
314         }
315
316         if !self.src_is_git || !self.config.submodules {
317             return
318         }
319         let git = || {
320             let mut cmd = Command::new("git");
321             cmd.current_dir(&self.src);
322             return cmd
323         };
324         let git_submodule = || {
325             let mut cmd = Command::new("git");
326             cmd.current_dir(&self.src).arg("submodule");
327             return cmd
328         };
329
330         // FIXME: this takes a seriously long time to execute on Windows and a
331         //        nontrivial amount of time on Unix, we should have a better way
332         //        of detecting whether we need to run all the submodule commands
333         //        below.
334         let out = output(git_submodule().arg("status"));
335         let mut submodules = vec![];
336         for line in out.lines() {
337             // NOTE `git submodule status` output looks like this:
338             //
339             // -5066b7dcab7e700844b0e2ba71b8af9dc627a59b src/liblibc
340             // +b37ef24aa82d2be3a3cc0fe89bf82292f4ca181c src/compiler-rt (remotes/origin/..)
341             //  e058ca661692a8d01f8cf9d35939dfe3105ce968 src/jemalloc (3.6.0-533-ge058ca6)
342             //
343             // The first character can be '-', '+' or ' ' and denotes the `State` of the submodule
344             // Right next to this character is the SHA-1 of the submodule HEAD
345             // And after that comes the path to the submodule
346             let path = Path::new(line[1..].split(' ').skip(1).next().unwrap());
347             let state = if line.starts_with('-') {
348                 State::NotInitialized
349             } else if line.starts_with('+') {
350                 State::OutOfSync
351             } else if line.starts_with(' ') {
352                 State::MaybeDirty
353             } else {
354                 panic!("unexpected git submodule state: {:?}", line.chars().next());
355             };
356
357             submodules.push(Submodule { path: path, state: state })
358         }
359
360         self.run(git_submodule().arg("sync"));
361
362         for submodule in submodules {
363             // If using llvm-root then don't touch the llvm submodule.
364             if submodule.path.components().any(|c| c == Component::Normal("llvm".as_ref())) &&
365                 self.config.target_config.get(&self.config.build)
366                     .and_then(|c| c.llvm_config.as_ref()).is_some()
367             {
368                 continue
369             }
370
371             if submodule.path.components().any(|c| c == Component::Normal("jemalloc".as_ref())) &&
372                 !self.config.use_jemalloc
373             {
374                 continue
375             }
376
377             // `submodule.path` is the relative path to a submodule (from the repository root)
378             // `submodule_path` is the path to a submodule from the cwd
379
380             // use `submodule.path` when e.g. executing a submodule specific command from the
381             // repository root
382             // use `submodule_path` when e.g. executing a normal git command for the submodule
383             // (set via `current_dir`)
384             let submodule_path = self.src.join(submodule.path);
385
386             match submodule.state {
387                 State::MaybeDirty => {
388                     // drop staged changes
389                     self.run(git().current_dir(&submodule_path)
390                                   .args(&["reset", "--hard"]));
391                     // drops unstaged changes
392                     self.run(git().current_dir(&submodule_path)
393                                   .args(&["clean", "-fdx"]));
394                 },
395                 State::NotInitialized => {
396                     self.run(git_submodule().arg("init").arg(submodule.path));
397                     self.run(git_submodule().arg("update").arg(submodule.path));
398                 },
399                 State::OutOfSync => {
400                     // drops submodule commits that weren't reported to the (outer) git repository
401                     self.run(git_submodule().arg("update").arg(submodule.path));
402                     self.run(git().current_dir(&submodule_path)
403                                   .args(&["reset", "--hard"]));
404                     self.run(git().current_dir(&submodule_path)
405                                   .args(&["clean", "-fdx"]));
406                 },
407             }
408         }
409     }
410
411     /// Clear out `dir` if `input` is newer.
412     ///
413     /// After this executes, it will also ensure that `dir` exists.
414     fn clear_if_dirty(&self, dir: &Path, input: &Path) {
415         let stamp = dir.join(".stamp");
416         if mtime(&stamp) < mtime(input) {
417             self.verbose(&format!("Dirty - {}", dir.display()));
418             let _ = fs::remove_dir_all(dir);
419         } else if stamp.exists() {
420             return
421         }
422         t!(fs::create_dir_all(dir));
423         t!(File::create(stamp));
424     }
425
426     /// Prepares an invocation of `cargo` to be run.
427     ///
428     /// This will create a `Command` that represents a pending execution of
429     /// Cargo. This cargo will be configured to use `compiler` as the actual
430     /// rustc compiler, its output will be scoped by `mode`'s output directory,
431     /// it will pass the `--target` flag for the specified `target`, and will be
432     /// executing the Cargo command `cmd`.
433     fn cargo(&self,
434              compiler: &Compiler,
435              mode: Mode,
436              target: &str,
437              cmd: &str) -> Command {
438         let mut cargo = Command::new(&self.cargo);
439         let out_dir = self.stage_out(compiler, mode);
440         cargo.env("CARGO_TARGET_DIR", out_dir)
441              .arg(cmd)
442              .arg("-j").arg(self.jobs().to_string())
443              .arg("--target").arg(target);
444
445         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
446         // Force cargo to output binaries with disambiguating hashes in the name
447         cargo.env("__CARGO_DEFAULT_LIB_METADATA", "1");
448
449         let stage;
450         if compiler.stage == 0 && self.local_rebuild {
451             // Assume the local-rebuild rustc already has stage1 features.
452             stage = 1;
453         } else {
454             stage = compiler.stage;
455         }
456
457         // Customize the compiler we're running. Specify the compiler to cargo
458         // as our shim and then pass it some various options used to configure
459         // how the actual compiler itself is called.
460         //
461         // These variables are primarily all read by
462         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
463         cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
464              .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
465              .env("RUSTC_REAL", self.compiler_path(compiler))
466              .env("RUSTC_STAGE", stage.to_string())
467              .env("RUSTC_CODEGEN_UNITS",
468                   self.config.rust_codegen_units.to_string())
469              .env("RUSTC_DEBUG_ASSERTIONS",
470                   self.config.rust_debug_assertions.to_string())
471              .env("RUSTC_SYSROOT", self.sysroot(compiler))
472              .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
473              .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
474              .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
475              .env("RUSTDOC_REAL", self.rustdoc(compiler))
476              .env("RUSTC_FLAGS", self.rustc_flags(target).join(" "));
477
478         // Tools don't get debuginfo right now, e.g. cargo and rls don't get
479         // compiled with debuginfo.
480         if mode != Mode::Tool {
481              cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string())
482                   .env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string());
483         }
484
485         // Enable usage of unstable features
486         cargo.env("RUSTC_BOOTSTRAP", "1");
487         self.add_rust_test_threads(&mut cargo);
488
489         // Almost all of the crates that we compile as part of the bootstrap may
490         // have a build script, including the standard library. To compile a
491         // build script, however, it itself needs a standard library! This
492         // introduces a bit of a pickle when we're compiling the standard
493         // library itself.
494         //
495         // To work around this we actually end up using the snapshot compiler
496         // (stage0) for compiling build scripts of the standard library itself.
497         // The stage0 compiler is guaranteed to have a libstd available for use.
498         //
499         // For other crates, however, we know that we've already got a standard
500         // library up and running, so we can use the normal compiler to compile
501         // build scripts in that situation.
502         if mode == Mode::Libstd {
503             cargo.env("RUSTC_SNAPSHOT", &self.rustc)
504                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
505         } else {
506             cargo.env("RUSTC_SNAPSHOT", self.compiler_path(compiler))
507                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
508         }
509
510         // There are two invariants we try must maintain:
511         // * stable crates cannot depend on unstable crates (general Rust rule),
512         // * crates that end up in the sysroot must be unstable (rustbuild rule).
513         //
514         // In order to do enforce the latter, we pass the env var
515         // `RUSTBUILD_UNSTABLE` down the line for any crates which will end up
516         // in the sysroot. We read this in bootstrap/bin/rustc.rs and if it is
517         // set, then we pass the `rustbuild` feature to rustc when building the
518         // the crate.
519         //
520         // In turn, crates that can be used here should recognise the `rustbuild`
521         // feature and opt-in to `rustc_private`.
522         //
523         // We can't always pass `rustbuild` because crates which are outside of
524         // the comipiler, libs, and tests are stable and we don't want to make
525         // their deps unstable (since this would break the first invariant
526         // above).
527         if mode != Mode::Tool {
528             cargo.env("RUSTBUILD_UNSTABLE", "1");
529         }
530
531         // Ignore incremental modes except for stage0, since we're
532         // not guaranteeing correctness acros builds if the compiler
533         // is changing under your feet.`
534         if self.flags.incremental && compiler.stage == 0 {
535             let incr_dir = self.incremental_dir(compiler);
536             cargo.env("RUSTC_INCREMENTAL", incr_dir);
537         }
538
539         if let Some(ref on_fail) = self.flags.on_fail {
540             cargo.env("RUSTC_ON_FAIL", on_fail);
541         }
542
543         let verbose = cmp::max(self.config.verbose, self.flags.verbose);
544         cargo.env("RUSTC_VERBOSE", format!("{}", verbose));
545
546         // Specify some various options for build scripts used throughout
547         // the build.
548         //
549         // FIXME: the guard against msvc shouldn't need to be here
550         if !target.contains("msvc") {
551             cargo.env(format!("CC_{}", target), self.cc(target))
552                  .env(format!("AR_{}", target), self.ar(target).unwrap()) // only msvc is None
553                  .env(format!("CFLAGS_{}", target), self.cflags(target).join(" "));
554         }
555
556         if self.config.extended && compiler.is_final_stage(self) {
557             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
558         }
559
560         // When being built Cargo will at some point call `nmake.exe` on Windows
561         // MSVC. Unfortunately `nmake` will read these two environment variables
562         // below and try to intepret them. We're likely being run, however, from
563         // MSYS `make` which uses the same variables.
564         //
565         // As a result, to prevent confusion and errors, we remove these
566         // variables from our environment to prevent passing MSYS make flags to
567         // nmake, causing it to blow up.
568         if cfg!(target_env = "msvc") {
569             cargo.env_remove("MAKE");
570             cargo.env_remove("MAKEFLAGS");
571         }
572
573         // Environment variables *required* needed throughout the build
574         //
575         // FIXME: should update code to not require this env var
576         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
577
578         if self.config.verbose() || self.flags.verbose() {
579             cargo.arg("-v");
580         }
581         // FIXME: cargo bench does not accept `--release`
582         if self.config.rust_optimize && cmd != "bench" {
583             cargo.arg("--release");
584         }
585         if self.config.locked_deps {
586             cargo.arg("--locked");
587         }
588         if self.config.vendor || self.is_sudo {
589             cargo.arg("--frozen");
590         }
591         return cargo
592     }
593
594     /// Get a path to the compiler specified.
595     fn compiler_path(&self, compiler: &Compiler) -> PathBuf {
596         if compiler.is_snapshot(self) {
597             self.rustc.clone()
598         } else {
599             self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
600         }
601     }
602
603     /// Get the specified tool built by the specified compiler
604     fn tool(&self, compiler: &Compiler, tool: &str) -> PathBuf {
605         self.cargo_out(compiler, Mode::Tool, compiler.host)
606             .join(exe(tool, compiler.host))
607     }
608
609     /// Get the `rustdoc` executable next to the specified compiler
610     fn rustdoc(&self, compiler: &Compiler) -> PathBuf {
611         let mut rustdoc = self.compiler_path(compiler);
612         rustdoc.pop();
613         rustdoc.push(exe("rustdoc", compiler.host));
614         return rustdoc
615     }
616
617     /// Get a `Command` which is ready to run `tool` in `stage` built for
618     /// `host`.
619     fn tool_cmd(&self, compiler: &Compiler, tool: &str) -> Command {
620         let mut cmd = Command::new(self.tool(&compiler, tool));
621         self.prepare_tool_cmd(compiler, &mut cmd);
622         return cmd
623     }
624
625     /// Prepares the `cmd` provided to be able to run the `compiler` provided.
626     ///
627     /// Notably this munges the dynamic library lookup path to point to the
628     /// right location to run `compiler`.
629     fn prepare_tool_cmd(&self, compiler: &Compiler, cmd: &mut Command) {
630         let host = compiler.host;
631         let mut paths = vec![
632             self.sysroot_libdir(compiler, compiler.host),
633             self.cargo_out(compiler, Mode::Tool, host).join("deps"),
634         ];
635
636         // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
637         // mode) and that C compiler may need some extra PATH modification. Do
638         // so here.
639         if compiler.host.contains("msvc") {
640             let curpaths = env::var_os("PATH").unwrap_or(OsString::new());
641             let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
642             for &(ref k, ref v) in self.cc[compiler.host].0.env() {
643                 if k != "PATH" {
644                     continue
645                 }
646                 for path in env::split_paths(v) {
647                     if !curpaths.contains(&path) {
648                         paths.push(path);
649                     }
650                 }
651             }
652         }
653         add_lib_path(paths, cmd);
654     }
655
656     /// Get the space-separated set of activated features for the standard
657     /// library.
658     fn std_features(&self) -> String {
659         let mut features = "panic-unwind".to_string();
660
661         if self.config.debug_jemalloc {
662             features.push_str(" debug-jemalloc");
663         }
664         if self.config.use_jemalloc {
665             features.push_str(" jemalloc");
666         }
667         if self.config.backtrace {
668             features.push_str(" backtrace");
669         }
670         return features
671     }
672
673     /// Get the space-separated set of activated features for the compiler.
674     fn rustc_features(&self) -> String {
675         let mut features = String::new();
676         if self.config.use_jemalloc {
677             features.push_str(" jemalloc");
678         }
679         return features
680     }
681
682     /// Component directory that Cargo will produce output into (e.g.
683     /// release/debug)
684     fn cargo_dir(&self) -> &'static str {
685         if self.config.rust_optimize {"release"} else {"debug"}
686     }
687
688     /// Returns the sysroot for the `compiler` specified that *this build system
689     /// generates*.
690     ///
691     /// That is, the sysroot for the stage0 compiler is not what the compiler
692     /// thinks it is by default, but it's the same as the default for stages
693     /// 1-3.
694     fn sysroot(&self, compiler: &Compiler) -> PathBuf {
695         if compiler.stage == 0 {
696             self.out.join(compiler.host).join("stage0-sysroot")
697         } else {
698             self.out.join(compiler.host).join(format!("stage{}", compiler.stage))
699         }
700     }
701
702     /// Get the directory for incremental by-products when using the
703     /// given compiler.
704     fn incremental_dir(&self, compiler: &Compiler) -> PathBuf {
705         self.out.join(compiler.host).join(format!("stage{}-incremental", compiler.stage))
706     }
707
708     /// Returns the libdir where the standard library and other artifacts are
709     /// found for a compiler's sysroot.
710     fn sysroot_libdir(&self, compiler: &Compiler, target: &str) -> PathBuf {
711         self.sysroot(compiler).join("lib").join("rustlib")
712             .join(target).join("lib")
713     }
714
715     /// Returns the root directory for all output generated in a particular
716     /// stage when running with a particular host compiler.
717     ///
718     /// The mode indicates what the root directory is for.
719     fn stage_out(&self, compiler: &Compiler, mode: Mode) -> PathBuf {
720         let suffix = match mode {
721             Mode::Libstd => "-std",
722             Mode::Libtest => "-test",
723             Mode::Tool => "-tools",
724             Mode::Librustc => "-rustc",
725         };
726         self.out.join(compiler.host)
727                 .join(format!("stage{}{}", compiler.stage, suffix))
728     }
729
730     /// Returns the root output directory for all Cargo output in a given stage,
731     /// running a particular comipler, wehther or not we're building the
732     /// standard library, and targeting the specified architecture.
733     fn cargo_out(&self,
734                  compiler: &Compiler,
735                  mode: Mode,
736                  target: &str) -> PathBuf {
737         self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
738     }
739
740     /// Root output directory for LLVM compiled for `target`
741     ///
742     /// Note that if LLVM is configured externally then the directory returned
743     /// will likely be empty.
744     fn llvm_out(&self, target: &str) -> PathBuf {
745         self.out.join(target).join("llvm")
746     }
747
748     /// Output directory for all documentation for a target
749     fn doc_out(&self, target: &str) -> PathBuf {
750         self.out.join(target).join("doc")
751     }
752
753     /// Output directory for all crate documentation for a target (temporary)
754     ///
755     /// The artifacts here are then copied into `doc_out` above.
756     fn crate_doc_out(&self, target: &str) -> PathBuf {
757         self.out.join(target).join("crate-docs")
758     }
759
760     /// Returns true if no custom `llvm-config` is set for the specified target.
761     ///
762     /// If no custom `llvm-config` was specified then Rust's llvm will be used.
763     fn is_rust_llvm(&self, target: &str) -> bool {
764         match self.config.target_config.get(target) {
765             Some(ref c) => c.llvm_config.is_none(),
766             None => true
767         }
768     }
769
770     /// Returns the path to `llvm-config` for the specified target.
771     ///
772     /// If a custom `llvm-config` was specified for target then that's returned
773     /// instead.
774     fn llvm_config(&self, target: &str) -> PathBuf {
775         let target_config = self.config.target_config.get(target);
776         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
777             s.clone()
778         } else {
779             self.llvm_out(&self.config.build).join("bin")
780                 .join(exe("llvm-config", target))
781         }
782     }
783
784     /// Returns the path to `FileCheck` binary for the specified target
785     fn llvm_filecheck(&self, target: &str) -> PathBuf {
786         let target_config = self.config.target_config.get(target);
787         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
788             let llvm_bindir = output(Command::new(s).arg("--bindir"));
789             Path::new(llvm_bindir.trim()).join(exe("FileCheck", target))
790         } else {
791             let base = self.llvm_out(&self.config.build).join("build");
792             let exe = exe("FileCheck", target);
793             if !self.config.ninja && self.config.build.contains("msvc") {
794                 base.join("Release/bin").join(exe)
795             } else {
796                 base.join("bin").join(exe)
797             }
798         }
799     }
800
801     /// Directory for libraries built from C/C++ code and shared between stages.
802     fn native_dir(&self, target: &str) -> PathBuf {
803         self.out.join(target).join("native")
804     }
805
806     /// Root output directory for rust_test_helpers library compiled for
807     /// `target`
808     fn test_helpers_out(&self, target: &str) -> PathBuf {
809         self.native_dir(target).join("rust-test-helpers")
810     }
811
812     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
813     /// library lookup path.
814     fn add_rustc_lib_path(&self, compiler: &Compiler, cmd: &mut Command) {
815         // Windows doesn't need dylib path munging because the dlls for the
816         // compiler live next to the compiler and the system will find them
817         // automatically.
818         if cfg!(windows) {
819             return
820         }
821
822         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
823     }
824
825     /// Adds the `RUST_TEST_THREADS` env var if necessary
826     fn add_rust_test_threads(&self, cmd: &mut Command) {
827         if env::var_os("RUST_TEST_THREADS").is_none() {
828             cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
829         }
830     }
831
832     /// Returns the compiler's libdir where it stores the dynamic libraries that
833     /// it itself links against.
834     ///
835     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
836     /// Windows.
837     fn rustc_libdir(&self, compiler: &Compiler) -> PathBuf {
838         if compiler.is_snapshot(self) {
839             self.rustc_snapshot_libdir()
840         } else {
841             self.sysroot(compiler).join(libdir(compiler.host))
842         }
843     }
844
845     /// Returns the libdir of the snapshot compiler.
846     fn rustc_snapshot_libdir(&self) -> PathBuf {
847         self.rustc.parent().unwrap().parent().unwrap()
848             .join(libdir(&self.config.build))
849     }
850
851     /// Runs a command, printing out nice contextual information if it fails.
852     fn run(&self, cmd: &mut Command) {
853         self.verbose(&format!("running: {:?}", cmd));
854         run_silent(cmd)
855     }
856
857     /// Runs a command, printing out nice contextual information if it fails.
858     fn run_quiet(&self, cmd: &mut Command) {
859         self.verbose(&format!("running: {:?}", cmd));
860         run_suppressed(cmd)
861     }
862
863     /// Prints a message if this build is configured in verbose mode.
864     fn verbose(&self, msg: &str) {
865         if self.flags.verbose() || self.config.verbose() {
866             println!("{}", msg);
867         }
868     }
869
870     /// Returns the number of parallel jobs that have been configured for this
871     /// build.
872     fn jobs(&self) -> u32 {
873         self.flags.jobs.unwrap_or(num_cpus::get() as u32)
874     }
875
876     /// Returns the path to the C compiler for the target specified.
877     fn cc(&self, target: &str) -> &Path {
878         self.cc[target].0.path()
879     }
880
881     /// Returns a list of flags to pass to the C compiler for the target
882     /// specified.
883     fn cflags(&self, target: &str) -> Vec<String> {
884         // Filter out -O and /O (the optimization flags) that we picked up from
885         // gcc-rs because the build scripts will determine that for themselves.
886         let mut base = self.cc[target].0.args().iter()
887                            .map(|s| s.to_string_lossy().into_owned())
888                            .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
889                            .collect::<Vec<_>>();
890
891         // If we're compiling on macOS then we add a few unconditional flags
892         // indicating that we want libc++ (more filled out than libstdc++) and
893         // we want to compile for 10.7. This way we can ensure that
894         // LLVM/jemalloc/etc are all properly compiled.
895         if target.contains("apple-darwin") {
896             base.push("-stdlib=libc++".into());
897         }
898
899         // Work around an apparently bad MinGW / GCC optimization,
900         // See: http://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
901         // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
902         if target == "i686-pc-windows-gnu" {
903             base.push("-fno-omit-frame-pointer".into());
904         }
905         return base
906     }
907
908     /// Returns the path to the `ar` archive utility for the target specified.
909     fn ar(&self, target: &str) -> Option<&Path> {
910         self.cc[target].1.as_ref().map(|p| &**p)
911     }
912
913     /// Returns the path to the C++ compiler for the target specified, may panic
914     /// if no C++ compiler was configured for the target.
915     fn cxx(&self, target: &str) -> &Path {
916         match self.cxx.get(target) {
917             Some(p) => p.path(),
918             None => panic!("\n\ntarget `{}` is not configured as a host,
919                             only as a target\n\n", target),
920         }
921     }
922
923     /// Returns flags to pass to the compiler to generate code for `target`.
924     fn rustc_flags(&self, target: &str) -> Vec<String> {
925         // New flags should be added here with great caution!
926         //
927         // It's quite unfortunate to **require** flags to generate code for a
928         // target, so it should only be passed here if absolutely necessary!
929         // Most default configuration should be done through target specs rather
930         // than an entry here.
931
932         let mut base = Vec::new();
933         if target != self.config.build && !target.contains("msvc") &&
934             !target.contains("emscripten") {
935             base.push(format!("-Clinker={}", self.cc(target).display()));
936         }
937         return base
938     }
939
940     /// Returns the "musl root" for this `target`, if defined
941     fn musl_root(&self, target: &str) -> Option<&Path> {
942         self.config.target_config.get(target)
943             .and_then(|t| t.musl_root.as_ref())
944             .or(self.config.musl_root.as_ref())
945             .map(|p| &**p)
946     }
947
948     /// Returns whether the target will be tested using the `remote-test-client`
949     /// and `remote-test-server` binaries.
950     fn remote_tested(&self, target: &str) -> bool {
951         self.qemu_rootfs(target).is_some() || target.contains("android")
952     }
953
954     /// Returns the root of the "rootfs" image that this target will be using,
955     /// if one was configured.
956     ///
957     /// If `Some` is returned then that means that tests for this target are
958     /// emulated with QEMU and binaries will need to be shipped to the emulator.
959     fn qemu_rootfs(&self, target: &str) -> Option<&Path> {
960         self.config.target_config.get(target)
961             .and_then(|t| t.qemu_rootfs.as_ref())
962             .map(|p| &**p)
963     }
964
965     /// Path to the python interpreter to use
966     fn python(&self) -> &Path {
967         self.config.python.as_ref().unwrap()
968     }
969
970     /// Tests whether the `compiler` compiling for `target` should be forced to
971     /// use a stage1 compiler instead.
972     ///
973     /// Currently, by default, the build system does not perform a "full
974     /// bootstrap" by default where we compile the compiler three times.
975     /// Instead, we compile the compiler two times. The final stage (stage2)
976     /// just copies the libraries from the previous stage, which is what this
977     /// method detects.
978     ///
979     /// Here we return `true` if:
980     ///
981     /// * The build isn't performing a full bootstrap
982     /// * The `compiler` is in the final stage, 2
983     /// * We're not cross-compiling, so the artifacts are already available in
984     ///   stage1
985     ///
986     /// When all of these conditions are met the build will lift artifacts from
987     /// the previous stage forward.
988     fn force_use_stage1(&self, compiler: &Compiler, target: &str) -> bool {
989         !self.config.full_bootstrap &&
990             compiler.stage >= 2 &&
991             self.config.host.iter().any(|h| h == target)
992     }
993
994     /// Returns the directory that OpenSSL artifacts are compiled into if
995     /// configured to do so.
996     fn openssl_dir(&self, target: &str) -> Option<PathBuf> {
997         // OpenSSL not used on Windows
998         if target.contains("windows") {
999             None
1000         } else if self.config.openssl_static {
1001             Some(self.out.join(target).join("openssl"))
1002         } else {
1003             None
1004         }
1005     }
1006
1007     /// Returns the directory that OpenSSL artifacts are installed into if
1008     /// configured as such.
1009     fn openssl_install_dir(&self, target: &str) -> Option<PathBuf> {
1010         self.openssl_dir(target).map(|p| p.join("install"))
1011     }
1012
1013     /// Given `num` in the form "a.b.c" return a "release string" which
1014     /// describes the release version number.
1015     ///
1016     /// For example on nightly this returns "a.b.c-nightly", on beta it returns
1017     /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
1018     fn release(&self, num: &str) -> String {
1019         match &self.config.channel[..] {
1020             "stable" => num.to_string(),
1021             "beta" => format!("{}-beta{}", num, channel::CFG_PRERELEASE_VERSION),
1022             "nightly" => format!("{}-nightly", num),
1023             _ => format!("{}-dev", num),
1024         }
1025     }
1026
1027     /// Returns the value of `release` above for Rust itself.
1028     fn rust_release(&self) -> String {
1029         self.release(channel::CFG_RELEASE_NUM)
1030     }
1031
1032     /// Returns the "package version" for a component given the `num` release
1033     /// number.
1034     ///
1035     /// The package version is typically what shows up in the names of tarballs.
1036     /// For channels like beta/nightly it's just the channel name, otherwise
1037     /// it's the `num` provided.
1038     fn package_vers(&self, num: &str) -> String {
1039         match &self.config.channel[..] {
1040             "stable" => num.to_string(),
1041             "beta" => "beta".to_string(),
1042             "nightly" => "nightly".to_string(),
1043             _ => format!("{}-dev", num),
1044         }
1045     }
1046
1047     /// Returns the value of `package_vers` above for Rust itself.
1048     fn rust_package_vers(&self) -> String {
1049         self.package_vers(channel::CFG_RELEASE_NUM)
1050     }
1051
1052     /// Returns the value of `package_vers` above for Cargo
1053     fn cargo_package_vers(&self) -> String {
1054         self.package_vers(&self.release_num("cargo"))
1055     }
1056
1057     /// Returns the value of `package_vers` above for rls
1058     fn rls_package_vers(&self) -> String {
1059         self.package_vers(&self.release_num("rls"))
1060     }
1061
1062     /// Returns the `version` string associated with this compiler for Rust
1063     /// itself.
1064     ///
1065     /// Note that this is a descriptive string which includes the commit date,
1066     /// sha, version, etc.
1067     fn rust_version(&self) -> String {
1068         self.rust_info.version(self, channel::CFG_RELEASE_NUM)
1069     }
1070
1071     /// Returns the `a.b.c` version that the given package is at.
1072     fn release_num(&self, package: &str) -> String {
1073         let mut toml = String::new();
1074         let toml_file_name = self.src.join(&format!("{}/Cargo.toml", package));
1075         t!(t!(File::open(toml_file_name)).read_to_string(&mut toml));
1076         for line in toml.lines() {
1077             let prefix = "version = \"";
1078             let suffix = "\"";
1079             if line.starts_with(prefix) && line.ends_with(suffix) {
1080                 return line[prefix.len()..line.len() - suffix.len()].to_string()
1081             }
1082         }
1083
1084         panic!("failed to find version in {}'s Cargo.toml", package)
1085     }
1086
1087     /// Returns whether unstable features should be enabled for the compiler
1088     /// we're building.
1089     fn unstable_features(&self) -> bool {
1090         match &self.config.channel[..] {
1091             "stable" | "beta" => false,
1092             "nightly" | _ => true,
1093         }
1094     }
1095 }
1096
1097 impl<'a> Compiler<'a> {
1098     /// Creates a new complier for the specified stage/host
1099     fn new(stage: u32, host: &'a str) -> Compiler<'a> {
1100         Compiler { stage: stage, host: host }
1101     }
1102
1103     /// Returns whether this is a snapshot compiler for `build`'s configuration
1104     fn is_snapshot(&self, build: &Build) -> bool {
1105         self.stage == 0 && self.host == build.config.build
1106     }
1107
1108     /// Returns if this compiler should be treated as a final stage one in the
1109     /// current build session.
1110     /// This takes into account whether we're performing a full bootstrap or
1111     /// not; don't directly compare the stage with `2`!
1112     fn is_final_stage(&self, build: &Build) -> bool {
1113         let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
1114         self.stage >= final_stage
1115     }
1116 }