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