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