2 use std
::cell
::{Cell, RefCell}
;
3 use std
::collections
::BTreeSet
;
4 use std
::collections
::HashMap
;
11 use std
::path
::{Path, PathBuf}
;
12 use std
::process
::Command
;
13 use std
::time
::{Duration, Instant}
;
17 use crate::cache
::{Cache, Interned, INTERNER}
;
22 use crate::flags
::Subcommand
;
27 use crate::util
::{self, add_lib_path, exe, libdir}
;
28 use crate::{Build, DocTests, Mode, GitRepo}
;
30 pub use crate::Compiler
;
32 use petgraph
::graph
::NodeIndex
;
35 pub struct Builder
<'a
> {
40 stack
: RefCell
<Vec
<Box
<dyn Any
>>>,
41 time_spent_on_dependencies
: Cell
<Duration
>,
42 pub paths
: Vec
<PathBuf
>,
43 graph_nodes
: RefCell
<HashMap
<String
, NodeIndex
>>,
44 graph
: RefCell
<Graph
<String
, bool
>>,
45 parent
: Cell
<Option
<NodeIndex
>>,
48 impl<'a
> Deref
for Builder
<'a
> {
51 fn deref(&self) -> &Self::Target
{
56 pub trait Step
: '
static + Clone
+ Debug
+ PartialEq
+ Eq
+ Hash
{
57 /// `PathBuf` when directories are created or to return a `Compiler` once
58 /// it's been assembled.
61 const DEFAULT
: bool
= false;
63 /// If true, then this rule should be skipped if --target was specified, but --host was not
64 const ONLY_HOSTS
: bool
= false;
66 /// Primary function to execute this rule. Can call `builder.ensure()`
67 /// with other steps to run those.
68 fn run(self, builder
: &Builder
<'_
>) -> Self::Output
;
70 /// When bootstrap is passed a set of paths, this controls whether this rule
71 /// will execute. However, it does not get called in a "default" context
72 /// when we are not passed any paths; in that case, `make_run` is called
74 fn should_run(run
: ShouldRun
<'_
>) -> ShouldRun
<'_
>;
76 /// Builds up a "root" rule, either as a default rule or from a path passed
79 /// When path is `None`, we are executing in a context where no paths were
80 /// passed. When `./x.py build` is run, for example, this rule could get
81 /// called if it is in the correct list below with a path of `None`.
82 fn make_run(_run
: RunConfig
<'_
>) {
83 // It is reasonable to not have an implementation of make_run for rules
84 // who do not want to get called from the root context. This means that
85 // they are likely dependencies (e.g., sysroot creation) or similar, and
86 // as such calling them from ./x.py isn't logical.
91 pub struct RunConfig
<'a
> {
92 pub builder
: &'a Builder
<'a
>,
93 pub host
: Interned
<String
>,
94 pub target
: Interned
<String
>,
98 struct StepDescription
{
101 should_run
: fn(ShouldRun
<'_
>) -> ShouldRun
<'_
>,
102 make_run
: fn(RunConfig
<'_
>),
106 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
108 Set(BTreeSet
<PathBuf
>),
113 fn empty() -> PathSet
{
114 PathSet
::Set(BTreeSet
::new())
117 fn one
<P
: Into
<PathBuf
>>(path
: P
) -> PathSet
{
118 let mut set
= BTreeSet
::new();
119 set
.insert(path
.into());
123 fn has(&self, needle
: &Path
) -> bool
{
125 PathSet
::Set(set
) => set
.iter().any(|p
| p
.ends_with(needle
)),
126 PathSet
::Suite(suite
) => suite
.ends_with(needle
),
130 fn path(&self, builder
: &Builder
<'_
>) -> PathBuf
{
132 PathSet
::Set(set
) => set
135 .unwrap_or(&builder
.build
.src
)
137 PathSet
::Suite(path
) => PathBuf
::from(path
),
142 impl StepDescription
{
143 fn from
<S
: Step
>() -> StepDescription
{
146 only_hosts
: S
::ONLY_HOSTS
,
147 should_run
: S
::should_run
,
148 make_run
: S
::make_run
,
149 name
: std
::any
::type_name
::<S
>(),
153 fn maybe_run(&self, builder
: &Builder
<'_
>, pathset
: &PathSet
) {
154 if builder
.config
.exclude
.iter().any(|e
| pathset
.has(e
)) {
155 eprintln
!("Skipping {:?} because it is excluded", pathset
);
157 } else if !builder
.config
.exclude
.is_empty() {
159 "{:?} not skipped for {:?} -- not in {:?}",
160 pathset
, self.name
, builder
.config
.exclude
163 let hosts
= &builder
.hosts
;
165 // Determine the targets participating in this rule.
166 let targets
= if self.only_hosts
{
167 if builder
.config
.skip_only_host_steps
{
168 return; // don't run anything
177 for target
in targets
{
178 let run
= RunConfig
{
180 path
: pathset
.path(builder
),
184 (self.make_run
)(run
);
189 fn run(v
: &[StepDescription
], builder
: &Builder
<'_
>, paths
: &[PathBuf
]) {
192 .map(|desc
| (desc
.should_run
)(ShouldRun
::new(builder
)))
193 .collect
::<Vec
<_
>>();
195 // sanity checks on rules
196 for (desc
, should_run
) in v
.iter().zip(&should_runs
) {
198 !should_run
.paths
.is_empty(),
199 "{:?} should have at least one pathset",
204 if paths
.is_empty() {
205 for (desc
, should_run
) in v
.iter().zip(should_runs
) {
206 if desc
.default && should_run
.is_really_default
{
207 for pathset
in &should_run
.paths
{
208 desc
.maybe_run(builder
, pathset
);
214 // strip CurDir prefix if present
215 let path
= match path
.strip_prefix(".") {
220 let mut attempted_run
= false;
221 for (desc
, should_run
) in v
.iter().zip(&should_runs
) {
222 if let Some(suite
) = should_run
.is_suite_path(path
) {
223 attempted_run
= true;
224 desc
.maybe_run(builder
, suite
);
225 } else if let Some(pathset
) = should_run
.pathset_for_path(path
) {
226 attempted_run
= true;
227 desc
.maybe_run(builder
, pathset
);
232 panic
!("Error: no rules matched {}.", path
.display());
240 pub struct ShouldRun
<'a
> {
241 pub builder
: &'a Builder
<'a
>,
242 // use a BTreeSet to maintain sort order
243 paths
: BTreeSet
<PathSet
>,
245 // If this is a default rule, this is an additional constraint placed on
246 // its run. Generally something like compiler docs being enabled.
247 is_really_default
: bool
,
250 impl<'a
> ShouldRun
<'a
> {
251 fn new(builder
: &'a Builder
<'_
>) -> ShouldRun
<'a
> {
254 paths
: BTreeSet
::new(),
255 is_really_default
: true, // by default no additional conditions
259 pub fn default_condition(mut self, cond
: bool
) -> Self {
260 self.is_really_default
= cond
;
264 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
265 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
266 // actually doing something different for every crate passed.
267 pub fn all_krates(mut self, name
: &str) -> Self {
268 let mut set
= BTreeSet
::new();
269 for krate
in self.builder
.in_tree_crates(name
) {
270 set
.insert(PathBuf
::from(&krate
.path
));
272 self.paths
.insert(PathSet
::Set(set
));
276 pub fn krate(mut self, name
: &str) -> Self {
277 for krate
in self.builder
.in_tree_crates(name
) {
278 self.paths
.insert(PathSet
::one(&krate
.path
));
283 // single, non-aliased path
284 pub fn path(self, path
: &str) -> Self {
288 // multiple aliases for the same job
289 pub fn paths(mut self, paths
: &[&str]) -> Self {
291 .insert(PathSet
::Set(paths
.iter().map(PathBuf
::from
).collect()));
295 pub fn is_suite_path(&self, path
: &Path
) -> Option
<&PathSet
> {
296 self.paths
.iter().find(|pathset
| match pathset
{
297 PathSet
::Suite(p
) => path
.starts_with(p
),
298 PathSet
::Set(_
) => false,
302 pub fn suite_path(mut self, suite
: &str) -> Self {
303 self.paths
.insert(PathSet
::Suite(PathBuf
::from(suite
)));
307 // allows being more explicit about why should_run in Step returns the value passed to it
308 pub fn never(mut self) -> ShouldRun
<'a
> {
309 self.paths
.insert(PathSet
::empty());
313 fn pathset_for_path(&self, path
: &Path
) -> Option
<&PathSet
> {
314 self.paths
.iter().find(|pathset
| pathset
.has(path
))
318 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
331 impl<'a
> Builder
<'a
> {
332 fn get_step_descriptions(kind
: Kind
) -> Vec
<StepDescription
> {
333 macro_rules
! describe
{
334 ($
($rule
:ty
),+ $
(,)?
) => {{
335 vec
![$
(StepDescription
::from
::<$rule
>()),+]
339 Kind
::Build
=> describe
!(
342 compile
::StartupObjects
,
346 tool
::UnstableBookGen
,
351 tool
::RemoteTestServer
,
352 tool
::RemoteTestClient
,
363 Kind
::Check
| Kind
::Clippy
| Kind
::Fix
=> describe
!(
368 Kind
::Test
=> describe
!(
369 crate::toolstate
::ToolStateCheck
,
374 test
::RunPassValgrind
,
385 test
::RunPassValgrindPretty
,
395 test
::RunMakeFullDeps
,
409 test
::CompiletestTest
,
411 test
::RustdocJSNotStd
,
414 // Run bootstrap close to the end as it's unlikely to fail
416 // Run run-make last, since these won't pass without make on Windows
419 Kind
::Bench
=> describe
!(test
::Crate
, test
::CrateLibrustc
),
420 Kind
::Doc
=> describe
!(
422 doc
::UnstableBookGen
,
438 Kind
::Dist
=> describe
!(
443 dist
::DebuggerScripts
,
448 dist
::PlainSourceTarball
,
459 Kind
::Install
=> describe
!(
474 pub fn get_help(build
: &Build
, subcommand
: &str) -> Option
<String
> {
475 let kind
= match subcommand
{
476 "build" => Kind
::Build
,
478 "test" => Kind
::Test
,
479 "bench" => Kind
::Bench
,
480 "dist" => Kind
::Dist
,
481 "install" => Kind
::Install
,
485 let builder
= Builder
{
487 top_stage
: build
.config
.stage
.unwrap_or(2),
490 stack
: RefCell
::new(Vec
::new()),
491 time_spent_on_dependencies
: Cell
::new(Duration
::new(0, 0)),
493 graph_nodes
: RefCell
::new(HashMap
::new()),
494 graph
: RefCell
::new(Graph
::new()),
495 parent
: Cell
::new(None
),
498 let builder
= &builder
;
499 let mut should_run
= ShouldRun
::new(builder
);
500 for desc
in Builder
::get_step_descriptions(builder
.kind
) {
501 should_run
= (desc
.should_run
)(should_run
);
503 let mut help
= String
::from("Available paths:\n");
504 for pathset
in should_run
.paths
{
505 if let PathSet
::Set(set
) = pathset
{
506 set
.iter().for_each(|path
| {
508 format
!(" ./x.py {} {}\n", subcommand
, path
.display()).as_str(),
516 pub fn new(build
: &Build
) -> Builder
<'_
> {
517 let (kind
, paths
) = match build
.config
.cmd
{
518 Subcommand
::Build { ref paths }
=> (Kind
::Build
, &paths
[..]),
519 Subcommand
::Check { ref paths }
=> (Kind
::Check
, &paths
[..]),
520 Subcommand
::Clippy { ref paths }
=> (Kind
::Clippy
, &paths
[..]),
521 Subcommand
::Fix { ref paths }
=> (Kind
::Fix
, &paths
[..]),
522 Subcommand
::Doc { ref paths }
=> (Kind
::Doc
, &paths
[..]),
523 Subcommand
::Test { ref paths, .. }
=> (Kind
::Test
, &paths
[..]),
524 Subcommand
::Bench { ref paths, .. }
=> (Kind
::Bench
, &paths
[..]),
525 Subcommand
::Dist { ref paths }
=> (Kind
::Dist
, &paths
[..]),
526 Subcommand
::Install { ref paths }
=> (Kind
::Install
, &paths
[..]),
527 Subcommand
::Clean { .. }
=> panic
!(),
530 let builder
= Builder
{
532 top_stage
: build
.config
.stage
.unwrap_or(2),
535 stack
: RefCell
::new(Vec
::new()),
536 time_spent_on_dependencies
: Cell
::new(Duration
::new(0, 0)),
537 paths
: paths
.to_owned(),
538 graph_nodes
: RefCell
::new(HashMap
::new()),
539 graph
: RefCell
::new(Graph
::new()),
540 parent
: Cell
::new(None
),
546 pub fn execute_cli(&self) -> Graph
<String
, bool
> {
547 self.run_step_descriptions(&Builder
::get_step_descriptions(self.kind
), &self.paths
);
548 self.graph
.borrow().clone()
551 pub fn default_doc(&self, paths
: Option
<&[PathBuf
]>) {
552 let paths
= paths
.unwrap_or(&[]);
553 self.run_step_descriptions(&Builder
::get_step_descriptions(Kind
::Doc
), paths
);
556 fn run_step_descriptions(&self, v
: &[StepDescription
], paths
: &[PathBuf
]) {
557 StepDescription
::run(v
, self, paths
);
560 /// Obtain a compiler at a given stage and for a given host. Explicitly does
561 /// not take `Compiler` since all `Compiler` instances are meant to be
562 /// obtained through this function, since it ensures that they are valid
563 /// (i.e., built and assembled).
564 pub fn compiler(&self, stage
: u32, host
: Interned
<String
>) -> Compiler
{
565 self.ensure(compile
::Assemble
{
566 target_compiler
: Compiler { stage, host }
,
570 /// Similar to `compiler`, except handles the full-bootstrap option to
571 /// silently use the stage1 compiler instead of a stage2 compiler if one is
574 /// Note that this does *not* have the side effect of creating
575 /// `compiler(stage, host)`, unlike `compiler` above which does have such
576 /// a side effect. The returned compiler here can only be used to compile
577 /// new artifacts, it can't be used to rely on the presence of a particular
580 /// See `force_use_stage1` for documentation on what each argument is.
584 host
: Interned
<String
>,
585 target
: Interned
<String
>,
587 if self.build
.force_use_stage1(Compiler { stage, host }
, target
) {
588 self.compiler(1, self.config
.build
)
590 self.compiler(stage
, host
)
594 pub fn sysroot(&self, compiler
: Compiler
) -> Interned
<PathBuf
> {
595 self.ensure(compile
::Sysroot { compiler }
)
598 /// Returns the libdir where the standard library and other artifacts are
599 /// found for a compiler's sysroot.
600 pub fn sysroot_libdir(
603 target
: Interned
<String
>,
604 ) -> Interned
<PathBuf
> {
605 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
608 target
: Interned
<String
>,
610 impl Step
for Libdir
{
611 type Output
= Interned
<PathBuf
>;
613 fn should_run(run
: ShouldRun
<'_
>) -> ShouldRun
<'_
> {
617 fn run(self, builder
: &Builder
<'_
>) -> Interned
<PathBuf
> {
618 let lib
= builder
.sysroot_libdir_relative(self.compiler
);
619 let sysroot
= builder
620 .sysroot(self.compiler
)
625 let _
= fs
::remove_dir_all(&sysroot
);
626 t
!(fs
::create_dir_all(&sysroot
));
627 INTERNER
.intern_path(sysroot
)
630 self.ensure(Libdir { compiler, target }
)
633 /// Returns the compiler's libdir where it stores the dynamic libraries that
634 /// it itself links against.
636 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
638 pub fn rustc_libdir(&self, compiler
: Compiler
) -> PathBuf
{
639 if compiler
.is_snapshot(self) {
640 self.rustc_snapshot_libdir()
642 match self.config
.libdir_relative() {
643 Some(relative_libdir
) if compiler
.stage
>= 1
644 => self.sysroot(compiler
).join(relative_libdir
),
645 _
=> self.sysroot(compiler
).join(libdir(&compiler
.host
))
650 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
651 /// it itself links against.
653 /// For example this returns `lib` on Unix and `bin` on
655 pub fn libdir_relative(&self, compiler
: Compiler
) -> &Path
{
656 if compiler
.is_snapshot(self) {
657 libdir(&self.config
.build
).as_ref()
659 match self.config
.libdir_relative() {
660 Some(relative_libdir
) if compiler
.stage
>= 1
662 _
=> libdir(&compiler
.host
).as_ref()
667 /// Returns the compiler's relative libdir where the standard library and other artifacts are
668 /// found for a compiler's sysroot.
670 /// For example this returns `lib` on Unix and Windows.
671 pub fn sysroot_libdir_relative(&self, compiler
: Compiler
) -> &Path
{
672 match self.config
.libdir_relative() {
673 Some(relative_libdir
) if compiler
.stage
>= 1
675 _
=> Path
::new("lib")
679 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
680 /// library lookup path.
681 pub fn add_rustc_lib_path(&self, compiler
: Compiler
, cmd
: &mut Cargo
) {
682 // Windows doesn't need dylib path munging because the dlls for the
683 // compiler live next to the compiler and the system will find them
689 add_lib_path(vec
![self.rustc_libdir(compiler
)], &mut cmd
.command
);
692 /// Gets a path to the compiler specified.
693 pub fn rustc(&self, compiler
: Compiler
) -> PathBuf
{
694 if compiler
.is_snapshot(self) {
695 self.initial_rustc
.clone()
697 self.sysroot(compiler
)
699 .join(exe("rustc", &compiler
.host
))
703 pub fn rustdoc(&self, compiler
: Compiler
) -> PathBuf
{
704 self.ensure(tool
::Rustdoc { compiler }
)
707 pub fn rustdoc_cmd(&self, compiler
: Compiler
) -> Command
{
708 let mut cmd
= Command
::new(&self.out
.join("bootstrap/debug/rustdoc"));
709 cmd
.env("RUSTC_STAGE", compiler
.stage
.to_string())
710 .env("RUSTC_SYSROOT", self.sysroot(compiler
))
711 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
712 // equivalently to rustc.
713 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler
))
714 .env("CFG_RELEASE_CHANNEL", &self.config
.channel
)
715 .env("RUSTDOC_REAL", self.rustdoc(compiler
))
716 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
717 .env("RUSTC_BOOTSTRAP", "1");
719 // Remove make-related flags that can cause jobserver problems.
720 cmd
.env_remove("MAKEFLAGS");
721 cmd
.env_remove("MFLAGS");
723 if let Some(linker
) = self.linker(compiler
.host
) {
724 cmd
.env("RUSTC_TARGET_LINKER", linker
);
729 /// Prepares an invocation of `cargo` to be run.
731 /// This will create a `Command` that represents a pending execution of
732 /// Cargo. This cargo will be configured to use `compiler` as the actual
733 /// rustc compiler, its output will be scoped by `mode`'s output directory,
734 /// it will pass the `--target` flag for the specified `target`, and will be
735 /// executing the Cargo command `cmd`.
740 target
: Interned
<String
>,
743 let mut cargo
= Command
::new(&self.initial_cargo
);
744 let out_dir
= self.stage_out(compiler
, mode
);
746 if cmd
== "doc" || cmd
== "rustdoc" {
747 let my_out
= match mode
{
748 // This is the intended out directory for compiler documentation.
749 Mode
::Rustc
| Mode
::ToolRustc
| Mode
::Codegen
=> self.compiler_doc_out(target
),
750 _
=> self.crate_doc_out(target
),
752 let rustdoc
= self.rustdoc(compiler
);
753 self.clear_if_dirty(&my_out
, &rustdoc
);
757 .env("CARGO_TARGET_DIR", out_dir
)
759 .arg("-Zconfig-profile");
761 let profile_var
= |name
: &str| {
762 let profile
= if self.config
.rust_optimize
{
767 format
!("CARGO_PROFILE_{}_{}", profile
, name
)
770 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
771 // needs to not accidentally link to libLLVM in stage0/lib.
772 cargo
.env("REAL_LIBRARY_PATH_VAR", &util
::dylib_path_var());
773 if let Some(e
) = env
::var_os(util
::dylib_path_var()) {
774 cargo
.env("REAL_LIBRARY_PATH", e
);
777 if cmd
!= "install" {
778 cargo
.arg("--target")
781 assert_eq
!(target
, compiler
.host
);
784 // Set a flag for `check`/`clippy`/`fix`, so that certain build
785 // scripts can do less work (e.g. not building/requiring LLVM).
786 if cmd
== "check" || cmd
== "clippy" || cmd
== "fix" {
787 cargo
.env("RUST_CHECK", "1");
791 if compiler
.stage
== 0 && self.local_rebuild
{
792 // Assume the local-rebuild rustc already has stage1 features.
795 stage
= compiler
.stage
;
798 let mut rustflags
= Rustflags
::new(&target
);
800 if let Ok(s
) = env
::var("CARGOFLAGS_NOT_BOOTSTRAP") {
801 cargo
.args(s
.split_whitespace());
803 rustflags
.env("RUSTFLAGS_NOT_BOOTSTRAP");
805 if let Ok(s
) = env
::var("CARGOFLAGS_BOOTSTRAP") {
806 cargo
.args(s
.split_whitespace());
808 rustflags
.env("RUSTFLAGS_BOOTSTRAP");
809 rustflags
.arg("--cfg=bootstrap");
812 if let Ok(s
) = env
::var("CARGOFLAGS") {
813 cargo
.args(s
.split_whitespace());
817 Mode
::Std
| Mode
::ToolBootstrap
| Mode
::ToolStd
=> {}
,
818 Mode
::Rustc
| Mode
::Codegen
| Mode
::ToolRustc
=> {
819 // Build proc macros both for the host and the target
820 if target
!= compiler
.host
&& cmd
!= "check" {
821 cargo
.arg("-Zdual-proc-macros");
822 rustflags
.arg("-Zdual-proc-macros");
827 // This tells Cargo (and in turn, rustc) to output more complete
828 // dependency information. Most importantly for rustbuild, this
829 // includes sysroot artifacts, like libstd, which means that we don't
830 // need to track those in rustbuild (an error prone process!). This
831 // feature is currently unstable as there may be some bugs and such, but
832 // it represents a big improvement in rustbuild's reliability on
833 // rebuilds, so we're using it here.
835 // For some additional context, see #63470 (the PR originally adding
836 // this), as well as #63012 which is the tracking issue for this
837 // feature on the rustc side.
838 cargo
.arg("-Zbinary-dep-depinfo");
840 cargo
.arg("-j").arg(self.jobs().to_string());
841 // Remove make-related flags to ensure Cargo can correctly set things up
842 cargo
.env_remove("MAKEFLAGS");
843 cargo
.env_remove("MFLAGS");
845 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
846 // Force cargo to output binaries with disambiguating hashes in the name
847 let mut metadata
= if compiler
.stage
== 0 {
848 // Treat stage0 like a special channel, whether it's a normal prior-
849 // release rustc or a local rebuild with the same version, so we
850 // never mix these libraries by accident.
851 "bootstrap".to_string()
853 self.config
.channel
.to_string()
855 // We want to make sure that none of the dependencies between
856 // std/test/rustc unify with one another. This is done for weird linkage
857 // reasons but the gist of the problem is that if librustc, libtest, and
858 // libstd all depend on libc from crates.io (which they actually do) we
859 // want to make sure they all get distinct versions. Things get really
860 // weird if we try to unify all these dependencies right now, namely
861 // around how many times the library is linked in dynamic libraries and
862 // such. If rustc were a static executable or if we didn't ship dylibs
863 // this wouldn't be a problem, but we do, so it is. This is in general
864 // just here to make sure things build right. If you can remove this and
865 // things still build right, please do!
867 Mode
::Std
=> metadata
.push_str("std"),
868 // When we're building rustc tools, they're built with a search path
869 // that contains things built during the rustc build. For example,
870 // bitflags is built during the rustc build, and is a dependency of
871 // rustdoc as well. We're building rustdoc in a different target
872 // directory, though, which means that Cargo will rebuild the
873 // dependency. When we go on to build rustdoc, we'll look for
874 // bitflags, and find two different copies: one built during the
875 // rustc step and one that we just built. This isn't always a
876 // problem, somehow -- not really clear why -- but we know that this
878 Mode
::ToolRustc
=> metadata
.push_str("tool-rustc"),
881 cargo
.env("__CARGO_DEFAULT_LIB_METADATA", &metadata
);
884 rustflags
.arg("-Zforce-unstable-if-unmarked");
887 rustflags
.arg("-Zexternal-macro-backtrace");
889 let want_rustdoc
= self.doc_tests
!= DocTests
::No
;
891 // We synthetically interpret a stage0 compiler used to build tools as a
892 // "raw" compiler in that it's the exact snapshot we download. Normally
893 // the stage0 build means it uses libraries build by the stage0
894 // compiler, but for tools we just use the precompiled libraries that
896 let use_snapshot
= mode
== Mode
::ToolBootstrap
;
897 assert
!(!use_snapshot
|| stage
== 0 || self.local_rebuild
);
899 let maybe_sysroot
= self.sysroot(compiler
);
900 let sysroot
= if use_snapshot
{
901 self.rustc_snapshot_sysroot()
905 let libdir
= self.rustc_libdir(compiler
);
907 // Customize the compiler we're running. Specify the compiler to cargo
908 // as our shim and then pass it some various options used to configure
909 // how the actual compiler itself is called.
911 // These variables are primarily all read by
912 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
914 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target
))
915 .env("RUSTC", self.out
.join("bootstrap/debug/rustc"))
916 .env("RUSTC_REAL", self.rustc(compiler
))
917 .env("RUSTC_STAGE", stage
.to_string())
919 "RUSTC_DEBUG_ASSERTIONS",
920 self.config
.rust_debug_assertions
.to_string(),
922 .env("RUSTC_SYSROOT", &sysroot
)
923 .env("RUSTC_LIBDIR", &libdir
)
924 .env("RUSTDOC", self.out
.join("bootstrap/debug/rustdoc"))
927 if cmd
== "doc" || cmd
== "rustdoc" || (cmd
== "test" && want_rustdoc
) {
928 self.rustdoc(compiler
)
930 PathBuf
::from("/path/to/nowhere/rustdoc/not/required")
933 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
934 .env("RUSTC_BREAK_ON_ICE", "1");
936 // Dealing with rpath here is a little special, so let's go into some
937 // detail. First off, `-rpath` is a linker option on Unix platforms
938 // which adds to the runtime dynamic loader path when looking for
939 // dynamic libraries. We use this by default on Unix platforms to ensure
940 // that our nightlies behave the same on Windows, that is they work out
941 // of the box. This can be disabled, of course, but basically that's why
942 // we're gated on RUSTC_RPATH here.
944 // Ok, so the astute might be wondering "why isn't `-C rpath` used
945 // here?" and that is indeed a good question to task. This codegen
946 // option is the compiler's current interface to generating an rpath.
947 // Unfortunately it doesn't quite suffice for us. The flag currently
948 // takes no value as an argument, so the compiler calculates what it
949 // should pass to the linker as `-rpath`. This unfortunately is based on
950 // the **compile time** directory structure which when building with
951 // Cargo will be very different than the runtime directory structure.
953 // All that's a really long winded way of saying that if we use
954 // `-Crpath` then the executables generated have the wrong rpath of
955 // something like `$ORIGIN/deps` when in fact the way we distribute
956 // rustc requires the rpath to be `$ORIGIN/../lib`.
958 // So, all in all, to set up the correct rpath we pass the linker
959 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
960 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
961 // to change a flag in a binary?
962 if self.config
.rust_rpath
&& util
::use_host_linker(&target
) {
963 let rpath
= if target
.contains("apple") {
965 // Note that we need to take one extra step on macOS to also pass
966 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
967 // do that we pass a weird flag to the compiler to get it to do
968 // so. Note that this is definitely a hack, and we should likely
969 // flesh out rpath support more fully in the future.
970 rustflags
.arg("-Zosx-rpath-install-name");
971 Some("-Wl,-rpath,@loader_path/../lib")
972 } else if !target
.contains("windows") {
973 Some("-Wl,-rpath,$ORIGIN/../lib")
977 if let Some(rpath
) = rpath
{
978 rustflags
.arg(&format
!("-Clink-args={}", rpath
));
982 if let Some(host_linker
) = self.linker(compiler
.host
) {
983 cargo
.env("RUSTC_HOST_LINKER", host_linker
);
985 if let Some(target_linker
) = self.linker(target
) {
986 let target
= crate::envify(&target
);
987 cargo
.env(&format
!("CARGO_TARGET_{}_LINKER", target
), target_linker
);
989 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd
)) && want_rustdoc
{
990 cargo
.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler
));
993 let debuginfo_level
= match mode
{
994 Mode
::Rustc
| Mode
::Codegen
=> self.config
.rust_debuginfo_level_rustc
,
995 Mode
::Std
=> self.config
.rust_debuginfo_level_std
,
996 Mode
::ToolBootstrap
| Mode
::ToolStd
|
997 Mode
::ToolRustc
=> self.config
.rust_debuginfo_level_tools
,
999 cargo
.env(profile_var("DEBUG"), debuginfo_level
.to_string());
1001 if !mode
.is_tool() {
1002 cargo
.env("RUSTC_FORCE_UNSTABLE", "1");
1005 if let Some(x
) = self.crt_static(target
) {
1007 rustflags
.arg("-Ctarget-feature=+crt-static");
1009 rustflags
.arg("-Ctarget-feature=-crt-static");
1013 if let Some(x
) = self.crt_static(compiler
.host
) {
1014 cargo
.env("RUSTC_HOST_CRT_STATIC", x
.to_string());
1017 if let Some(map
) = self.build
.debuginfo_map(GitRepo
::Rustc
) {
1018 cargo
.env("RUSTC_DEBUGINFO_MAP", map
);
1021 // Enable usage of unstable features
1022 cargo
.env("RUSTC_BOOTSTRAP", "1");
1023 self.add_rust_test_threads(&mut cargo
);
1025 // Almost all of the crates that we compile as part of the bootstrap may
1026 // have a build script, including the standard library. To compile a
1027 // build script, however, it itself needs a standard library! This
1028 // introduces a bit of a pickle when we're compiling the standard
1031 // To work around this we actually end up using the snapshot compiler
1032 // (stage0) for compiling build scripts of the standard library itself.
1033 // The stage0 compiler is guaranteed to have a libstd available for use.
1035 // For other crates, however, we know that we've already got a standard
1036 // library up and running, so we can use the normal compiler to compile
1037 // build scripts in that situation.
1038 if mode
== Mode
::Std
{
1040 .env("RUSTC_SNAPSHOT", &self.initial_rustc
)
1041 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1044 .env("RUSTC_SNAPSHOT", self.rustc(compiler
))
1045 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler
));
1048 if self.config
.incremental
{
1049 cargo
.env("CARGO_INCREMENTAL", "1");
1051 // Don't rely on any default setting for incr. comp. in Cargo
1052 cargo
.env("CARGO_INCREMENTAL", "0");
1055 if let Some(ref on_fail
) = self.config
.on_fail
{
1056 cargo
.env("RUSTC_ON_FAIL", on_fail
);
1059 if self.config
.print_step_timings
{
1060 cargo
.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1063 if self.config
.backtrace_on_ice
{
1064 cargo
.env("RUSTC_BACKTRACE_ON_ICE", "1");
1067 cargo
.env("RUSTC_VERBOSE", self.verbosity
.to_string());
1069 if !mode
.is_tool() {
1070 // When extending this list, add the new lints to the RUSTFLAGS of the
1071 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1072 // some code doesn't go through this `rustc` wrapper.
1073 rustflags
.arg("-Wrust_2018_idioms");
1074 rustflags
.arg("-Wunused_lifetimes");
1076 if self.config
.deny_warnings
{
1077 rustflags
.arg("-Dwarnings");
1081 if let Mode
::Rustc
| Mode
::Codegen
= mode
{
1082 rustflags
.arg("-Zunstable-options");
1083 rustflags
.arg("-Wrustc::internal");
1086 // Throughout the build Cargo can execute a number of build scripts
1087 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1088 // obtained previously to those build scripts.
1089 // Build scripts use either the `cc` crate or `configure/make` so we pass
1090 // the options through environment variables that are fetched and understood by both.
1092 // FIXME: the guard against msvc shouldn't need to be here
1093 if target
.contains("msvc") {
1094 if let Some(ref cl
) = self.config
.llvm_clang_cl
{
1095 cargo
.env("CC", cl
).env("CXX", cl
);
1098 let ccache
= self.config
.ccache
.as_ref();
1099 let ccacheify
= |s
: &Path
| {
1100 let ccache
= match ccache
{
1102 None
=> return s
.display().to_string(),
1104 // FIXME: the cc-rs crate only recognizes the literal strings
1105 // `ccache` and `sccache` when doing caching compilations, so we
1106 // mirror that here. It should probably be fixed upstream to
1107 // accept a new env var or otherwise work with custom ccache
1110 "ccache" | "sccache" => format
!("{} {}", ccache
, s
.display()),
1111 _
=> s
.display().to_string(),
1114 let cc
= ccacheify(&self.cc(target
));
1115 cargo
.env(format
!("CC_{}", target
), &cc
);
1117 let cflags
= self.cflags(target
, GitRepo
::Rustc
).join(" ");
1119 .env(format
!("CFLAGS_{}", target
), cflags
.clone());
1121 if let Some(ar
) = self.ar(target
) {
1122 let ranlib
= format
!("{} s", ar
.display());
1124 .env(format
!("AR_{}", target
), ar
)
1125 .env(format
!("RANLIB_{}", target
), ranlib
);
1128 if let Ok(cxx
) = self.cxx(target
) {
1129 let cxx
= ccacheify(&cxx
);
1131 .env(format
!("CXX_{}", target
), &cxx
)
1132 .env(format
!("CXXFLAGS_{}", target
), cflags
);
1136 if mode
== Mode
::Std
1137 && self.config
.extended
1138 && compiler
.is_final_stage(self)
1140 rustflags
.arg("-Zsave-analysis");
1141 cargo
.env("RUST_SAVE_ANALYSIS_CONFIG",
1142 "{\"output_file\": null,\"full_docs\": false,\
1143 \"pub_only\": true,\"reachable_only\": false,\
1144 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
1147 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1148 cargo
.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1150 // Environment variables *required* throughout the build
1152 // FIXME: should update code to not require this env var
1153 cargo
.env("CFG_COMPILER_HOST_TRIPLE", target
);
1155 // Set this for all builds to make sure doc builds also get it.
1156 cargo
.env("CFG_RELEASE_CHANNEL", &self.config
.channel
);
1158 // This one's a bit tricky. As of the time of this writing the compiler
1159 // links to the `winapi` crate on crates.io. This crate provides raw
1160 // bindings to Windows system functions, sort of like libc does for
1161 // Unix. This crate also, however, provides "import libraries" for the
1162 // MinGW targets. There's an import library per dll in the windows
1163 // distribution which is what's linked to. These custom import libraries
1164 // are used because the winapi crate can reference Windows functions not
1165 // present in the MinGW import libraries.
1167 // For example MinGW may ship libdbghelp.a, but it may not have
1168 // references to all the functions in the dbghelp dll. Instead the
1169 // custom import library for dbghelp in the winapi crates has all this
1172 // Unfortunately for us though the import libraries are linked by
1173 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1174 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1175 // conflict with the system MinGW ones). This consequently means that
1176 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1177 // DLL) when linked against *again*, for example with procedural macros
1178 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1179 // `-lwinapi_foo` to the linker again. This isn't actually available in
1180 // our distribution, however, so the link fails.
1182 // To solve this problem we tell winapi to not use its bundled import
1183 // libraries. This means that it will link to the system MinGW import
1184 // libraries by default, and the `-ldylib=foo` directives will still get
1185 // passed to the final linker, but they'll look like `-lfoo` which can
1186 // be resolved because MinGW has the import library. The downside is we
1187 // don't get newer functions from Windows, but we don't use any of them
1189 if !mode
.is_tool() {
1190 cargo
.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1193 for _
in 1..self.verbosity
{
1197 match (mode
, self.config
.rust_codegen_units_std
, self.config
.rust_codegen_units
) {
1198 (Mode
::Std
, Some(n
), _
) |
1199 (_
, _
, Some(n
)) => {
1200 cargo
.env(profile_var("CODEGEN_UNITS"), n
.to_string());
1203 // Don't set anything
1207 if self.config
.rust_optimize
{
1208 // FIXME: cargo bench/install do not accept `--release`
1209 if cmd
!= "bench" && cmd
!= "install" {
1210 cargo
.arg("--release");
1214 if self.config
.locked_deps
{
1215 cargo
.arg("--locked");
1217 if self.config
.vendor
|| self.is_sudo
{
1218 cargo
.arg("--frozen");
1221 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1222 cargo
.env("RUSTC_INSTALL_BINDIR", self.config
.bindir_relative());
1224 self.ci_env
.force_coloring_in_ci(&mut cargo
);
1226 // When we build Rust dylibs they're all intended for intermediate
1227 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1228 // linking all deps statically into the dylib.
1229 if let Mode
::Std
| Mode
::Rustc
| Mode
::Codegen
= mode
{
1230 rustflags
.arg("-Cprefer-dynamic");
1239 /// Ensure that a given step is built, returning its output. This will
1240 /// cache the step, so it is safe (and good!) to call this as often as
1241 /// needed to ensure that all dependencies are built.
1242 pub fn ensure
<S
: Step
>(&'a
self, step
: S
) -> S
::Output
{
1244 let mut stack
= self.stack
.borrow_mut();
1245 for stack_step
in stack
.iter() {
1248 .downcast_ref
::<S
>()
1249 .map_or(true, |stack_step
| *stack_step
!= step
)
1253 let mut out
= String
::new();
1254 out
+= &format
!("\n\nCycle in build detected when adding {:?}\n", step
);
1255 for el
in stack
.iter().rev() {
1256 out
+= &format
!("\t{:?}\n", el
);
1260 if let Some(out
) = self.cache
.get(&step
) {
1261 self.verbose(&format
!("{}c {:?}", " ".repeat(stack
.len()), step
));
1264 let mut graph
= self.graph
.borrow_mut();
1265 let parent
= self.parent
.get();
1269 .entry(format
!("{:?}", step
))
1270 .or_insert_with(|| graph
.add_node(format
!("{:?}", step
)));
1271 if let Some(parent
) = parent
{
1272 graph
.add_edge(parent
, us
, false);
1278 self.verbose(&format
!("{}> {:?}", " ".repeat(stack
.len()), step
));
1279 stack
.push(Box
::new(step
.clone()));
1282 let prev_parent
= self.parent
.get();
1285 let mut graph
= self.graph
.borrow_mut();
1286 let parent
= self.parent
.get();
1290 .entry(format
!("{:?}", step
))
1291 .or_insert_with(|| graph
.add_node(format
!("{:?}", step
)));
1292 self.parent
.set(Some(us
));
1293 if let Some(parent
) = parent
{
1294 graph
.add_edge(parent
, us
, true);
1299 let start
= Instant
::now();
1300 let zero
= Duration
::new(0, 0);
1301 let parent
= self.time_spent_on_dependencies
.replace(zero
);
1302 let out
= step
.clone().run(self);
1303 let dur
= start
.elapsed();
1304 let deps
= self.time_spent_on_dependencies
.replace(parent
+ dur
);
1308 self.parent
.set(prev_parent
);
1310 if self.config
.print_step_timings
&& dur
> Duration
::from_millis(100) {
1312 "[TIMING] {:?} -- {}.{:03}",
1315 dur
.subsec_nanos() / 1_000_000
1320 let mut stack
= self.stack
.borrow_mut();
1321 let cur_step
= stack
.pop().expect("step stack empty");
1322 assert_eq
!(cur_step
.downcast_ref(), Some(&step
));
1324 self.verbose(&format
!(
1326 " ".repeat(self.stack
.borrow().len()),
1329 self.cache
.put(step
, out
.clone());
1338 struct Rustflags(String
);
1341 fn new(target
: &str) -> Rustflags
{
1342 let mut ret
= Rustflags(String
::new());
1344 // Inherit `RUSTFLAGS` by default ...
1345 ret
.env("RUSTFLAGS");
1347 // ... and also handle target-specific env RUSTFLAGS if they're
1349 let target_specific
= format
!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(target
));
1350 ret
.env(&target_specific
);
1355 fn env(&mut self, env
: &str) {
1356 if let Ok(s
) = env
::var(env
) {
1357 for part
in s
.split_whitespace() {
1363 fn arg(&mut self, arg
: &str) -> &mut Self {
1364 assert_eq
!(arg
.split_whitespace().count(), 1);
1365 if self.0.len() > 0 {
1366 self.0.push_str(" ");
1368 self.0.push_str(arg
);
1376 rustflags
: Rustflags
,
1380 pub fn rustflag(&mut self, arg
: &str) -> &mut Cargo
{
1381 self.rustflags
.arg(arg
);
1385 pub fn arg(&mut self, arg
: impl AsRef
<OsStr
>) -> &mut Cargo
{
1386 self.command
.arg(arg
.as_ref());
1390 pub fn args
<I
, S
>(&mut self, args
: I
) -> &mut Cargo
1391 where I
: IntoIterator
<Item
=S
>, S
: AsRef
<OsStr
>
1394 self.arg(arg
.as_ref());
1399 pub fn env(&mut self, key
: impl AsRef
<OsStr
>, value
: impl AsRef
<OsStr
>) -> &mut Cargo
{
1400 self.command
.env(key
.as_ref(), value
.as_ref());
1405 impl From
<Cargo
> for Command
{
1406 fn from(mut cargo
: Cargo
) -> Command
{
1407 cargo
.command
.env("RUSTFLAGS", &cargo
.rustflags
.0);