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