]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/lib.rs
Rollup merge of #39593 - steveklabnik:bookshelf-landing-page, r=frewsxcv
[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::collections::HashMap;
80 use std::cmp;
81 use std::env;
82 use std::ffi::OsString;
83 use std::fs::{self, File};
84 use std::path::{Component, PathBuf, Path};
85 use std::process::Command;
86
87 use build_helper::{run_silent, output, mtime};
88
89 use util::{exe, libdir, add_lib_path};
90
91 mod cc;
92 mod channel;
93 mod check;
94 mod clean;
95 mod compile;
96 mod metadata;
97 mod config;
98 mod dist;
99 mod doc;
100 mod flags;
101 mod install;
102 mod native;
103 mod sanity;
104 mod step;
105 pub mod util;
106
107 #[cfg(windows)]
108 mod job;
109
110 #[cfg(not(windows))]
111 mod job {
112     pub unsafe fn setup() {}
113 }
114
115 pub use config::Config;
116 pub use flags::{Flags, Subcommand};
117
118 /// A structure representing a Rust compiler.
119 ///
120 /// Each compiler has a `stage` that it is associated with and a `host` that
121 /// corresponds to the platform the compiler runs on. This structure is used as
122 /// a parameter to many methods below.
123 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
124 pub struct Compiler<'a> {
125     stage: u32,
126     host: &'a str,
127 }
128
129 /// Global configuration for the build system.
130 ///
131 /// This structure transitively contains all configuration for the build system.
132 /// All filesystem-encoded configuration is in `config`, all flags are in
133 /// `flags`, and then parsed or probed information is listed in the keys below.
134 ///
135 /// This structure is a parameter of almost all methods in the build system,
136 /// although most functions are implemented as free functions rather than
137 /// methods specifically on this structure itself (to make it easier to
138 /// organize).
139 pub struct Build {
140     // User-specified configuration via config.toml
141     config: Config,
142
143     // User-specified configuration via CLI flags
144     flags: Flags,
145
146     // Derived properties from the above two configurations
147     cargo: PathBuf,
148     rustc: PathBuf,
149     src: PathBuf,
150     out: PathBuf,
151     release: String,
152     unstable_features: bool,
153     ver_hash: Option<String>,
154     short_ver_hash: Option<String>,
155     ver_date: Option<String>,
156     version: String,
157     package_vers: String,
158     local_rebuild: bool,
159     release_num: String,
160     prerelease_version: String,
161
162     // Probed tools at runtime
163     lldb_version: Option<String>,
164     lldb_python_dir: Option<String>,
165
166     // Runtime state filled in later on
167     cc: HashMap<String, (gcc::Tool, Option<PathBuf>)>,
168     cxx: HashMap<String, gcc::Tool>,
169     crates: HashMap<String, Crate>,
170     is_sudo: bool,
171 }
172
173 #[derive(Debug)]
174 struct Crate {
175     name: String,
176     deps: Vec<String>,
177     path: PathBuf,
178     doc_step: String,
179     build_step: String,
180     test_step: String,
181     bench_step: String,
182 }
183
184 /// The various "modes" of invoking Cargo.
185 ///
186 /// These entries currently correspond to the various output directories of the
187 /// build system, with each mod generating output in a different directory.
188 #[derive(Clone, Copy)]
189 pub enum Mode {
190     /// This cargo is going to build the standard library, placing output in the
191     /// "stageN-std" directory.
192     Libstd,
193
194     /// This cargo is going to build libtest, placing output in the
195     /// "stageN-test" directory.
196     Libtest,
197
198     /// This cargo is going to build librustc and compiler libraries, placing
199     /// output in the "stageN-rustc" directory.
200     Librustc,
201
202     /// This cargo is going to some build tool, placing output in the
203     /// "stageN-tools" directory.
204     Tool,
205 }
206
207 impl Build {
208     /// Creates a new set of build configuration from the `flags` on the command
209     /// line and the filesystem `config`.
210     ///
211     /// By default all build output will be placed in the current directory.
212     pub fn new(flags: Flags, config: Config) -> Build {
213         let cwd = t!(env::current_dir());
214         let src = flags.src.clone().or_else(|| {
215             env::var_os("SRC").map(|x| x.into())
216         }).unwrap_or(cwd.clone());
217         let out = cwd.join("build");
218
219         let stage0_root = out.join(&config.build).join("stage0/bin");
220         let rustc = match config.rustc {
221             Some(ref s) => PathBuf::from(s),
222             None => stage0_root.join(exe("rustc", &config.build)),
223         };
224         let cargo = match config.cargo {
225             Some(ref s) => PathBuf::from(s),
226             None => stage0_root.join(exe("cargo", &config.build)),
227         };
228         let local_rebuild = config.local_rebuild;
229
230         let is_sudo = match env::var_os("SUDO_USER") {
231             Some(sudo_user) => {
232                 match env::var_os("USER") {
233                     Some(user) => user != sudo_user,
234                     None => false,
235                 }
236             }
237             None => false,
238         };
239
240         Build {
241             flags: flags,
242             config: config,
243             cargo: cargo,
244             rustc: rustc,
245             src: src,
246             out: out,
247
248             release: String::new(),
249             unstable_features: false,
250             ver_hash: None,
251             short_ver_hash: None,
252             ver_date: None,
253             version: String::new(),
254             local_rebuild: local_rebuild,
255             package_vers: String::new(),
256             cc: HashMap::new(),
257             cxx: HashMap::new(),
258             crates: HashMap::new(),
259             lldb_version: None,
260             lldb_python_dir: None,
261             is_sudo: is_sudo,
262             release_num: String::new(),
263             prerelease_version: String::new(),
264         }
265     }
266
267     /// Executes the entire build, as configured by the flags and configuration.
268     pub fn build(&mut self) {
269         unsafe {
270             job::setup();
271         }
272
273         if let Subcommand::Clean = self.flags.cmd {
274             return clean::clean(self);
275         }
276
277         self.verbose("finding compilers");
278         cc::find(self);
279         self.verbose("running sanity check");
280         sanity::check(self);
281         self.verbose("collecting channel variables");
282         channel::collect(self);
283         // If local-rust is the same major.minor as the current version, then force a local-rebuild
284         let local_version_verbose = output(
285             Command::new(&self.rustc).arg("--version").arg("--verbose"));
286         let local_release = local_version_verbose
287             .lines().filter(|x| x.starts_with("release:"))
288             .next().unwrap().trim_left_matches("release:").trim();
289         if local_release.split('.').take(2).eq(self.release.split('.').take(2)) {
290             self.verbose(&format!("auto-detected local-rebuild {}", local_release));
291             self.local_rebuild = true;
292         }
293         self.verbose("updating submodules");
294         self.update_submodules();
295         self.verbose("learning about cargo");
296         metadata::build(self);
297
298         step::run(self);
299     }
300
301     /// Updates all git submodules that we have.
302     ///
303     /// This will detect if any submodules are out of date an run the necessary
304     /// commands to sync them all with upstream.
305     fn update_submodules(&self) {
306         struct Submodule<'a> {
307             path: &'a Path,
308             state: State,
309         }
310
311         enum State {
312             // The submodule may have staged/unstaged changes
313             MaybeDirty,
314             // Or could be initialized but never updated
315             NotInitialized,
316             // The submodule, itself, has extra commits but those changes haven't been commited to
317             // the (outer) git repository
318             OutOfSync,
319         }
320
321         if !self.config.submodules {
322             return
323         }
324         if fs::metadata(self.src.join(".git")).is_err() {
325             return
326         }
327         let git = || {
328             let mut cmd = Command::new("git");
329             cmd.current_dir(&self.src);
330             return cmd
331         };
332         let git_submodule = || {
333             let mut cmd = Command::new("git");
334             cmd.current_dir(&self.src).arg("submodule");
335             return cmd
336         };
337
338         // FIXME: this takes a seriously long time to execute on Windows and a
339         //        nontrivial amount of time on Unix, we should have a better way
340         //        of detecting whether we need to run all the submodule commands
341         //        below.
342         let out = output(git_submodule().arg("status"));
343         let mut submodules = vec![];
344         for line in out.lines() {
345             // NOTE `git submodule status` output looks like this:
346             //
347             // -5066b7dcab7e700844b0e2ba71b8af9dc627a59b src/liblibc
348             // +b37ef24aa82d2be3a3cc0fe89bf82292f4ca181c src/compiler-rt (remotes/origin/..)
349             //  e058ca661692a8d01f8cf9d35939dfe3105ce968 src/jemalloc (3.6.0-533-ge058ca6)
350             //
351             // The first character can be '-', '+' or ' ' and denotes the `State` of the submodule
352             // Right next to this character is the SHA-1 of the submodule HEAD
353             // And after that comes the path to the submodule
354             let path = Path::new(line[1..].split(' ').skip(1).next().unwrap());
355             let state = if line.starts_with('-') {
356                 State::NotInitialized
357             } else if line.starts_with('+') {
358                 State::OutOfSync
359             } else if line.starts_with(' ') {
360                 State::MaybeDirty
361             } else {
362                 panic!("unexpected git submodule state: {:?}", line.chars().next());
363             };
364
365             submodules.push(Submodule { path: path, state: state })
366         }
367
368         self.run(git_submodule().arg("sync"));
369
370         for submodule in submodules {
371             // If using llvm-root then don't touch the llvm submodule.
372             if submodule.path.components().any(|c| c == Component::Normal("llvm".as_ref())) &&
373                 self.config.target_config.get(&self.config.build)
374                     .and_then(|c| c.llvm_config.as_ref()).is_some()
375             {
376                 continue
377             }
378
379             if submodule.path.components().any(|c| c == Component::Normal("jemalloc".as_ref())) &&
380                 !self.config.use_jemalloc
381             {
382                 continue
383             }
384
385             // `submodule.path` is the relative path to a submodule (from the repository root)
386             // `submodule_path` is the path to a submodule from the cwd
387
388             // use `submodule.path` when e.g. executing a submodule specific command from the
389             // repository root
390             // use `submodule_path` when e.g. executing a normal git command for the submodule
391             // (set via `current_dir`)
392             let submodule_path = self.src.join(submodule.path);
393
394             match submodule.state {
395                 State::MaybeDirty => {
396                     // drop staged changes
397                     self.run(git().current_dir(&submodule_path)
398                                   .args(&["reset", "--hard"]));
399                     // drops unstaged changes
400                     self.run(git().current_dir(&submodule_path)
401                                   .args(&["clean", "-fdx"]));
402                 },
403                 State::NotInitialized => {
404                     self.run(git_submodule().arg("init").arg(submodule.path));
405                     self.run(git_submodule().arg("update").arg(submodule.path));
406                 },
407                 State::OutOfSync => {
408                     // drops submodule commits that weren't reported to the (outer) git repository
409                     self.run(git_submodule().arg("update").arg(submodule.path));
410                     self.run(git().current_dir(&submodule_path)
411                                   .args(&["reset", "--hard"]));
412                     self.run(git().current_dir(&submodule_path)
413                                   .args(&["clean", "-fdx"]));
414                 },
415             }
416         }
417     }
418
419     /// Clear out `dir` if `input` is newer.
420     ///
421     /// After this executes, it will also ensure that `dir` exists.
422     fn clear_if_dirty(&self, dir: &Path, input: &Path) {
423         let stamp = dir.join(".stamp");
424         if mtime(&stamp) < mtime(input) {
425             self.verbose(&format!("Dirty - {}", dir.display()));
426             let _ = fs::remove_dir_all(dir);
427         } else if stamp.exists() {
428             return
429         }
430         t!(fs::create_dir_all(dir));
431         t!(File::create(stamp));
432     }
433
434     /// Prepares an invocation of `cargo` to be run.
435     ///
436     /// This will create a `Command` that represents a pending execution of
437     /// Cargo. This cargo will be configured to use `compiler` as the actual
438     /// rustc compiler, its output will be scoped by `mode`'s output directory,
439     /// it will pass the `--target` flag for the specified `target`, and will be
440     /// executing the Cargo command `cmd`.
441     fn cargo(&self,
442              compiler: &Compiler,
443              mode: Mode,
444              target: &str,
445              cmd: &str) -> Command {
446         let mut cargo = Command::new(&self.cargo);
447         let out_dir = self.stage_out(compiler, mode);
448         cargo.env("CARGO_TARGET_DIR", out_dir)
449              .arg(cmd)
450              .arg("-j").arg(self.jobs().to_string())
451              .arg("--target").arg(target);
452
453         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
454         // Force cargo to output binaries with disambiguating hashes in the name
455         cargo.env("__CARGO_DEFAULT_LIB_METADATA", "1");
456
457         let stage;
458         if compiler.stage == 0 && self.local_rebuild {
459             // Assume the local-rebuild rustc already has stage1 features.
460             stage = 1;
461         } else {
462             stage = compiler.stage;
463         }
464
465         // Customize the compiler we're running. Specify the compiler to cargo
466         // as our shim and then pass it some various options used to configure
467         // how the actual compiler itself is called.
468         //
469         // These variables are primarily all read by
470         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
471         cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
472              .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
473              .env("RUSTC_REAL", self.compiler_path(compiler))
474              .env("RUSTC_STAGE", stage.to_string())
475              .env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string())
476              .env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string())
477              .env("RUSTC_CODEGEN_UNITS",
478                   self.config.rust_codegen_units.to_string())
479              .env("RUSTC_DEBUG_ASSERTIONS",
480                   self.config.rust_debug_assertions.to_string())
481              .env("RUSTC_SNAPSHOT", &self.rustc)
482              .env("RUSTC_SYSROOT", self.sysroot(compiler))
483              .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
484              .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir())
485              .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
486              .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
487              .env("RUSTDOC_REAL", self.rustdoc(compiler))
488              .env("RUSTC_FLAGS", self.rustc_flags(target).join(" "));
489
490         // Enable usage of unstable features
491         cargo.env("RUSTC_BOOTSTRAP", "1");
492         self.add_rust_test_threads(&mut cargo);
493
494         // Ignore incremental modes except for stage0, since we're
495         // not guaranteeing correctness acros builds if the compiler
496         // is changing under your feet.`
497         if self.flags.incremental && compiler.stage == 0 {
498             let incr_dir = self.incremental_dir(compiler);
499             cargo.env("RUSTC_INCREMENTAL", incr_dir);
500         }
501
502         let verbose = cmp::max(self.config.verbose, self.flags.verbose);
503         cargo.env("RUSTC_VERBOSE", format!("{}", verbose));
504
505         // Specify some various options for build scripts used throughout
506         // the build.
507         //
508         // FIXME: the guard against msvc shouldn't need to be here
509         if !target.contains("msvc") {
510             cargo.env(format!("CC_{}", target), self.cc(target))
511                  .env(format!("AR_{}", target), self.ar(target).unwrap()) // only msvc is None
512                  .env(format!("CFLAGS_{}", target), self.cflags(target).join(" "));
513         }
514
515         if self.config.channel == "nightly" && compiler.is_final_stage(self) {
516             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
517         }
518
519         // Environment variables *required* needed throughout the build
520         //
521         // FIXME: should update code to not require this env var
522         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
523
524         if self.config.verbose() || self.flags.verbose() {
525             cargo.arg("-v");
526         }
527         // FIXME: cargo bench does not accept `--release`
528         if self.config.rust_optimize && cmd != "bench" {
529             cargo.arg("--release");
530         }
531         if self.config.vendor || self.is_sudo {
532             cargo.arg("--frozen");
533         }
534         return cargo
535     }
536
537     /// Get a path to the compiler specified.
538     fn compiler_path(&self, compiler: &Compiler) -> PathBuf {
539         if compiler.is_snapshot(self) {
540             self.rustc.clone()
541         } else {
542             self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
543         }
544     }
545
546     /// Get the specified tool built by the specified compiler
547     fn tool(&self, compiler: &Compiler, tool: &str) -> PathBuf {
548         self.cargo_out(compiler, Mode::Tool, compiler.host)
549             .join(exe(tool, compiler.host))
550     }
551
552     /// Get the `rustdoc` executable next to the specified compiler
553     fn rustdoc(&self, compiler: &Compiler) -> PathBuf {
554         let mut rustdoc = self.compiler_path(compiler);
555         rustdoc.pop();
556         rustdoc.push(exe("rustdoc", compiler.host));
557         return rustdoc
558     }
559
560     /// Get a `Command` which is ready to run `tool` in `stage` built for
561     /// `host`.
562     fn tool_cmd(&self, compiler: &Compiler, tool: &str) -> Command {
563         let mut cmd = Command::new(self.tool(&compiler, tool));
564         self.prepare_tool_cmd(compiler, &mut cmd);
565         return cmd
566     }
567
568     /// Prepares the `cmd` provided to be able to run the `compiler` provided.
569     ///
570     /// Notably this munges the dynamic library lookup path to point to the
571     /// right location to run `compiler`.
572     fn prepare_tool_cmd(&self, compiler: &Compiler, cmd: &mut Command) {
573         let host = compiler.host;
574         let mut paths = vec![
575             self.sysroot_libdir(compiler, compiler.host),
576             self.cargo_out(compiler, Mode::Tool, host).join("deps"),
577         ];
578
579         // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
580         // mode) and that C compiler may need some extra PATH modification. Do
581         // so here.
582         if compiler.host.contains("msvc") {
583             let curpaths = env::var_os("PATH").unwrap_or(OsString::new());
584             let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
585             for &(ref k, ref v) in self.cc[compiler.host].0.env() {
586                 if k != "PATH" {
587                     continue
588                 }
589                 for path in env::split_paths(v) {
590                     if !curpaths.contains(&path) {
591                         paths.push(path);
592                     }
593                 }
594             }
595         }
596         add_lib_path(paths, cmd);
597     }
598
599     /// Get the space-separated set of activated features for the standard
600     /// library.
601     fn std_features(&self) -> String {
602         let mut features = "panic-unwind".to_string();
603         if self.config.debug_jemalloc {
604             features.push_str(" debug-jemalloc");
605         }
606         if self.config.use_jemalloc {
607             features.push_str(" jemalloc");
608         }
609         if self.config.backtrace {
610             features.push_str(" backtrace");
611         }
612         return features
613     }
614
615     /// Get the space-separated set of activated features for the compiler.
616     fn rustc_features(&self) -> String {
617         let mut features = String::new();
618         if self.config.use_jemalloc {
619             features.push_str(" jemalloc");
620         }
621         return features
622     }
623
624     /// Component directory that Cargo will produce output into (e.g.
625     /// release/debug)
626     fn cargo_dir(&self) -> &'static str {
627         if self.config.rust_optimize {"release"} else {"debug"}
628     }
629
630     /// Returns the sysroot for the `compiler` specified that *this build system
631     /// generates*.
632     ///
633     /// That is, the sysroot for the stage0 compiler is not what the compiler
634     /// thinks it is by default, but it's the same as the default for stages
635     /// 1-3.
636     fn sysroot(&self, compiler: &Compiler) -> PathBuf {
637         if compiler.stage == 0 {
638             self.out.join(compiler.host).join("stage0-sysroot")
639         } else {
640             self.out.join(compiler.host).join(format!("stage{}", compiler.stage))
641         }
642     }
643
644     /// Get the directory for incremental by-products when using the
645     /// given compiler.
646     fn incremental_dir(&self, compiler: &Compiler) -> PathBuf {
647         self.out.join(compiler.host).join(format!("stage{}-incremental", compiler.stage))
648     }
649
650     /// Returns the libdir where the standard library and other artifacts are
651     /// found for a compiler's sysroot.
652     fn sysroot_libdir(&self, compiler: &Compiler, target: &str) -> PathBuf {
653         self.sysroot(compiler).join("lib").join("rustlib")
654             .join(target).join("lib")
655     }
656
657     /// Returns the root directory for all output generated in a particular
658     /// stage when running with a particular host compiler.
659     ///
660     /// The mode indicates what the root directory is for.
661     fn stage_out(&self, compiler: &Compiler, mode: Mode) -> PathBuf {
662         let suffix = match mode {
663             Mode::Libstd => "-std",
664             Mode::Libtest => "-test",
665             Mode::Tool => "-tools",
666             Mode::Librustc => "-rustc",
667         };
668         self.out.join(compiler.host)
669                 .join(format!("stage{}{}", compiler.stage, suffix))
670     }
671
672     /// Returns the root output directory for all Cargo output in a given stage,
673     /// running a particular comipler, wehther or not we're building the
674     /// standard library, and targeting the specified architecture.
675     fn cargo_out(&self,
676                  compiler: &Compiler,
677                  mode: Mode,
678                  target: &str) -> PathBuf {
679         self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
680     }
681
682     /// Root output directory for LLVM compiled for `target`
683     ///
684     /// Note that if LLVM is configured externally then the directory returned
685     /// will likely be empty.
686     fn llvm_out(&self, target: &str) -> PathBuf {
687         self.out.join(target).join("llvm")
688     }
689
690     /// Output directory for all documentation for a target
691     fn doc_out(&self, target: &str) -> PathBuf {
692         self.out.join(target).join("doc")
693     }
694
695     /// Returns true if no custom `llvm-config` is set for the specified target.
696     ///
697     /// If no custom `llvm-config` was specified then Rust's llvm will be used.
698     fn is_rust_llvm(&self, target: &str) -> bool {
699         match self.config.target_config.get(target) {
700             Some(ref c) => c.llvm_config.is_none(),
701             None => true
702         }
703     }
704
705     /// Returns the path to `llvm-config` for the specified target.
706     ///
707     /// If a custom `llvm-config` was specified for target then that's returned
708     /// instead.
709     fn llvm_config(&self, target: &str) -> PathBuf {
710         let target_config = self.config.target_config.get(target);
711         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
712             s.clone()
713         } else {
714             self.llvm_out(&self.config.build).join("bin")
715                 .join(exe("llvm-config", target))
716         }
717     }
718
719     /// Returns the path to `FileCheck` binary for the specified target
720     fn llvm_filecheck(&self, target: &str) -> PathBuf {
721         let target_config = self.config.target_config.get(target);
722         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
723             let llvm_bindir = output(Command::new(s).arg("--bindir"));
724             Path::new(llvm_bindir.trim()).join(exe("FileCheck", target))
725         } else {
726             let base = self.llvm_out(&self.config.build).join("build");
727             let exe = exe("FileCheck", target);
728             if self.config.build.contains("msvc") {
729                 base.join("Release/bin").join(exe)
730             } else {
731                 base.join("bin").join(exe)
732             }
733         }
734     }
735
736     /// Directory for libraries built from C/C++ code and shared between stages.
737     fn native_dir(&self, target: &str) -> PathBuf {
738         self.out.join(target).join("native")
739     }
740
741     /// Root output directory for rust_test_helpers library compiled for
742     /// `target`
743     fn test_helpers_out(&self, target: &str) -> PathBuf {
744         self.native_dir(target).join("rust-test-helpers")
745     }
746
747     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
748     /// library lookup path.
749     fn add_rustc_lib_path(&self, compiler: &Compiler, cmd: &mut Command) {
750         // Windows doesn't need dylib path munging because the dlls for the
751         // compiler live next to the compiler and the system will find them
752         // automatically.
753         if cfg!(windows) {
754             return
755         }
756
757         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
758     }
759
760     /// Adds the `RUST_TEST_THREADS` env var if necessary
761     fn add_rust_test_threads(&self, cmd: &mut Command) {
762         if env::var_os("RUST_TEST_THREADS").is_none() {
763             cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
764         }
765     }
766
767     /// Returns the compiler's libdir where it stores the dynamic libraries that
768     /// it itself links against.
769     ///
770     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
771     /// Windows.
772     fn rustc_libdir(&self, compiler: &Compiler) -> PathBuf {
773         if compiler.is_snapshot(self) {
774             self.rustc_snapshot_libdir()
775         } else {
776             self.sysroot(compiler).join(libdir(compiler.host))
777         }
778     }
779
780     /// Returns the libdir of the snapshot compiler.
781     fn rustc_snapshot_libdir(&self) -> PathBuf {
782         self.rustc.parent().unwrap().parent().unwrap()
783             .join(libdir(&self.config.build))
784     }
785
786     /// Runs a command, printing out nice contextual information if it fails.
787     fn run(&self, cmd: &mut Command) {
788         self.verbose(&format!("running: {:?}", cmd));
789         run_silent(cmd)
790     }
791
792     /// Prints a message if this build is configured in verbose mode.
793     fn verbose(&self, msg: &str) {
794         if self.flags.verbose() || self.config.verbose() {
795             println!("{}", msg);
796         }
797     }
798
799     /// Returns the number of parallel jobs that have been configured for this
800     /// build.
801     fn jobs(&self) -> u32 {
802         self.flags.jobs.unwrap_or(num_cpus::get() as u32)
803     }
804
805     /// Returns the path to the C compiler for the target specified.
806     fn cc(&self, target: &str) -> &Path {
807         self.cc[target].0.path()
808     }
809
810     /// Returns a list of flags to pass to the C compiler for the target
811     /// specified.
812     fn cflags(&self, target: &str) -> Vec<String> {
813         // Filter out -O and /O (the optimization flags) that we picked up from
814         // gcc-rs because the build scripts will determine that for themselves.
815         let mut base = self.cc[target].0.args().iter()
816                            .map(|s| s.to_string_lossy().into_owned())
817                            .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
818                            .collect::<Vec<_>>();
819
820         // If we're compiling on OSX then we add a few unconditional flags
821         // indicating that we want libc++ (more filled out than libstdc++) and
822         // we want to compile for 10.7. This way we can ensure that
823         // LLVM/jemalloc/etc are all properly compiled.
824         if target.contains("apple-darwin") {
825             base.push("-stdlib=libc++".into());
826         }
827         // This is a hack, because newer binutils broke things on some vms/distros
828         // (i.e., linking against unknown relocs disabled by the following flag)
829         // See: https://github.com/rust-lang/rust/issues/34978
830         match target {
831             "i586-unknown-linux-gnu" |
832             "i686-unknown-linux-musl" |
833             "x86_64-unknown-linux-musl" => {
834                 base.push("-Wa,-mrelax-relocations=no".into());
835             },
836             _ => {},
837         }
838         return base
839     }
840
841     /// Returns the path to the `ar` archive utility for the target specified.
842     fn ar(&self, target: &str) -> Option<&Path> {
843         self.cc[target].1.as_ref().map(|p| &**p)
844     }
845
846     /// Returns the path to the C++ compiler for the target specified, may panic
847     /// if no C++ compiler was configured for the target.
848     fn cxx(&self, target: &str) -> &Path {
849         match self.cxx.get(target) {
850             Some(p) => p.path(),
851             None => panic!("\n\ntarget `{}` is not configured as a host,
852                             only as a target\n\n", target),
853         }
854     }
855
856     /// Returns flags to pass to the compiler to generate code for `target`.
857     fn rustc_flags(&self, target: &str) -> Vec<String> {
858         // New flags should be added here with great caution!
859         //
860         // It's quite unfortunate to **require** flags to generate code for a
861         // target, so it should only be passed here if absolutely necessary!
862         // Most default configuration should be done through target specs rather
863         // than an entry here.
864
865         let mut base = Vec::new();
866         if target != self.config.build && !target.contains("msvc") &&
867             !target.contains("emscripten") {
868             base.push(format!("-Clinker={}", self.cc(target).display()));
869         }
870         return base
871     }
872
873     /// Returns the "musl root" for this `target`, if defined
874     fn musl_root(&self, target: &str) -> Option<&Path> {
875         self.config.target_config.get(target)
876             .and_then(|t| t.musl_root.as_ref())
877             .or(self.config.musl_root.as_ref())
878             .map(|p| &**p)
879     }
880
881     /// Returns the root of the "rootfs" image that this target will be using,
882     /// if one was configured.
883     ///
884     /// If `Some` is returned then that means that tests for this target are
885     /// emulated with QEMU and binaries will need to be shipped to the emulator.
886     fn qemu_rootfs(&self, target: &str) -> Option<&Path> {
887         self.config.target_config.get(target)
888             .and_then(|t| t.qemu_rootfs.as_ref())
889             .map(|p| &**p)
890     }
891
892     /// Path to the python interpreter to use
893     fn python(&self) -> &Path {
894         self.config.python.as_ref().unwrap()
895     }
896
897     /// Tests whether the `compiler` compiling for `target` should be forced to
898     /// use a stage1 compiler instead.
899     ///
900     /// Currently, by default, the build system does not perform a "full
901     /// bootstrap" by default where we compile the compiler three times.
902     /// Instead, we compile the compiler two times. The final stage (stage2)
903     /// just copies the libraries from the previous stage, which is what this
904     /// method detects.
905     ///
906     /// Here we return `true` if:
907     ///
908     /// * The build isn't performing a full bootstrap
909     /// * The `compiler` is in the final stage, 2
910     /// * We're not cross-compiling, so the artifacts are already available in
911     ///   stage1
912     ///
913     /// When all of these conditions are met the build will lift artifacts from
914     /// the previous stage forward.
915     fn force_use_stage1(&self, compiler: &Compiler, target: &str) -> bool {
916         !self.config.full_bootstrap &&
917             compiler.stage >= 2 &&
918             self.config.host.iter().any(|h| h == target)
919     }
920 }
921
922 impl<'a> Compiler<'a> {
923     /// Creates a new complier for the specified stage/host
924     fn new(stage: u32, host: &'a str) -> Compiler<'a> {
925         Compiler { stage: stage, host: host }
926     }
927
928     /// Returns whether this is a snapshot compiler for `build`'s configuration
929     fn is_snapshot(&self, build: &Build) -> bool {
930         self.stage == 0 && self.host == build.config.build
931     }
932
933     /// Returns if this compiler should be treated as a final stage one in the
934     /// current build session.
935     /// This takes into account whether we're performing a full bootstrap or
936     /// not; don't directly compare the stage with `2`!
937     fn is_final_stage(&self, build: &Build) -> bool {
938         let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
939         self.stage >= final_stage
940     }
941 }