]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/lib.rs
943271fc8a641665734531b3393b32d4f37d1e5e
[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.
17 //!
18 //! More documentation can be found in each respective module below.
19
20 extern crate build_helper;
21 extern crate cmake;
22 extern crate filetime;
23 extern crate gcc;
24 extern crate getopts;
25 extern crate md5;
26 extern crate num_cpus;
27 extern crate rustc_serialize;
28 extern crate toml;
29
30 use std::cell::RefCell;
31 use std::collections::HashMap;
32 use std::env;
33 use std::fs::{self, File};
34 use std::path::{PathBuf, Path};
35 use std::process::Command;
36
37 use build_helper::{run_silent, output};
38
39 use util::{exe, mtime, libdir, add_lib_path};
40
41 /// A helper macro to `unwrap` a result except also print out details like:
42 ///
43 /// * The file/line of the panic
44 /// * The expression that failed
45 /// * The error itself
46 ///
47 /// This is currently used judiciously throughout the build system rather than
48 /// using a `Result` with `try!`, but this may change on day...
49 macro_rules! t {
50     ($e:expr) => (match $e {
51         Ok(e) => e,
52         Err(e) => panic!("{} failed with {}", stringify!($e), e),
53     })
54 }
55
56 mod cc;
57 mod channel;
58 mod check;
59 mod clean;
60 mod compile;
61 mod config;
62 mod dist;
63 mod doc;
64 mod flags;
65 mod native;
66 mod sanity;
67 mod step;
68 pub mod util;
69
70 #[cfg(windows)]
71 mod job;
72
73 #[cfg(not(windows))]
74 mod job {
75     pub unsafe fn setup() {}
76 }
77
78 pub use config::Config;
79 pub use flags::Flags;
80
81 /// A structure representing a Rust compiler.
82 ///
83 /// Each compiler has a `stage` that it is associated with and a `host` that
84 /// corresponds to the platform the compiler runs on. This structure is used as
85 /// a parameter to many methods below.
86 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
87 pub struct Compiler<'a> {
88     stage: u32,
89     host: &'a str,
90 }
91
92 /// Global configuration for the build system.
93 ///
94 /// This structure transitively contains all configuration for the build system.
95 /// All filesystem-encoded configuration is in `config`, all flags are in
96 /// `flags`, and then parsed or probed information is listed in the keys below.
97 ///
98 /// This structure is a parameter of almost all methods in the build system,
99 /// although most functions are implemented as free functions rather than
100 /// methods specifically on this structure itself (to make it easier to
101 /// organize).
102 pub struct Build {
103     // User-specified configuration via config.toml
104     config: Config,
105
106     // User-specified configuration via CLI flags
107     flags: Flags,
108
109     // Derived properties from the above two configurations
110     cargo: PathBuf,
111     rustc: PathBuf,
112     src: PathBuf,
113     out: PathBuf,
114     release: String,
115     unstable_features: bool,
116     ver_hash: Option<String>,
117     short_ver_hash: Option<String>,
118     ver_date: Option<String>,
119     version: String,
120     package_vers: String,
121     bootstrap_key: String,
122     bootstrap_key_stage0: String,
123
124     // Probed tools at runtime
125     gdb_version: Option<String>,
126     lldb_version: Option<String>,
127     lldb_python_dir: Option<String>,
128
129     // Runtime state filled in later on
130     cc: HashMap<String, (gcc::Tool, Option<PathBuf>)>,
131     cxx: HashMap<String, gcc::Tool>,
132     compiler_rt_built: RefCell<HashMap<String, PathBuf>>,
133 }
134
135 /// The various "modes" of invoking Cargo.
136 ///
137 /// These entries currently correspond to the various output directories of the
138 /// build system, with each mod generating output in a different directory.
139 #[derive(Clone, Copy)]
140 pub enum Mode {
141     /// This cargo is going to build the standard library, placing output in the
142     /// "stageN-std" directory.
143     Libstd,
144
145     /// This cargo is going to build libtest, placing output in the
146     /// "stageN-test" directory.
147     Libtest,
148
149     /// This cargo is going to build librustc and compiler libraries, placing
150     /// output in the "stageN-rustc" directory.
151     Librustc,
152
153     /// This cargo is going to some build tool, placing output in the
154     /// "stageN-tools" directory.
155     Tool,
156 }
157
158 impl Build {
159     /// Creates a new set of build configuration from the `flags` on the command
160     /// line and the filesystem `config`.
161     ///
162     /// By default all build output will be placed in the current directory.
163     pub fn new(flags: Flags, config: Config) -> Build {
164         let cwd = t!(env::current_dir());
165         let src = flags.src.clone().unwrap_or(cwd.clone());
166         let out = cwd.join("build");
167
168         let stage0_root = out.join(&config.build).join("stage0/bin");
169         let rustc = match config.rustc {
170             Some(ref s) => PathBuf::from(s),
171             None => stage0_root.join(exe("rustc", &config.build)),
172         };
173         let cargo = match config.cargo {
174             Some(ref s) => PathBuf::from(s),
175             None => stage0_root.join(exe("cargo", &config.build)),
176         };
177
178         Build {
179             flags: flags,
180             config: config,
181             cargo: cargo,
182             rustc: rustc,
183             src: src,
184             out: out,
185
186             release: String::new(),
187             unstable_features: false,
188             ver_hash: None,
189             short_ver_hash: None,
190             ver_date: None,
191             version: String::new(),
192             bootstrap_key: String::new(),
193             bootstrap_key_stage0: String::new(),
194             package_vers: String::new(),
195             cc: HashMap::new(),
196             cxx: HashMap::new(),
197             compiler_rt_built: RefCell::new(HashMap::new()),
198             gdb_version: None,
199             lldb_version: None,
200             lldb_python_dir: None,
201         }
202     }
203
204     /// Executes the entire build, as configured by the flags and configuration.
205     pub fn build(&mut self) {
206         use step::Source::*;
207
208         unsafe {
209             job::setup();
210         }
211
212         if self.flags.clean {
213             return clean::clean(self);
214         }
215
216         self.verbose("finding compilers");
217         cc::find(self);
218         self.verbose("running sanity check");
219         sanity::check(self);
220         self.verbose("collecting channel variables");
221         channel::collect(self);
222         self.verbose("updating submodules");
223         self.update_submodules();
224
225         // The main loop of the build system.
226         //
227         // The `step::all` function returns a topographically sorted list of all
228         // steps that need to be executed as part of this build. Each step has a
229         // corresponding entry in `step.rs` and indicates some unit of work that
230         // needs to be done as part of the build.
231         //
232         // Almost all of these are simple one-liners that shell out to the
233         // corresponding functionality in the extra modules, where more
234         // documentation can be found.
235         for target in step::all(self) {
236             let doc_out = self.out.join(&target.target).join("doc");
237             match target.src {
238                 Llvm { _dummy } => {
239                     native::llvm(self, target.target);
240                 }
241                 CompilerRt { _dummy } => {
242                     native::compiler_rt(self, target.target);
243                 }
244                 TestHelpers { _dummy } => {
245                     native::test_helpers(self, target.target);
246                 }
247                 Libstd { compiler } => {
248                     compile::std(self, target.target, &compiler);
249                 }
250                 Libtest { compiler } => {
251                     compile::test(self, target.target, &compiler);
252                 }
253                 Librustc { compiler } => {
254                     compile::rustc(self, target.target, &compiler);
255                 }
256                 LibstdLink { compiler, host } => {
257                     compile::std_link(self, target.target, &compiler, host);
258                 }
259                 LibtestLink { compiler, host } => {
260                     compile::test_link(self, target.target, &compiler, host);
261                 }
262                 LibrustcLink { compiler, host } => {
263                     compile::rustc_link(self, target.target, &compiler, host);
264                 }
265                 Rustc { stage: 0 } => {
266                     // nothing to do...
267                 }
268                 Rustc { stage } => {
269                     compile::assemble_rustc(self, stage, target.target);
270                 }
271                 ToolLinkchecker { stage } => {
272                     compile::tool(self, stage, target.target, "linkchecker");
273                 }
274                 ToolRustbook { stage } => {
275                     compile::tool(self, stage, target.target, "rustbook");
276                 }
277                 ToolErrorIndex { stage } => {
278                     compile::tool(self, stage, target.target,
279                                   "error_index_generator");
280                 }
281                 ToolCargoTest { stage } => {
282                     compile::tool(self, stage, target.target, "cargotest");
283                 }
284                 ToolTidy { stage } => {
285                     compile::tool(self, stage, target.target, "tidy");
286                 }
287                 ToolCompiletest { stage } => {
288                     compile::tool(self, stage, target.target, "compiletest");
289                 }
290                 DocBook { stage } => {
291                     doc::rustbook(self, stage, target.target, "book", &doc_out);
292                 }
293                 DocNomicon { stage } => {
294                     doc::rustbook(self, stage, target.target, "nomicon",
295                                   &doc_out);
296                 }
297                 DocStyle { stage } => {
298                     doc::rustbook(self, stage, target.target, "style",
299                                   &doc_out);
300                 }
301                 DocStandalone { stage } => {
302                     doc::standalone(self, stage, target.target, &doc_out);
303                 }
304                 DocStd { stage } => {
305                     doc::std(self, stage, target.target, &doc_out);
306                 }
307                 DocTest { stage } => {
308                     doc::test(self, stage, target.target, &doc_out);
309                 }
310                 DocRustc { stage } => {
311                     doc::rustc(self, stage, target.target, &doc_out);
312                 }
313                 DocErrorIndex { stage } => {
314                     doc::error_index(self, stage, target.target, &doc_out);
315                 }
316
317                 CheckLinkcheck { stage } => {
318                     check::linkcheck(self, stage, target.target);
319                 }
320                 CheckCargoTest { stage } => {
321                     check::cargotest(self, stage, target.target);
322                 }
323                 CheckTidy { stage } => {
324                     check::tidy(self, stage, target.target);
325                 }
326                 CheckRPass { compiler } => {
327                     check::compiletest(self, &compiler, target.target,
328                                        "run-pass", "run-pass");
329                 }
330                 CheckRPassFull { compiler } => {
331                     check::compiletest(self, &compiler, target.target,
332                                        "run-pass", "run-pass-fulldeps");
333                 }
334                 CheckCFail { compiler } => {
335                     check::compiletest(self, &compiler, target.target,
336                                        "compile-fail", "compile-fail");
337                 }
338                 CheckCFailFull { compiler } => {
339                     check::compiletest(self, &compiler, target.target,
340                                        "compile-fail", "compile-fail-fulldeps")
341                 }
342                 CheckPFail { compiler } => {
343                     check::compiletest(self, &compiler, target.target,
344                                        "parse-fail", "parse-fail");
345                 }
346                 CheckRFail { compiler } => {
347                     check::compiletest(self, &compiler, target.target,
348                                        "run-fail", "run-fail");
349                 }
350                 CheckRFailFull { compiler } => {
351                     check::compiletest(self, &compiler, target.target,
352                                        "run-fail", "run-fail-fulldeps");
353                 }
354                 CheckPretty { compiler } => {
355                     check::compiletest(self, &compiler, target.target,
356                                        "pretty", "pretty");
357                 }
358                 CheckPrettyRPass { compiler } => {
359                     check::compiletest(self, &compiler, target.target,
360                                        "pretty", "run-pass");
361                 }
362                 CheckPrettyRPassFull { compiler } => {
363                     check::compiletest(self, &compiler, target.target,
364                                        "pretty", "run-pass-fulldeps");
365                 }
366                 CheckPrettyRFail { compiler } => {
367                     check::compiletest(self, &compiler, target.target,
368                                        "pretty", "run-fail");
369                 }
370                 CheckPrettyRFailFull { compiler } => {
371                     check::compiletest(self, &compiler, target.target,
372                                        "pretty", "run-fail-fulldeps");
373                 }
374                 CheckPrettyRPassValgrind { compiler } => {
375                     check::compiletest(self, &compiler, target.target,
376                                        "pretty", "run-pass-valgrind");
377                 }
378                 CheckCodegen { compiler } => {
379                     check::compiletest(self, &compiler, target.target,
380                                        "codegen", "codegen");
381                 }
382                 CheckCodegenUnits { compiler } => {
383                     check::compiletest(self, &compiler, target.target,
384                                        "codegen-units", "codegen-units");
385                 }
386                 CheckIncremental { compiler } => {
387                     check::compiletest(self, &compiler, target.target,
388                                        "incremental", "incremental");
389                 }
390                 CheckUi { compiler } => {
391                     check::compiletest(self, &compiler, target.target,
392                                        "ui", "ui");
393                 }
394                 CheckDebuginfo { compiler } => {
395                     if target.target.contains("msvc") {
396                         // nothing to do
397                     } else if target.target.contains("apple") {
398                         check::compiletest(self, &compiler, target.target,
399                                            "debuginfo-lldb", "debuginfo");
400                     } else {
401                         check::compiletest(self, &compiler, target.target,
402                                            "debuginfo-gdb", "debuginfo");
403                     }
404                 }
405                 CheckRustdoc { compiler } => {
406                     check::compiletest(self, &compiler, target.target,
407                                        "rustdoc", "rustdoc");
408                 }
409                 CheckRPassValgrind { compiler } => {
410                     check::compiletest(self, &compiler, target.target,
411                                        "run-pass-valgrind", "run-pass-valgrind");
412                 }
413                 CheckDocs { compiler } => {
414                     check::docs(self, &compiler);
415                 }
416                 CheckErrorIndex { compiler } => {
417                     check::error_index(self, &compiler);
418                 }
419                 CheckRMake { compiler } => {
420                     check::compiletest(self, &compiler, target.target,
421                                        "run-make", "run-make")
422                 }
423                 CheckCrateStd { compiler } => {
424                     check::krate(self, &compiler, target.target, Mode::Libstd)
425                 }
426                 CheckCrateTest { compiler } => {
427                     check::krate(self, &compiler, target.target, Mode::Libtest)
428                 }
429                 CheckCrateRustc { compiler } => {
430                     check::krate(self, &compiler, target.target, Mode::Librustc)
431                 }
432
433                 DistDocs { stage } => dist::docs(self, stage, target.target),
434                 DistMingw { _dummy } => dist::mingw(self, target.target),
435                 DistRustc { stage } => dist::rustc(self, stage, target.target),
436                 DistStd { compiler } => dist::std(self, &compiler, target.target),
437
438                 DebuggerScripts { stage } => {
439                     let compiler = Compiler::new(stage, target.target);
440                     dist::debugger_scripts(self,
441                                            &self.sysroot(&compiler),
442                                            target.target);
443                 }
444
445                 AndroidCopyLibs { compiler } => {
446                     check::android_copy_libs(self, &compiler, target.target);
447                 }
448
449                 // pseudo-steps
450                 Dist { .. } |
451                 Doc { .. } |
452                 CheckTarget { .. } |
453                 Check { .. } => {}
454             }
455         }
456     }
457
458     /// Updates all git submodules that we have.
459     ///
460     /// This will detect if any submodules are out of date an run the necessary
461     /// commands to sync them all with upstream.
462     fn update_submodules(&self) {
463         if !self.config.submodules {
464             return
465         }
466         if fs::metadata(self.src.join(".git")).is_err() {
467             return
468         }
469         let git_submodule = || {
470             let mut cmd = Command::new("git");
471             cmd.current_dir(&self.src).arg("submodule");
472             return cmd
473         };
474
475         // FIXME: this takes a seriously long time to execute on Windows and a
476         //        nontrivial amount of time on Unix, we should have a better way
477         //        of detecting whether we need to run all the submodule commands
478         //        below.
479         let out = output(git_submodule().arg("status"));
480         if !out.lines().any(|l| l.starts_with("+") || l.starts_with("-")) {
481             return
482         }
483
484         self.run(git_submodule().arg("sync"));
485         self.run(git_submodule().arg("init"));
486         self.run(git_submodule().arg("update"));
487         self.run(git_submodule().arg("update").arg("--recursive"));
488         self.run(git_submodule().arg("status").arg("--recursive"));
489         self.run(git_submodule().arg("foreach").arg("--recursive")
490                                 .arg("git").arg("clean").arg("-fdx"));
491         self.run(git_submodule().arg("foreach").arg("--recursive")
492                                 .arg("git").arg("checkout").arg("."));
493     }
494
495     /// Clear out `dir` if `input` is newer.
496     ///
497     /// After this executes, it will also ensure that `dir` exists.
498     fn clear_if_dirty(&self, dir: &Path, input: &Path) {
499         let stamp = dir.join(".stamp");
500         if mtime(&stamp) < mtime(input) {
501             self.verbose(&format!("Dirty - {}", dir.display()));
502             let _ = fs::remove_dir_all(dir);
503         }
504         t!(fs::create_dir_all(dir));
505         t!(File::create(stamp));
506     }
507
508     /// Prepares an invocation of `cargo` to be run.
509     ///
510     /// This will create a `Command` that represents a pending execution of
511     /// Cargo. This cargo will be configured to use `compiler` as the actual
512     /// rustc compiler, its output will be scoped by `mode`'s output directory,
513     /// it will pass the `--target` flag for the specified `target`, and will be
514     /// executing the Cargo command `cmd`.
515     fn cargo(&self,
516              compiler: &Compiler,
517              mode: Mode,
518              target: &str,
519              cmd: &str) -> Command {
520         let mut cargo = Command::new(&self.cargo);
521         let out_dir = self.stage_out(compiler, mode);
522         cargo.env("CARGO_TARGET_DIR", out_dir)
523              .arg(cmd)
524              .arg("-j").arg(self.jobs().to_string())
525              .arg("--target").arg(target);
526
527         let stage;
528         if compiler.stage == 0 && self.config.local_rebuild {
529             // Assume the local-rebuild rustc already has stage1 features.
530             stage = 1;
531         } else {
532             stage = compiler.stage;
533         }
534
535         // Customize the compiler we're running. Specify the compiler to cargo
536         // as our shim and then pass it some various options used to configure
537         // how the actual compiler itself is called.
538         //
539         // These variables are primarily all read by
540         // src/bootstrap/{rustc,rustdoc.rs}
541         cargo.env("RUSTC", self.out.join("bootstrap/debug/rustc"))
542              .env("RUSTC_REAL", self.compiler_path(compiler))
543              .env("RUSTC_STAGE", stage.to_string())
544              .env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string())
545              .env("RUSTC_CODEGEN_UNITS",
546                   self.config.rust_codegen_units.to_string())
547              .env("RUSTC_DEBUG_ASSERTIONS",
548                   self.config.rust_debug_assertions.to_string())
549              .env("RUSTC_SNAPSHOT", &self.rustc)
550              .env("RUSTC_SYSROOT", self.sysroot(compiler))
551              .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
552              .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir())
553              .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
554              .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
555              .env("RUSTDOC_REAL", self.rustdoc(compiler))
556              .env("RUSTC_FLAGS", self.rustc_flags(target).join(" "));
557
558         self.add_bootstrap_key(compiler, &mut cargo);
559
560         // Specify some various options for build scripts used throughout
561         // the build.
562         //
563         // FIXME: the guard against msvc shouldn't need to be here
564         if !target.contains("msvc") {
565             cargo.env(format!("CC_{}", target), self.cc(target))
566                  .env(format!("AR_{}", target), self.ar(target).unwrap()) // only msvc is None
567                  .env(format!("CFLAGS_{}", target), self.cflags(target).join(" "));
568         }
569
570         // If we're building for OSX, inform the compiler and the linker that
571         // we want to build a compiler runnable on 10.7
572         if target.contains("apple-darwin") {
573             cargo.env("MACOSX_DEPLOYMENT_TARGET", "10.7");
574         }
575
576         // Environment variables *required* needed throughout the build
577         //
578         // FIXME: should update code to not require this env var
579         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
580
581         if self.config.verbose || self.flags.verbose {
582             cargo.arg("-v");
583         }
584         if self.config.rust_optimize {
585             cargo.arg("--release");
586         }
587         return cargo
588     }
589
590     /// Get a path to the compiler specified.
591     fn compiler_path(&self, compiler: &Compiler) -> PathBuf {
592         if compiler.is_snapshot(self) {
593             self.rustc.clone()
594         } else {
595             self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
596         }
597     }
598
599     /// Get the specified tool built by the specified compiler
600     fn tool(&self, compiler: &Compiler, tool: &str) -> PathBuf {
601         self.cargo_out(compiler, Mode::Tool, compiler.host)
602             .join(exe(tool, compiler.host))
603     }
604
605     /// Get the `rustdoc` executable next to the specified compiler
606     fn rustdoc(&self, compiler: &Compiler) -> PathBuf {
607         let mut rustdoc = self.compiler_path(compiler);
608         rustdoc.pop();
609         rustdoc.push(exe("rustdoc", compiler.host));
610         return rustdoc
611     }
612
613     /// Get a `Command` which is ready to run `tool` in `stage` built for
614     /// `host`.
615     fn tool_cmd(&self, compiler: &Compiler, tool: &str) -> Command {
616         let mut cmd = Command::new(self.tool(&compiler, tool));
617         let host = compiler.host;
618         let paths = vec![
619             self.cargo_out(compiler, Mode::Libstd, host).join("deps"),
620             self.cargo_out(compiler, Mode::Libtest, host).join("deps"),
621             self.cargo_out(compiler, Mode::Librustc, host).join("deps"),
622             self.cargo_out(compiler, Mode::Tool, host).join("deps"),
623         ];
624         add_lib_path(paths, &mut cmd);
625         return cmd
626     }
627
628     /// Get the space-separated set of activated features for the standard
629     /// library.
630     fn std_features(&self) -> String {
631         let mut features = String::new();
632         if self.config.debug_jemalloc {
633             features.push_str(" debug-jemalloc");
634         }
635         if self.config.use_jemalloc {
636             features.push_str(" jemalloc");
637         }
638         return features
639     }
640
641     /// Get the space-separated set of activated features for the compiler.
642     fn rustc_features(&self) -> String {
643         let mut features = String::new();
644         if self.config.use_jemalloc {
645             features.push_str(" jemalloc");
646         }
647         return features
648     }
649
650     /// Component directory that Cargo will produce output into (e.g.
651     /// release/debug)
652     fn cargo_dir(&self) -> &'static str {
653         if self.config.rust_optimize {"release"} else {"debug"}
654     }
655
656     /// Returns the sysroot for the `compiler` specified that *this build system
657     /// generates*.
658     ///
659     /// That is, the sysroot for the stage0 compiler is not what the compiler
660     /// thinks it is by default, but it's the same as the default for stages
661     /// 1-3.
662     fn sysroot(&self, compiler: &Compiler) -> PathBuf {
663         if compiler.stage == 0 {
664             self.out.join(compiler.host).join("stage0-sysroot")
665         } else {
666             self.out.join(compiler.host).join(format!("stage{}", compiler.stage))
667         }
668     }
669
670     /// Returns the libdir where the standard library and other artifacts are
671     /// found for a compiler's sysroot.
672     fn sysroot_libdir(&self, compiler: &Compiler, target: &str) -> PathBuf {
673         self.sysroot(compiler).join("lib").join("rustlib")
674             .join(target).join("lib")
675     }
676
677     /// Returns the root directory for all output generated in a particular
678     /// stage when running with a particular host compiler.
679     ///
680     /// The mode indicates what the root directory is for.
681     fn stage_out(&self, compiler: &Compiler, mode: Mode) -> PathBuf {
682         let suffix = match mode {
683             Mode::Libstd => "-std",
684             Mode::Libtest => "-test",
685             Mode::Tool => "-tools",
686             Mode::Librustc => "-rustc",
687         };
688         self.out.join(compiler.host)
689                 .join(format!("stage{}{}", compiler.stage, suffix))
690     }
691
692     /// Returns the root output directory for all Cargo output in a given stage,
693     /// running a particular comipler, wehther or not we're building the
694     /// standard library, and targeting the specified architecture.
695     fn cargo_out(&self,
696                  compiler: &Compiler,
697                  mode: Mode,
698                  target: &str) -> PathBuf {
699         self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
700     }
701
702     /// Root output directory for LLVM compiled for `target`
703     ///
704     /// Note that if LLVM is configured externally then the directory returned
705     /// will likely be empty.
706     fn llvm_out(&self, target: &str) -> PathBuf {
707         self.out.join(target).join("llvm")
708     }
709
710     /// Returns the path to `llvm-config` for the specified target.
711     ///
712     /// If a custom `llvm-config` was specified for target then that's returned
713     /// instead.
714     fn llvm_config(&self, target: &str) -> PathBuf {
715         let target_config = self.config.target_config.get(target);
716         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
717             s.clone()
718         } else {
719             self.llvm_out(&self.config.build).join("bin")
720                 .join(exe("llvm-config", target))
721         }
722     }
723
724     /// Returns the path to `FileCheck` binary for the specified target
725     fn llvm_filecheck(&self, target: &str) -> PathBuf {
726         let target_config = self.config.target_config.get(target);
727         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
728             s.parent().unwrap().join(exe("FileCheck", target))
729         } else {
730             let base = self.llvm_out(&self.config.build).join("build");
731             let exe = exe("FileCheck", target);
732             if self.config.build.contains("msvc") {
733                 base.join("Release/bin").join(exe)
734             } else {
735                 base.join("bin").join(exe)
736             }
737         }
738     }
739
740     /// Root output directory for compiler-rt compiled for `target`
741     fn compiler_rt_out(&self, target: &str) -> PathBuf {
742         self.out.join(target).join("compiler-rt")
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 compiler's bootstrap key to the environment of `cmd`.
765     fn add_bootstrap_key(&self, compiler: &Compiler, cmd: &mut Command) {
766         // In stage0 we're using a previously released stable compiler, so we
767         // use the stage0 bootstrap key. Otherwise we use our own build's
768         // bootstrap key.
769         let bootstrap_key = if compiler.is_snapshot(self) && !self.config.local_rebuild {
770             &self.bootstrap_key_stage0
771         } else {
772             &self.bootstrap_key
773         };
774         cmd.env("RUSTC_BOOTSTRAP_KEY", bootstrap_key);
775     }
776
777     /// Returns the compiler's libdir where it stores the dynamic libraries that
778     /// it itself links against.
779     ///
780     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
781     /// Windows.
782     fn rustc_libdir(&self, compiler: &Compiler) -> PathBuf {
783         if compiler.is_snapshot(self) {
784             self.rustc_snapshot_libdir()
785         } else {
786             self.sysroot(compiler).join(libdir(compiler.host))
787         }
788     }
789
790     /// Returns the libdir of the snapshot compiler.
791     fn rustc_snapshot_libdir(&self) -> PathBuf {
792         self.rustc.parent().unwrap().parent().unwrap()
793             .join(libdir(&self.config.build))
794     }
795
796     /// Runs a command, printing out nice contextual information if it fails.
797     fn run(&self, cmd: &mut Command) {
798         self.verbose(&format!("running: {:?}", cmd));
799         run_silent(cmd)
800     }
801
802     /// Prints a message if this build is configured in verbose mode.
803     fn verbose(&self, msg: &str) {
804         if self.flags.verbose || self.config.verbose {
805             println!("{}", msg);
806         }
807     }
808
809     /// Returns the number of parallel jobs that have been configured for this
810     /// build.
811     fn jobs(&self) -> u32 {
812         self.flags.jobs.unwrap_or(num_cpus::get() as u32)
813     }
814
815     /// Returns the path to the C compiler for the target specified.
816     fn cc(&self, target: &str) -> &Path {
817         self.cc[target].0.path()
818     }
819
820     /// Returns a list of flags to pass to the C compiler for the target
821     /// specified.
822     fn cflags(&self, target: &str) -> Vec<String> {
823         // Filter out -O and /O (the optimization flags) that we picked up from
824         // gcc-rs because the build scripts will determine that for themselves.
825         let mut base = self.cc[target].0.args().iter()
826                            .map(|s| s.to_string_lossy().into_owned())
827                            .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
828                            .collect::<Vec<_>>();
829
830         // If we're compiling on OSX then we add a few unconditional flags
831         // indicating that we want libc++ (more filled out than libstdc++) and
832         // we want to compile for 10.7. This way we can ensure that
833         // LLVM/jemalloc/etc are all properly compiled.
834         if target.contains("apple-darwin") {
835             base.push("-stdlib=libc++".into());
836             base.push("-mmacosx-version-min=10.7".into());
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         self.cxx[target].path()
850     }
851
852     /// Returns flags to pass to the compiler to generate code for `target`.
853     fn rustc_flags(&self, target: &str) -> Vec<String> {
854         // New flags should be added here with great caution!
855         //
856         // It's quite unfortunate to **require** flags to generate code for a
857         // target, so it should only be passed here if absolutely necessary!
858         // Most default configuration should be done through target specs rather
859         // than an entry here.
860
861         let mut base = Vec::new();
862         if target != self.config.build && !target.contains("msvc") {
863             base.push(format!("-Clinker={}", self.cc(target).display()));
864         }
865         return base
866     }
867 }
868
869 impl<'a> Compiler<'a> {
870     /// Creates a new complier for the specified stage/host
871     fn new(stage: u32, host: &'a str) -> Compiler<'a> {
872         Compiler { stage: stage, host: host }
873     }
874
875     /// Returns whether this is a snapshot compiler for `build`'s configuration
876     fn is_snapshot(&self, build: &Build) -> bool {
877         self.stage == 0 && self.host == build.config.build
878     }
879 }