]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/test.rs
bootstrap: put Miri sysroot into local build dir
[rust.git] / src / bootstrap / test.rs
1 //! Implementation of the test-related targets of the build system.
2 //!
3 //! This file implements the various regression test suites that we execute on
4 //! our CI.
5
6 use std::env;
7 use std::ffi::OsString;
8 use std::fmt;
9 use std::fs;
10 use std::iter;
11 use std::path::{Path, PathBuf};
12 use std::process::{Command, Stdio};
13
14 use crate::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step};
15 use crate::cache::Interned;
16 use crate::compile;
17 use crate::config::TargetSelection;
18 use crate::dist;
19 use crate::flags::Subcommand;
20 use crate::native;
21 use crate::tool::{self, SourceType, Tool};
22 use crate::toolstate::ToolState;
23 use crate::util::{self, add_link_lib_path, dylib_path, dylib_path_var, output, t};
24 use crate::{envify, CLang, DocTests, GitRepo, Mode};
25
26 const ADB_TEST_DIR: &str = "/data/local/tmp/work";
27
28 /// The two modes of the test runner; tests or benchmarks.
29 #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, PartialOrd, Ord)]
30 pub enum TestKind {
31     /// Run `cargo test`.
32     Test,
33     /// Run `cargo bench`.
34     Bench,
35 }
36
37 impl From<Kind> for TestKind {
38     fn from(kind: Kind) -> Self {
39         match kind {
40             Kind::Test => TestKind::Test,
41             Kind::Bench => TestKind::Bench,
42             _ => panic!("unexpected kind in crate: {:?}", kind),
43         }
44     }
45 }
46
47 impl TestKind {
48     // Return the cargo subcommand for this test kind
49     fn subcommand(self) -> &'static str {
50         match self {
51             TestKind::Test => "test",
52             TestKind::Bench => "bench",
53         }
54     }
55 }
56
57 impl fmt::Display for TestKind {
58     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59         f.write_str(match *self {
60             TestKind::Test => "Testing",
61             TestKind::Bench => "Benchmarking",
62         })
63     }
64 }
65
66 fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> bool {
67     if !builder.fail_fast {
68         if !builder.try_run(cmd) {
69             let mut failures = builder.delayed_failures.borrow_mut();
70             failures.push(format!("{:?}", cmd));
71             return false;
72         }
73     } else {
74         builder.run(cmd);
75     }
76     true
77 }
78
79 fn try_run_quiet(builder: &Builder<'_>, cmd: &mut Command) -> bool {
80     if !builder.fail_fast {
81         if !builder.try_run_quiet(cmd) {
82             let mut failures = builder.delayed_failures.borrow_mut();
83             failures.push(format!("{:?}", cmd));
84             return false;
85         }
86     } else {
87         builder.run_quiet(cmd);
88     }
89     true
90 }
91
92 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
93 pub struct Linkcheck {
94     host: TargetSelection,
95 }
96
97 impl Step for Linkcheck {
98     type Output = ();
99     const ONLY_HOSTS: bool = true;
100     const DEFAULT: bool = true;
101
102     /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
103     ///
104     /// This tool in `src/tools` will verify the validity of all our links in the
105     /// documentation to ensure we don't have a bunch of dead ones.
106     fn run(self, builder: &Builder<'_>) {
107         let host = self.host;
108         let hosts = &builder.hosts;
109         let targets = &builder.targets;
110
111         // if we have different hosts and targets, some things may be built for
112         // the host (e.g. rustc) and others for the target (e.g. std). The
113         // documentation built for each will contain broken links to
114         // docs built for the other platform (e.g. rustc linking to cargo)
115         if (hosts != targets) && !hosts.is_empty() && !targets.is_empty() {
116             panic!(
117                 "Linkcheck currently does not support builds with different hosts and targets.
118 You can skip linkcheck with --exclude src/tools/linkchecker"
119             );
120         }
121
122         builder.info(&format!("Linkcheck ({})", host));
123
124         // Test the linkchecker itself.
125         let bootstrap_host = builder.config.build;
126         let compiler = builder.compiler(0, bootstrap_host);
127         let cargo = tool::prepare_tool_cargo(
128             builder,
129             compiler,
130             Mode::ToolBootstrap,
131             bootstrap_host,
132             "test",
133             "src/tools/linkchecker",
134             SourceType::InTree,
135             &[],
136         );
137         try_run(builder, &mut cargo.into());
138
139         // Build all the default documentation.
140         builder.default_doc(&[]);
141
142         // Run the linkchecker.
143         let _time = util::timeit(&builder);
144         try_run(
145             builder,
146             builder.tool_cmd(Tool::Linkchecker).arg(builder.out.join(host.triple).join("doc")),
147         );
148     }
149
150     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
151         let builder = run.builder;
152         let run = run.path("src/tools/linkchecker");
153         run.default_condition(builder.config.docs)
154     }
155
156     fn make_run(run: RunConfig<'_>) {
157         run.builder.ensure(Linkcheck { host: run.target });
158     }
159 }
160
161 fn check_if_tidy_is_installed() -> bool {
162     Command::new("tidy")
163         .arg("--version")
164         .stdout(Stdio::null())
165         .status()
166         .map_or(false, |status| status.success())
167 }
168
169 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
170 pub struct HtmlCheck {
171     target: TargetSelection,
172 }
173
174 impl Step for HtmlCheck {
175     type Output = ();
176     const DEFAULT: bool = true;
177     const ONLY_HOSTS: bool = true;
178
179     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
180         let run = run.path("src/tools/html-checker");
181         run.lazy_default_condition(Box::new(check_if_tidy_is_installed))
182     }
183
184     fn make_run(run: RunConfig<'_>) {
185         run.builder.ensure(HtmlCheck { target: run.target });
186     }
187
188     fn run(self, builder: &Builder<'_>) {
189         if !check_if_tidy_is_installed() {
190             eprintln!("not running HTML-check tool because `tidy` is missing");
191             eprintln!(
192                 "Note that `tidy` is not the in-tree `src/tools/tidy` but needs to be installed"
193             );
194             panic!("Cannot run html-check tests");
195         }
196         // Ensure that a few different kinds of documentation are available.
197         builder.default_doc(&[]);
198         builder.ensure(crate::doc::Rustc { target: self.target, stage: builder.top_stage });
199
200         try_run(builder, builder.tool_cmd(Tool::HtmlChecker).arg(builder.doc_out(self.target)));
201     }
202 }
203
204 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
205 pub struct Cargotest {
206     stage: u32,
207     host: TargetSelection,
208 }
209
210 impl Step for Cargotest {
211     type Output = ();
212     const ONLY_HOSTS: bool = true;
213
214     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
215         run.path("src/tools/cargotest")
216     }
217
218     fn make_run(run: RunConfig<'_>) {
219         run.builder.ensure(Cargotest { stage: run.builder.top_stage, host: run.target });
220     }
221
222     /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
223     ///
224     /// This tool in `src/tools` will check out a few Rust projects and run `cargo
225     /// test` to ensure that we don't regress the test suites there.
226     fn run(self, builder: &Builder<'_>) {
227         let compiler = builder.compiler(self.stage, self.host);
228         builder.ensure(compile::Rustc::new(compiler, compiler.host));
229         let cargo = builder.ensure(tool::Cargo { compiler, target: compiler.host });
230
231         // Note that this is a short, cryptic, and not scoped directory name. This
232         // is currently to minimize the length of path on Windows where we otherwise
233         // quickly run into path name limit constraints.
234         let out_dir = builder.out.join("ct");
235         t!(fs::create_dir_all(&out_dir));
236
237         let _time = util::timeit(&builder);
238         let mut cmd = builder.tool_cmd(Tool::CargoTest);
239         try_run(
240             builder,
241             cmd.arg(&cargo)
242                 .arg(&out_dir)
243                 .args(builder.config.cmd.test_args())
244                 .env("RUSTC", builder.rustc(compiler))
245                 .env("RUSTDOC", builder.rustdoc(compiler)),
246         );
247     }
248 }
249
250 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
251 pub struct Cargo {
252     stage: u32,
253     host: TargetSelection,
254 }
255
256 impl Step for Cargo {
257     type Output = ();
258     const ONLY_HOSTS: bool = true;
259
260     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
261         run.path("src/tools/cargo")
262     }
263
264     fn make_run(run: RunConfig<'_>) {
265         run.builder.ensure(Cargo { stage: run.builder.top_stage, host: run.target });
266     }
267
268     /// Runs `cargo test` for `cargo` packaged with Rust.
269     fn run(self, builder: &Builder<'_>) {
270         let compiler = builder.compiler(self.stage, self.host);
271
272         builder.ensure(tool::Cargo { compiler, target: self.host });
273         let mut cargo = tool::prepare_tool_cargo(
274             builder,
275             compiler,
276             Mode::ToolRustc,
277             self.host,
278             "test",
279             "src/tools/cargo",
280             SourceType::Submodule,
281             &[],
282         );
283
284         if !builder.fail_fast {
285             cargo.arg("--no-fail-fast");
286         }
287         cargo.arg("--").args(builder.config.cmd.test_args());
288
289         // Don't run cross-compile tests, we may not have cross-compiled libstd libs
290         // available.
291         cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
292         // Forcibly disable tests using nightly features since any changes to
293         // those features won't be able to land.
294         cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1");
295
296         cargo.env("PATH", &path_for_cargo(builder, compiler));
297
298         try_run(builder, &mut cargo.into());
299     }
300 }
301
302 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
303 pub struct RustAnalyzer {
304     stage: u32,
305     host: TargetSelection,
306 }
307
308 impl Step for RustAnalyzer {
309     type Output = ();
310     const ONLY_HOSTS: bool = true;
311     const DEFAULT: bool = true;
312
313     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
314         run.path("src/tools/rust-analyzer")
315     }
316
317     fn make_run(run: RunConfig<'_>) {
318         run.builder.ensure(Self { stage: run.builder.top_stage, host: run.target });
319     }
320
321     /// Runs `cargo test` for rust-analyzer
322     fn run(self, builder: &Builder<'_>) {
323         let stage = self.stage;
324         let host = self.host;
325         let compiler = builder.compiler(stage, host);
326
327         builder.ensure(tool::RustAnalyzer { compiler, target: self.host }).expect("in-tree tool");
328
329         let workspace_path = "src/tools/rust-analyzer";
330         // until the whole RA test suite runs on `i686`, we only run
331         // `proc-macro-srv` tests
332         let crate_path = "src/tools/rust-analyzer/crates/proc-macro-srv";
333         let mut cargo = tool::prepare_tool_cargo(
334             builder,
335             compiler,
336             Mode::ToolStd,
337             host,
338             "test",
339             crate_path,
340             SourceType::InTree,
341             &["sysroot-abi".to_owned()],
342         );
343
344         let dir = builder.src.join(workspace_path);
345         // needed by rust-analyzer to find its own text fixtures, cf.
346         // https://github.com/rust-analyzer/expect-test/issues/33
347         cargo.env("CARGO_WORKSPACE_DIR", &dir);
348
349         // RA's test suite tries to write to the source directory, that can't
350         // work in Rust CI
351         cargo.env("SKIP_SLOW_TESTS", "1");
352
353         cargo.add_rustc_lib_path(builder, compiler);
354         cargo.arg("--").args(builder.config.cmd.test_args());
355
356         builder.run(&mut cargo.into());
357     }
358 }
359
360 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
361 pub struct Rustfmt {
362     stage: u32,
363     host: TargetSelection,
364 }
365
366 impl Step for Rustfmt {
367     type Output = ();
368     const ONLY_HOSTS: bool = true;
369
370     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
371         run.path("src/tools/rustfmt")
372     }
373
374     fn make_run(run: RunConfig<'_>) {
375         run.builder.ensure(Rustfmt { stage: run.builder.top_stage, host: run.target });
376     }
377
378     /// Runs `cargo test` for rustfmt.
379     fn run(self, builder: &Builder<'_>) {
380         let stage = self.stage;
381         let host = self.host;
382         let compiler = builder.compiler(stage, host);
383
384         builder
385             .ensure(tool::Rustfmt { compiler, target: self.host, extra_features: Vec::new() })
386             .expect("in-tree tool");
387
388         let mut cargo = tool::prepare_tool_cargo(
389             builder,
390             compiler,
391             Mode::ToolRustc,
392             host,
393             "test",
394             "src/tools/rustfmt",
395             SourceType::InTree,
396             &[],
397         );
398
399         let dir = testdir(builder, compiler.host);
400         t!(fs::create_dir_all(&dir));
401         cargo.env("RUSTFMT_TEST_DIR", dir);
402
403         cargo.add_rustc_lib_path(builder, compiler);
404
405         builder.run(&mut cargo.into());
406     }
407 }
408
409 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
410 pub struct RustDemangler {
411     stage: u32,
412     host: TargetSelection,
413 }
414
415 impl Step for RustDemangler {
416     type Output = ();
417     const ONLY_HOSTS: bool = true;
418
419     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
420         run.path("src/tools/rust-demangler")
421     }
422
423     fn make_run(run: RunConfig<'_>) {
424         run.builder.ensure(RustDemangler { stage: run.builder.top_stage, host: run.target });
425     }
426
427     /// Runs `cargo test` for rust-demangler.
428     fn run(self, builder: &Builder<'_>) {
429         let stage = self.stage;
430         let host = self.host;
431         let compiler = builder.compiler(stage, host);
432
433         let rust_demangler = builder
434             .ensure(tool::RustDemangler { compiler, target: self.host, extra_features: Vec::new() })
435             .expect("in-tree tool");
436         let mut cargo = tool::prepare_tool_cargo(
437             builder,
438             compiler,
439             Mode::ToolRustc,
440             host,
441             "test",
442             "src/tools/rust-demangler",
443             SourceType::InTree,
444             &[],
445         );
446
447         let dir = testdir(builder, compiler.host);
448         t!(fs::create_dir_all(&dir));
449
450         cargo.env("RUST_DEMANGLER_DRIVER_PATH", rust_demangler);
451
452         cargo.arg("--").args(builder.config.cmd.test_args());
453
454         cargo.add_rustc_lib_path(builder, compiler);
455
456         builder.run(&mut cargo.into());
457     }
458 }
459
460 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
461 pub struct Miri {
462     stage: u32,
463     host: TargetSelection,
464     target: TargetSelection,
465 }
466
467 impl Miri {
468     /// Run `cargo miri setup` for the given target, return where the Miri sysroot was put.
469     pub fn build_miri_sysroot(
470         builder: &Builder<'_>,
471         compiler: Compiler,
472         miri: &Path,
473         target: TargetSelection,
474     ) -> String {
475         let miri_sysroot = builder.out.join(compiler.host.triple).join("miri-sysrot");
476         let mut cargo = tool::prepare_tool_cargo(
477             builder,
478             compiler,
479             Mode::ToolRustc,
480             compiler.host,
481             "run",
482             "src/tools/miri/cargo-miri",
483             SourceType::InTree,
484             &[],
485         );
486         cargo.add_rustc_lib_path(builder, compiler);
487         cargo.arg("--").arg("miri").arg("setup");
488         cargo.arg("--target").arg(target.rustc_target_arg());
489
490         // Tell `cargo miri setup` where to find the sources.
491         cargo.env("MIRI_LIB_SRC", builder.src.join("library"));
492         // Tell it where to find Miri.
493         cargo.env("MIRI", &miri);
494         // Tell it where to put the sysroot.
495         cargo.env("MIRI_SYSROOT", &miri_sysroot);
496         // Debug things.
497         cargo.env("RUST_BACKTRACE", "1");
498
499         let mut cargo = Command::from(cargo);
500         builder.run(&mut cargo);
501
502         // # Determine where Miri put its sysroot.
503         // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
504         // (We do this separately from the above so that when the setup actually
505         // happens we get some output.)
506         // We re-use the `cargo` from above.
507         cargo.arg("--print-sysroot");
508
509         // FIXME: Is there a way in which we can re-use the usual `run` helpers?
510         if builder.config.dry_run {
511             String::new()
512         } else {
513             builder.verbose(&format!("running: {:?}", cargo));
514             let out =
515                 cargo.output().expect("We already ran `cargo miri setup` before and that worked");
516             assert!(out.status.success(), "`cargo miri setup` returned with non-0 exit code");
517             // Output is "<sysroot>\n".
518             let stdout = String::from_utf8(out.stdout)
519                 .expect("`cargo miri setup` stdout is not valid UTF-8");
520             let sysroot = stdout.trim_end();
521             builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {:?}", sysroot));
522             sysroot.to_owned()
523         }
524     }
525 }
526
527 impl Step for Miri {
528     type Output = ();
529     const ONLY_HOSTS: bool = false;
530
531     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
532         run.path("src/tools/miri")
533     }
534
535     fn make_run(run: RunConfig<'_>) {
536         run.builder.ensure(Miri {
537             stage: run.builder.top_stage,
538             host: run.build_triple(),
539             target: run.target,
540         });
541     }
542
543     /// Runs `cargo test` for miri.
544     fn run(self, builder: &Builder<'_>) {
545         let stage = self.stage;
546         let host = self.host;
547         let target = self.target;
548         let compiler = builder.compiler(stage, host);
549         // We need the stdlib for the *next* stage, as it was built with this compiler that also built Miri.
550         // Except if we are at stage 2, the bootstrap loop is complete and we can stick with our current stage.
551         let compiler_std = builder.compiler(if stage < 2 { stage + 1 } else { stage }, host);
552
553         let miri = builder
554             .ensure(tool::Miri { compiler, target: self.host, extra_features: Vec::new() })
555             .expect("in-tree tool");
556         let _cargo_miri = builder
557             .ensure(tool::CargoMiri { compiler, target: self.host, extra_features: Vec::new() })
558             .expect("in-tree tool");
559         // The stdlib we need might be at a different stage. And just asking for the
560         // sysroot does not seem to populate it, so we do that first.
561         builder.ensure(compile::Std::new(compiler_std, host));
562         let sysroot = builder.sysroot(compiler_std);
563         // We also need a Miri sysroot.
564         let miri_sysroot = Miri::build_miri_sysroot(builder, compiler, &miri, target);
565
566         // # Run `cargo test`.
567         let mut cargo = tool::prepare_tool_cargo(
568             builder,
569             compiler,
570             Mode::ToolRustc,
571             host,
572             "test",
573             "src/tools/miri",
574             SourceType::InTree,
575             &[],
576         );
577         cargo.add_rustc_lib_path(builder, compiler);
578
579         // miri tests need to know about the stage sysroot
580         cargo.env("MIRI_SYSROOT", &miri_sysroot);
581         cargo.env("MIRI_HOST_SYSROOT", sysroot);
582         cargo.env("MIRI", &miri);
583         // propagate --bless
584         if builder.config.cmd.bless() {
585             cargo.env("MIRI_BLESS", "Gesundheit");
586         }
587
588         // Set the target.
589         cargo.env("MIRI_TEST_TARGET", target.rustc_target_arg());
590         // Forward test filters.
591         cargo.arg("--").args(builder.config.cmd.test_args());
592
593         let mut cargo = Command::from(cargo);
594         builder.run(&mut cargo);
595
596         // # Run `cargo miri test`.
597         // This is just a smoke test (Miri's own CI invokes this in a bunch of different ways and ensures
598         // that we get the desired output), but that is sufficient to make sure that the libtest harness
599         // itself executes properly under Miri.
600         let mut cargo = tool::prepare_tool_cargo(
601             builder,
602             compiler,
603             Mode::ToolRustc,
604             host,
605             "run",
606             "src/tools/miri/cargo-miri",
607             SourceType::Submodule,
608             &[],
609         );
610         cargo.add_rustc_lib_path(builder, compiler);
611         cargo.arg("--").arg("miri").arg("test");
612         cargo
613             .arg("--manifest-path")
614             .arg(builder.src.join("src/tools/miri/test-cargo-miri/Cargo.toml"));
615         cargo.arg("--target").arg(target.rustc_target_arg());
616         cargo.arg("--tests"); // don't run doctests, they are too confused by the staging
617         cargo.arg("--").args(builder.config.cmd.test_args());
618
619         // Tell `cargo miri` where to find things.
620         cargo.env("MIRI_SYSROOT", &miri_sysroot);
621         cargo.env("MIRI_HOST_SYSROOT", sysroot);
622         cargo.env("MIRI", &miri);
623         // Debug things.
624         cargo.env("RUST_BACKTRACE", "1");
625
626         let mut cargo = Command::from(cargo);
627         builder.run(&mut cargo);
628     }
629 }
630
631 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
632 pub struct CompiletestTest {
633     host: TargetSelection,
634 }
635
636 impl Step for CompiletestTest {
637     type Output = ();
638
639     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
640         run.path("src/tools/compiletest")
641     }
642
643     fn make_run(run: RunConfig<'_>) {
644         run.builder.ensure(CompiletestTest { host: run.target });
645     }
646
647     /// Runs `cargo test` for compiletest.
648     fn run(self, builder: &Builder<'_>) {
649         let host = self.host;
650         let compiler = builder.compiler(0, host);
651
652         // We need `ToolStd` for the locally-built sysroot because
653         // compiletest uses unstable features of the `test` crate.
654         builder.ensure(compile::Std::new(compiler, host));
655         let cargo = tool::prepare_tool_cargo(
656             builder,
657             compiler,
658             Mode::ToolStd,
659             host,
660             "test",
661             "src/tools/compiletest",
662             SourceType::InTree,
663             &[],
664         );
665
666         try_run(builder, &mut cargo.into());
667     }
668 }
669
670 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
671 pub struct Clippy {
672     stage: u32,
673     host: TargetSelection,
674 }
675
676 impl Step for Clippy {
677     type Output = ();
678     const ONLY_HOSTS: bool = true;
679     const DEFAULT: bool = false;
680
681     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
682         run.path("src/tools/clippy")
683     }
684
685     fn make_run(run: RunConfig<'_>) {
686         run.builder.ensure(Clippy { stage: run.builder.top_stage, host: run.target });
687     }
688
689     /// Runs `cargo test` for clippy.
690     fn run(self, builder: &Builder<'_>) {
691         let stage = self.stage;
692         let host = self.host;
693         let compiler = builder.compiler(stage, host);
694
695         builder
696             .ensure(tool::Clippy { compiler, target: self.host, extra_features: Vec::new() })
697             .expect("in-tree tool");
698         let mut cargo = tool::prepare_tool_cargo(
699             builder,
700             compiler,
701             Mode::ToolRustc,
702             host,
703             "test",
704             "src/tools/clippy",
705             SourceType::InTree,
706             &[],
707         );
708
709         cargo.env("RUSTC_TEST_SUITE", builder.rustc(compiler));
710         cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
711         let host_libs = builder.stage_out(compiler, Mode::ToolRustc).join(builder.cargo_dir());
712         cargo.env("HOST_LIBS", host_libs);
713
714         cargo.arg("--").args(builder.config.cmd.test_args());
715
716         cargo.add_rustc_lib_path(builder, compiler);
717
718         if builder.try_run(&mut cargo.into()) {
719             // The tests succeeded; nothing to do.
720             return;
721         }
722
723         if !builder.config.cmd.bless() {
724             crate::detail_exit(1);
725         }
726
727         let mut cargo = builder.cargo(compiler, Mode::ToolRustc, SourceType::InTree, host, "run");
728         cargo.arg("-p").arg("clippy_dev");
729         // clippy_dev gets confused if it can't find `clippy/Cargo.toml`
730         cargo.current_dir(&builder.src.join("src").join("tools").join("clippy"));
731         if builder.config.rust_optimize {
732             cargo.env("PROFILE", "release");
733         } else {
734             cargo.env("PROFILE", "debug");
735         }
736         cargo.arg("--");
737         cargo.arg("bless");
738         builder.run(&mut cargo.into());
739     }
740 }
741
742 fn path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString {
743     // Configure PATH to find the right rustc. NB. we have to use PATH
744     // and not RUSTC because the Cargo test suite has tests that will
745     // fail if rustc is not spelled `rustc`.
746     let path = builder.sysroot(compiler).join("bin");
747     let old_path = env::var_os("PATH").unwrap_or_default();
748     env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
749 }
750
751 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
752 pub struct RustdocTheme {
753     pub compiler: Compiler,
754 }
755
756 impl Step for RustdocTheme {
757     type Output = ();
758     const DEFAULT: bool = true;
759     const ONLY_HOSTS: bool = true;
760
761     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
762         run.path("src/tools/rustdoc-themes")
763     }
764
765     fn make_run(run: RunConfig<'_>) {
766         let compiler = run.builder.compiler(run.builder.top_stage, run.target);
767
768         run.builder.ensure(RustdocTheme { compiler });
769     }
770
771     fn run(self, builder: &Builder<'_>) {
772         let rustdoc = builder.bootstrap_out.join("rustdoc");
773         let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
774         cmd.arg(rustdoc.to_str().unwrap())
775             .arg(builder.src.join("src/librustdoc/html/static/css/themes").to_str().unwrap())
776             .env("RUSTC_STAGE", self.compiler.stage.to_string())
777             .env("RUSTC_SYSROOT", builder.sysroot(self.compiler))
778             .env("RUSTDOC_LIBDIR", builder.sysroot_libdir(self.compiler, self.compiler.host))
779             .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
780             .env("RUSTDOC_REAL", builder.rustdoc(self.compiler))
781             .env("RUSTC_BOOTSTRAP", "1");
782         if let Some(linker) = builder.linker(self.compiler.host) {
783             cmd.env("RUSTDOC_LINKER", linker);
784         }
785         if builder.is_fuse_ld_lld(self.compiler.host) {
786             cmd.env(
787                 "RUSTDOC_LLD_NO_THREADS",
788                 util::lld_flag_no_threads(self.compiler.host.contains("windows")),
789             );
790         }
791         try_run(builder, &mut cmd);
792     }
793 }
794
795 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
796 pub struct RustdocJSStd {
797     pub target: TargetSelection,
798 }
799
800 impl Step for RustdocJSStd {
801     type Output = ();
802     const DEFAULT: bool = true;
803     const ONLY_HOSTS: bool = true;
804
805     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
806         run.suite_path("src/test/rustdoc-js-std")
807     }
808
809     fn make_run(run: RunConfig<'_>) {
810         run.builder.ensure(RustdocJSStd { target: run.target });
811     }
812
813     fn run(self, builder: &Builder<'_>) {
814         if let Some(ref nodejs) = builder.config.nodejs {
815             let mut command = Command::new(nodejs);
816             command
817                 .arg(builder.src.join("src/tools/rustdoc-js/tester.js"))
818                 .arg("--crate-name")
819                 .arg("std")
820                 .arg("--resource-suffix")
821                 .arg(&builder.version)
822                 .arg("--doc-folder")
823                 .arg(builder.doc_out(self.target))
824                 .arg("--test-folder")
825                 .arg(builder.src.join("src/test/rustdoc-js-std"));
826             for path in &builder.paths {
827                 if let Some(p) =
828                     util::is_valid_test_suite_arg(path, "src/test/rustdoc-js-std", builder)
829                 {
830                     if !p.ends_with(".js") {
831                         eprintln!("A non-js file was given: `{}`", path.display());
832                         panic!("Cannot run rustdoc-js-std tests");
833                     }
834                     command.arg("--test-file").arg(path);
835                 }
836             }
837             builder.ensure(crate::doc::Std { target: self.target, stage: builder.top_stage });
838             builder.run(&mut command);
839         } else {
840             builder.info("No nodejs found, skipping \"src/test/rustdoc-js-std\" tests");
841         }
842     }
843 }
844
845 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
846 pub struct RustdocJSNotStd {
847     pub target: TargetSelection,
848     pub compiler: Compiler,
849 }
850
851 impl Step for RustdocJSNotStd {
852     type Output = ();
853     const DEFAULT: bool = true;
854     const ONLY_HOSTS: bool = true;
855
856     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
857         run.suite_path("src/test/rustdoc-js")
858     }
859
860     fn make_run(run: RunConfig<'_>) {
861         let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
862         run.builder.ensure(RustdocJSNotStd { target: run.target, compiler });
863     }
864
865     fn run(self, builder: &Builder<'_>) {
866         if builder.config.nodejs.is_some() {
867             builder.ensure(Compiletest {
868                 compiler: self.compiler,
869                 target: self.target,
870                 mode: "js-doc-test",
871                 suite: "rustdoc-js",
872                 path: "src/test/rustdoc-js",
873                 compare_mode: None,
874             });
875         } else {
876             builder.info("No nodejs found, skipping \"src/test/rustdoc-js\" tests");
877         }
878     }
879 }
880
881 fn get_browser_ui_test_version_inner(npm: &Path, global: bool) -> Option<String> {
882     let mut command = Command::new(&npm);
883     command.arg("list").arg("--parseable").arg("--long").arg("--depth=0");
884     if global {
885         command.arg("--global");
886     }
887     let lines = command
888         .output()
889         .map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
890         .unwrap_or(String::new());
891     lines
892         .lines()
893         .find_map(|l| l.split(':').nth(1)?.strip_prefix("browser-ui-test@"))
894         .map(|v| v.to_owned())
895 }
896
897 fn get_browser_ui_test_version(npm: &Path) -> Option<String> {
898     get_browser_ui_test_version_inner(npm, false)
899         .or_else(|| get_browser_ui_test_version_inner(npm, true))
900 }
901
902 fn compare_browser_ui_test_version(installed_version: &str, src: &Path) {
903     match fs::read_to_string(
904         src.join("src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version"),
905     ) {
906         Ok(v) => {
907             if v.trim() != installed_version {
908                 eprintln!(
909                     "⚠️ Installed version of browser-ui-test (`{}`) is different than the \
910                      one used in the CI (`{}`)",
911                     installed_version, v
912                 );
913                 eprintln!(
914                     "You can install this version using `npm update browser-ui-test` or by using \
915                      `npm install browser-ui-test@{}`",
916                     v,
917                 );
918             }
919         }
920         Err(e) => eprintln!("Couldn't find the CI browser-ui-test version: {:?}", e),
921     }
922 }
923
924 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
925 pub struct RustdocGUI {
926     pub target: TargetSelection,
927     pub compiler: Compiler,
928 }
929
930 impl Step for RustdocGUI {
931     type Output = ();
932     const DEFAULT: bool = true;
933     const ONLY_HOSTS: bool = true;
934
935     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
936         let builder = run.builder;
937         let run = run.suite_path("src/test/rustdoc-gui");
938         run.lazy_default_condition(Box::new(move || {
939             builder.config.nodejs.is_some()
940                 && builder
941                     .config
942                     .npm
943                     .as_ref()
944                     .map(|p| get_browser_ui_test_version(p).is_some())
945                     .unwrap_or(false)
946         }))
947     }
948
949     fn make_run(run: RunConfig<'_>) {
950         let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
951         run.builder.ensure(RustdocGUI { target: run.target, compiler });
952     }
953
954     fn run(self, builder: &Builder<'_>) {
955         let nodejs = builder.config.nodejs.as_ref().expect("nodejs isn't available");
956         let npm = builder.config.npm.as_ref().expect("npm isn't available");
957
958         builder.ensure(compile::Std::new(self.compiler, self.target));
959
960         // The goal here is to check if the necessary packages are installed, and if not, we
961         // panic.
962         match get_browser_ui_test_version(&npm) {
963             Some(version) => {
964                 // We also check the version currently used in CI and emit a warning if it's not the
965                 // same one.
966                 compare_browser_ui_test_version(&version, &builder.build.src);
967             }
968             None => {
969                 eprintln!(
970                     "error: rustdoc-gui test suite cannot be run because npm `browser-ui-test` \
971                      dependency is missing",
972                 );
973                 eprintln!(
974                     "If you want to install the `{0}` dependency, run `npm install {0}`",
975                     "browser-ui-test",
976                 );
977                 panic!("Cannot run rustdoc-gui tests");
978             }
979         }
980
981         let out_dir = builder.test_out(self.target).join("rustdoc-gui");
982
983         // We remove existing folder to be sure there won't be artifacts remaining.
984         builder.clear_if_dirty(&out_dir, &builder.rustdoc(self.compiler));
985
986         let src_path = builder.build.src.join("src/test/rustdoc-gui/src");
987         // We generate docs for the libraries present in the rustdoc-gui's src folder.
988         for entry in src_path.read_dir().expect("read_dir call failed") {
989             if let Ok(entry) = entry {
990                 let path = entry.path();
991
992                 if !path.is_dir() {
993                     continue;
994                 }
995
996                 let mut cargo = Command::new(&builder.initial_cargo);
997                 cargo
998                     .arg("doc")
999                     .arg("--target-dir")
1000                     .arg(&out_dir)
1001                     .env("RUSTC_BOOTSTRAP", "1")
1002                     .env("RUSTDOC", builder.rustdoc(self.compiler))
1003                     .env("RUSTC", builder.rustc(self.compiler))
1004                     .current_dir(path);
1005                 // FIXME: implement a `// compile-flags` command or similar
1006                 //        instead of hard-coding this test
1007                 if entry.file_name() == "link_to_definition" {
1008                     cargo.env("RUSTDOCFLAGS", "-Zunstable-options --generate-link-to-definition");
1009                 }
1010                 builder.run(&mut cargo);
1011             }
1012         }
1013
1014         // We now run GUI tests.
1015         let mut command = Command::new(&nodejs);
1016         command
1017             .arg(builder.build.src.join("src/tools/rustdoc-gui/tester.js"))
1018             .arg("--jobs")
1019             .arg(&builder.jobs().to_string())
1020             .arg("--doc-folder")
1021             .arg(out_dir.join("doc"))
1022             .arg("--tests-folder")
1023             .arg(builder.build.src.join("src/test/rustdoc-gui"));
1024         for path in &builder.paths {
1025             if let Some(p) = util::is_valid_test_suite_arg(path, "src/test/rustdoc-gui", builder) {
1026                 if !p.ends_with(".goml") {
1027                     eprintln!("A non-goml file was given: `{}`", path.display());
1028                     panic!("Cannot run rustdoc-gui tests");
1029                 }
1030                 if let Some(name) = path.file_name().and_then(|f| f.to_str()) {
1031                     command.arg("--file").arg(name);
1032                 }
1033             }
1034         }
1035         for test_arg in builder.config.cmd.test_args() {
1036             command.arg(test_arg);
1037         }
1038         builder.run(&mut command);
1039     }
1040 }
1041
1042 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1043 pub struct Tidy;
1044
1045 impl Step for Tidy {
1046     type Output = ();
1047     const DEFAULT: bool = true;
1048     const ONLY_HOSTS: bool = true;
1049
1050     /// Runs the `tidy` tool.
1051     ///
1052     /// This tool in `src/tools` checks up on various bits and pieces of style and
1053     /// otherwise just implements a few lint-like checks that are specific to the
1054     /// compiler itself.
1055     ///
1056     /// Once tidy passes, this step also runs `fmt --check` if tests are being run
1057     /// for the `dev` or `nightly` channels.
1058     fn run(self, builder: &Builder<'_>) {
1059         let mut cmd = builder.tool_cmd(Tool::Tidy);
1060         cmd.arg(&builder.src);
1061         cmd.arg(&builder.initial_cargo);
1062         cmd.arg(&builder.out);
1063         cmd.arg(builder.jobs().to_string());
1064         if builder.is_verbose() {
1065             cmd.arg("--verbose");
1066         }
1067         if builder.config.cmd.bless() {
1068             cmd.arg("--bless");
1069         }
1070
1071         builder.info("tidy check");
1072         try_run(builder, &mut cmd);
1073
1074         if builder.config.channel == "dev" || builder.config.channel == "nightly" {
1075             builder.info("fmt check");
1076             if builder.initial_rustfmt().is_none() {
1077                 let inferred_rustfmt_dir = builder.config.initial_rustc.parent().unwrap();
1078                 eprintln!(
1079                     "\
1080 error: no `rustfmt` binary found in {PATH}
1081 info: `rust.channel` is currently set to \"{CHAN}\"
1082 help: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `config.toml` file
1083 help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` to `x.py test`",
1084                     PATH = inferred_rustfmt_dir.display(),
1085                     CHAN = builder.config.channel,
1086                 );
1087                 crate::detail_exit(1);
1088             }
1089             crate::format::format(&builder, !builder.config.cmd.bless(), &[]);
1090         }
1091     }
1092
1093     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1094         run.path("src/tools/tidy")
1095     }
1096
1097     fn make_run(run: RunConfig<'_>) {
1098         run.builder.ensure(Tidy);
1099     }
1100 }
1101
1102 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1103 pub struct ExpandYamlAnchors;
1104
1105 impl Step for ExpandYamlAnchors {
1106     type Output = ();
1107     const ONLY_HOSTS: bool = true;
1108
1109     /// Ensure the `generate-ci-config` tool was run locally.
1110     ///
1111     /// The tool in `src/tools` reads the CI definition in `src/ci/builders.yml` and generates the
1112     /// appropriate configuration for all our CI providers. This step ensures the tool was called
1113     /// by the user before committing CI changes.
1114     fn run(self, builder: &Builder<'_>) {
1115         builder.info("Ensuring the YAML anchors in the GitHub Actions config were expanded");
1116         try_run(
1117             builder,
1118             &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("check").arg(&builder.src),
1119         );
1120     }
1121
1122     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1123         run.path("src/tools/expand-yaml-anchors")
1124     }
1125
1126     fn make_run(run: RunConfig<'_>) {
1127         run.builder.ensure(ExpandYamlAnchors);
1128     }
1129 }
1130
1131 fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
1132     builder.out.join(host.triple).join("test")
1133 }
1134
1135 macro_rules! default_test {
1136     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
1137         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: false });
1138     };
1139 }
1140
1141 macro_rules! default_test_with_compare_mode {
1142     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr,
1143                    compare_mode: $compare_mode:expr }) => {
1144         test_with_compare_mode!($name {
1145             path: $path,
1146             mode: $mode,
1147             suite: $suite,
1148             default: true,
1149             host: false,
1150             compare_mode: $compare_mode
1151         });
1152     };
1153 }
1154
1155 macro_rules! host_test {
1156     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
1157         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: true });
1158     };
1159 }
1160
1161 macro_rules! test {
1162     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1163                    host: $host:expr }) => {
1164         test_definitions!($name {
1165             path: $path,
1166             mode: $mode,
1167             suite: $suite,
1168             default: $default,
1169             host: $host,
1170             compare_mode: None
1171         });
1172     };
1173 }
1174
1175 macro_rules! test_with_compare_mode {
1176     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1177                    host: $host:expr, compare_mode: $compare_mode:expr }) => {
1178         test_definitions!($name {
1179             path: $path,
1180             mode: $mode,
1181             suite: $suite,
1182             default: $default,
1183             host: $host,
1184             compare_mode: Some($compare_mode)
1185         });
1186     };
1187 }
1188
1189 macro_rules! test_definitions {
1190     ($name:ident {
1191         path: $path:expr,
1192         mode: $mode:expr,
1193         suite: $suite:expr,
1194         default: $default:expr,
1195         host: $host:expr,
1196         compare_mode: $compare_mode:expr
1197     }) => {
1198         #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1199         pub struct $name {
1200             pub compiler: Compiler,
1201             pub target: TargetSelection,
1202         }
1203
1204         impl Step for $name {
1205             type Output = ();
1206             const DEFAULT: bool = $default;
1207             const ONLY_HOSTS: bool = $host;
1208
1209             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1210                 run.suite_path($path)
1211             }
1212
1213             fn make_run(run: RunConfig<'_>) {
1214                 let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1215
1216                 run.builder.ensure($name { compiler, target: run.target });
1217             }
1218
1219             fn run(self, builder: &Builder<'_>) {
1220                 builder.ensure(Compiletest {
1221                     compiler: self.compiler,
1222                     target: self.target,
1223                     mode: $mode,
1224                     suite: $suite,
1225                     path: $path,
1226                     compare_mode: $compare_mode,
1227                 })
1228             }
1229         }
1230     };
1231 }
1232
1233 default_test!(Ui { path: "src/test/ui", mode: "ui", suite: "ui" });
1234
1235 default_test!(RunPassValgrind {
1236     path: "src/test/run-pass-valgrind",
1237     mode: "run-pass-valgrind",
1238     suite: "run-pass-valgrind"
1239 });
1240
1241 default_test!(MirOpt { path: "src/test/mir-opt", mode: "mir-opt", suite: "mir-opt" });
1242
1243 default_test!(Codegen { path: "src/test/codegen", mode: "codegen", suite: "codegen" });
1244
1245 default_test!(CodegenUnits {
1246     path: "src/test/codegen-units",
1247     mode: "codegen-units",
1248     suite: "codegen-units"
1249 });
1250
1251 default_test!(Incremental {
1252     path: "src/test/incremental",
1253     mode: "incremental",
1254     suite: "incremental"
1255 });
1256
1257 default_test_with_compare_mode!(Debuginfo {
1258     path: "src/test/debuginfo",
1259     mode: "debuginfo",
1260     suite: "debuginfo",
1261     compare_mode: "split-dwarf"
1262 });
1263
1264 host_test!(UiFullDeps { path: "src/test/ui-fulldeps", mode: "ui", suite: "ui-fulldeps" });
1265
1266 host_test!(Rustdoc { path: "src/test/rustdoc", mode: "rustdoc", suite: "rustdoc" });
1267 host_test!(RustdocUi { path: "src/test/rustdoc-ui", mode: "ui", suite: "rustdoc-ui" });
1268
1269 host_test!(RustdocJson {
1270     path: "src/test/rustdoc-json",
1271     mode: "rustdoc-json",
1272     suite: "rustdoc-json"
1273 });
1274
1275 host_test!(Pretty { path: "src/test/pretty", mode: "pretty", suite: "pretty" });
1276
1277 default_test!(RunMake { path: "src/test/run-make", mode: "run-make", suite: "run-make" });
1278
1279 host_test!(RunMakeFullDeps {
1280     path: "src/test/run-make-fulldeps",
1281     mode: "run-make",
1282     suite: "run-make-fulldeps"
1283 });
1284
1285 default_test!(Assembly { path: "src/test/assembly", mode: "assembly", suite: "assembly" });
1286
1287 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1288 struct Compiletest {
1289     compiler: Compiler,
1290     target: TargetSelection,
1291     mode: &'static str,
1292     suite: &'static str,
1293     path: &'static str,
1294     compare_mode: Option<&'static str>,
1295 }
1296
1297 impl Step for Compiletest {
1298     type Output = ();
1299
1300     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1301         run.never()
1302     }
1303
1304     /// Executes the `compiletest` tool to run a suite of tests.
1305     ///
1306     /// Compiles all tests with `compiler` for `target` with the specified
1307     /// compiletest `mode` and `suite` arguments. For example `mode` can be
1308     /// "run-pass" or `suite` can be something like `debuginfo`.
1309     fn run(self, builder: &Builder<'_>) {
1310         if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() {
1311             eprintln!("\
1312 error: `--stage 0` runs compiletest on the beta compiler, not your local changes, and will almost always cause tests to fail
1313 help: to test the compiler, use `--stage 1` instead
1314 help: to test the standard library, use `--stage 0 library/std` instead
1315 note: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `COMPILETEST_FORCE_STAGE0=1`."
1316             );
1317             crate::detail_exit(1);
1318         }
1319
1320         let compiler = self.compiler;
1321         let target = self.target;
1322         let mode = self.mode;
1323         let suite = self.suite;
1324
1325         // Path for test suite
1326         let suite_path = self.path;
1327
1328         // Skip codegen tests if they aren't enabled in configuration.
1329         if !builder.config.codegen_tests && suite == "codegen" {
1330             return;
1331         }
1332
1333         if suite == "debuginfo" {
1334             builder
1335                 .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target });
1336         }
1337
1338         if suite.ends_with("fulldeps") {
1339             builder.ensure(compile::Rustc::new(compiler, target));
1340         }
1341
1342         builder.ensure(compile::Std::new(compiler, target));
1343         // ensure that `libproc_macro` is available on the host.
1344         builder.ensure(compile::Std::new(compiler, compiler.host));
1345
1346         // Also provide `rust_test_helpers` for the host.
1347         builder.ensure(native::TestHelpers { target: compiler.host });
1348
1349         // As well as the target, except for plain wasm32, which can't build it
1350         if !target.contains("wasm") || target.contains("emscripten") {
1351             builder.ensure(native::TestHelpers { target });
1352         }
1353
1354         builder.ensure(RemoteCopyLibs { compiler, target });
1355
1356         let mut cmd = builder.tool_cmd(Tool::Compiletest);
1357
1358         // compiletest currently has... a lot of arguments, so let's just pass all
1359         // of them!
1360
1361         cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
1362         cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
1363         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1364
1365         let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js");
1366
1367         // Avoid depending on rustdoc when we don't need it.
1368         if mode == "rustdoc"
1369             || mode == "run-make"
1370             || (mode == "ui" && is_rustdoc)
1371             || mode == "js-doc-test"
1372             || mode == "rustdoc-json"
1373         {
1374             cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
1375         }
1376
1377         if mode == "rustdoc-json" {
1378             // Use the beta compiler for jsondocck
1379             let json_compiler = compiler.with_stage(0);
1380             cmd.arg("--jsondocck-path")
1381                 .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }));
1382             cmd.arg("--jsondoclint-path")
1383                 .arg(builder.ensure(tool::JsonDocLint { compiler: json_compiler, target }));
1384         }
1385
1386         if mode == "run-make" {
1387             let rust_demangler = builder
1388                 .ensure(tool::RustDemangler {
1389                     compiler,
1390                     target: compiler.host,
1391                     extra_features: Vec::new(),
1392                 })
1393                 .expect("in-tree tool");
1394             cmd.arg("--rust-demangler-path").arg(rust_demangler);
1395         }
1396
1397         cmd.arg("--src-base").arg(builder.src.join("src/test").join(suite));
1398         cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite));
1399         cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
1400         cmd.arg("--suite").arg(suite);
1401         cmd.arg("--mode").arg(mode);
1402         cmd.arg("--target").arg(target.rustc_target_arg());
1403         cmd.arg("--host").arg(&*compiler.host.triple);
1404         cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.build));
1405
1406         if builder.config.cmd.bless() {
1407             cmd.arg("--bless");
1408         }
1409
1410         if builder.config.cmd.force_rerun() {
1411             cmd.arg("--force-rerun");
1412         }
1413
1414         let compare_mode =
1415             builder.config.cmd.compare_mode().or_else(|| {
1416                 if builder.config.test_compare_mode { self.compare_mode } else { None }
1417             });
1418
1419         if let Some(ref pass) = builder.config.cmd.pass() {
1420             cmd.arg("--pass");
1421             cmd.arg(pass);
1422         }
1423
1424         if let Some(ref run) = builder.config.cmd.run() {
1425             cmd.arg("--run");
1426             cmd.arg(run);
1427         }
1428
1429         if let Some(ref nodejs) = builder.config.nodejs {
1430             cmd.arg("--nodejs").arg(nodejs);
1431         }
1432         if let Some(ref npm) = builder.config.npm {
1433             cmd.arg("--npm").arg(npm);
1434         }
1435         if builder.config.rust_optimize_tests {
1436             cmd.arg("--optimize-tests");
1437         }
1438         let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
1439         flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
1440         flags.extend(builder.config.cmd.rustc_args().iter().map(|s| s.to_string()));
1441
1442         if let Some(linker) = builder.linker(target) {
1443             cmd.arg("--linker").arg(linker);
1444         }
1445
1446         let mut hostflags = flags.clone();
1447         hostflags.push(format!("-Lnative={}", builder.test_helpers_out(compiler.host).display()));
1448         hostflags.extend(builder.lld_flags(compiler.host));
1449         for flag in hostflags {
1450             cmd.arg("--host-rustcflags").arg(flag);
1451         }
1452
1453         let mut targetflags = flags;
1454         targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
1455         targetflags.extend(builder.lld_flags(target));
1456         for flag in targetflags {
1457             cmd.arg("--target-rustcflags").arg(flag);
1458         }
1459
1460         cmd.arg("--python").arg(builder.python());
1461
1462         if let Some(ref gdb) = builder.config.gdb {
1463             cmd.arg("--gdb").arg(gdb);
1464         }
1465
1466         let run = |cmd: &mut Command| {
1467             cmd.output().map(|output| {
1468                 String::from_utf8_lossy(&output.stdout)
1469                     .lines()
1470                     .next()
1471                     .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output))
1472                     .to_string()
1473             })
1474         };
1475         let lldb_exe = "lldb";
1476         let lldb_version = Command::new(lldb_exe)
1477             .arg("--version")
1478             .output()
1479             .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
1480             .ok();
1481         if let Some(ref vers) = lldb_version {
1482             cmd.arg("--lldb-version").arg(vers);
1483             let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok();
1484             if let Some(ref dir) = lldb_python_dir {
1485                 cmd.arg("--lldb-python-dir").arg(dir);
1486             }
1487         }
1488
1489         if util::forcing_clang_based_tests() {
1490             let clang_exe = builder.llvm_out(target).join("bin").join("clang");
1491             cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
1492         }
1493
1494         for exclude in &builder.config.exclude {
1495             cmd.arg("--skip");
1496             cmd.arg(&exclude.path);
1497         }
1498
1499         // Get paths from cmd args
1500         let paths = match &builder.config.cmd {
1501             Subcommand::Test { ref paths, .. } => &paths[..],
1502             _ => &[],
1503         };
1504
1505         // Get test-args by striping suite path
1506         let mut test_args: Vec<&str> = paths
1507             .iter()
1508             .filter_map(|p| util::is_valid_test_suite_arg(p, suite_path, builder))
1509             .collect();
1510
1511         test_args.append(&mut builder.config.cmd.test_args());
1512
1513         // On Windows, replace forward slashes in test-args by backslashes
1514         // so the correct filters are passed to libtest
1515         if cfg!(windows) {
1516             let test_args_win: Vec<String> =
1517                 test_args.iter().map(|s| s.replace("/", "\\")).collect();
1518             cmd.args(&test_args_win);
1519         } else {
1520             cmd.args(&test_args);
1521         }
1522
1523         if builder.is_verbose() {
1524             cmd.arg("--verbose");
1525         }
1526
1527         if !builder.config.verbose_tests {
1528             cmd.arg("--quiet");
1529         }
1530
1531         let mut llvm_components_passed = false;
1532         let mut copts_passed = false;
1533         if builder.config.llvm_enabled() {
1534             let llvm_config = builder.ensure(native::Llvm { target: builder.config.build });
1535             if !builder.config.dry_run {
1536                 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1537                 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1538                 // Remove trailing newline from llvm-config output.
1539                 cmd.arg("--llvm-version")
1540                     .arg(llvm_version.trim())
1541                     .arg("--llvm-components")
1542                     .arg(llvm_components.trim());
1543                 llvm_components_passed = true;
1544             }
1545             if !builder.is_rust_llvm(target) {
1546                 cmd.arg("--system-llvm");
1547             }
1548
1549             // Tests that use compiler libraries may inherit the `-lLLVM` link
1550             // requirement, but the `-L` library path is not propagated across
1551             // separate compilations. We can add LLVM's library path to the
1552             // platform-specific environment variable as a workaround.
1553             if !builder.config.dry_run && suite.ends_with("fulldeps") {
1554                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1555                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cmd);
1556             }
1557
1558             // Only pass correct values for these flags for the `run-make` suite as it
1559             // requires that a C++ compiler was configured which isn't always the case.
1560             if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1561                 // The llvm/bin directory contains many useful cross-platform
1562                 // tools. Pass the path to run-make tests so they can use them.
1563                 let llvm_bin_path = llvm_config
1564                     .parent()
1565                     .expect("Expected llvm-config to be contained in directory");
1566                 assert!(llvm_bin_path.is_dir());
1567                 cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1568
1569                 // If LLD is available, add it to the PATH
1570                 if builder.config.lld_enabled {
1571                     let lld_install_root =
1572                         builder.ensure(native::Lld { target: builder.config.build });
1573
1574                     let lld_bin_path = lld_install_root.join("bin");
1575
1576                     let old_path = env::var_os("PATH").unwrap_or_default();
1577                     let new_path = env::join_paths(
1578                         std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
1579                     )
1580                     .expect("Could not add LLD bin path to PATH");
1581                     cmd.env("PATH", new_path);
1582                 }
1583             }
1584         }
1585
1586         // Only pass correct values for these flags for the `run-make` suite as it
1587         // requires that a C++ compiler was configured which isn't always the case.
1588         if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1589             cmd.arg("--cc")
1590                 .arg(builder.cc(target))
1591                 .arg("--cxx")
1592                 .arg(builder.cxx(target).unwrap())
1593                 .arg("--cflags")
1594                 .arg(builder.cflags(target, GitRepo::Rustc, CLang::C).join(" "))
1595                 .arg("--cxxflags")
1596                 .arg(builder.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" "));
1597             copts_passed = true;
1598             if let Some(ar) = builder.ar(target) {
1599                 cmd.arg("--ar").arg(ar);
1600             }
1601         }
1602
1603         if !llvm_components_passed {
1604             cmd.arg("--llvm-components").arg("");
1605         }
1606         if !copts_passed {
1607             cmd.arg("--cc")
1608                 .arg("")
1609                 .arg("--cxx")
1610                 .arg("")
1611                 .arg("--cflags")
1612                 .arg("")
1613                 .arg("--cxxflags")
1614                 .arg("");
1615         }
1616
1617         if builder.remote_tested(target) {
1618             cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
1619         }
1620
1621         // Running a C compiler on MSVC requires a few env vars to be set, to be
1622         // sure to set them here.
1623         //
1624         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
1625         // rather than stomp over it.
1626         if target.contains("msvc") {
1627             for &(ref k, ref v) in builder.cc[&target].env() {
1628                 if k != "PATH" {
1629                     cmd.env(k, v);
1630                 }
1631             }
1632         }
1633         cmd.env("RUSTC_BOOTSTRAP", "1");
1634         // Override the rustc version used in symbol hashes to reduce the amount of normalization
1635         // needed when diffing test output.
1636         cmd.env("RUSTC_FORCE_RUSTC_VERSION", "compiletest");
1637         cmd.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
1638         builder.add_rust_test_threads(&mut cmd);
1639
1640         if builder.config.sanitizers_enabled(target) {
1641             cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1642         }
1643
1644         if builder.config.profiler_enabled(target) {
1645             cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1646         }
1647
1648         cmd.env("RUST_TEST_TMPDIR", builder.tempdir());
1649
1650         cmd.arg("--adb-path").arg("adb");
1651         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
1652         if target.contains("android") {
1653             // Assume that cc for this target comes from the android sysroot
1654             cmd.arg("--android-cross-path")
1655                 .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1656         } else {
1657             cmd.arg("--android-cross-path").arg("");
1658         }
1659
1660         if builder.config.cmd.rustfix_coverage() {
1661             cmd.arg("--rustfix-coverage");
1662         }
1663
1664         cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo);
1665
1666         cmd.arg("--channel").arg(&builder.config.channel);
1667
1668         builder.ci_env.force_coloring_in_ci(&mut cmd);
1669
1670         builder.info(&format!(
1671             "Check compiletest suite={} mode={} ({} -> {})",
1672             suite, mode, &compiler.host, target
1673         ));
1674         let _time = util::timeit(&builder);
1675         try_run(builder, &mut cmd);
1676
1677         if let Some(compare_mode) = compare_mode {
1678             cmd.arg("--compare-mode").arg(compare_mode);
1679             builder.info(&format!(
1680                 "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
1681                 suite, mode, compare_mode, &compiler.host, target
1682             ));
1683             let _time = util::timeit(&builder);
1684             try_run(builder, &mut cmd);
1685         }
1686     }
1687 }
1688
1689 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1690 struct BookTest {
1691     compiler: Compiler,
1692     path: PathBuf,
1693     name: &'static str,
1694     is_ext_doc: bool,
1695 }
1696
1697 impl Step for BookTest {
1698     type Output = ();
1699     const ONLY_HOSTS: bool = true;
1700
1701     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1702         run.never()
1703     }
1704
1705     /// Runs the documentation tests for a book in `src/doc`.
1706     ///
1707     /// This uses the `rustdoc` that sits next to `compiler`.
1708     fn run(self, builder: &Builder<'_>) {
1709         // External docs are different from local because:
1710         // - Some books need pre-processing by mdbook before being tested.
1711         // - They need to save their state to toolstate.
1712         // - They are only tested on the "checktools" builders.
1713         //
1714         // The local docs are tested by default, and we don't want to pay the
1715         // cost of building mdbook, so they use `rustdoc --test` directly.
1716         // Also, the unstable book is special because SUMMARY.md is generated,
1717         // so it is easier to just run `rustdoc` on its files.
1718         if self.is_ext_doc {
1719             self.run_ext_doc(builder);
1720         } else {
1721             self.run_local_doc(builder);
1722         }
1723     }
1724 }
1725
1726 impl BookTest {
1727     /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
1728     /// which in turn runs `rustdoc --test` on each file in the book.
1729     fn run_ext_doc(self, builder: &Builder<'_>) {
1730         let compiler = self.compiler;
1731
1732         builder.ensure(compile::Std::new(compiler, compiler.host));
1733
1734         // mdbook just executes a binary named "rustdoc", so we need to update
1735         // PATH so that it points to our rustdoc.
1736         let mut rustdoc_path = builder.rustdoc(compiler);
1737         rustdoc_path.pop();
1738         let old_path = env::var_os("PATH").unwrap_or_default();
1739         let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
1740             .expect("could not add rustdoc to PATH");
1741
1742         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1743         let path = builder.src.join(&self.path);
1744         // Books often have feature-gated example text.
1745         rustbook_cmd.env("RUSTC_BOOTSTRAP", "1");
1746         rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
1747         builder.add_rust_test_threads(&mut rustbook_cmd);
1748         builder.info(&format!("Testing rustbook {}", self.path.display()));
1749         let _time = util::timeit(&builder);
1750         let toolstate = if try_run(builder, &mut rustbook_cmd) {
1751             ToolState::TestPass
1752         } else {
1753             ToolState::TestFail
1754         };
1755         builder.save_toolstate(self.name, toolstate);
1756     }
1757
1758     /// This runs `rustdoc --test` on all `.md` files in the path.
1759     fn run_local_doc(self, builder: &Builder<'_>) {
1760         let compiler = self.compiler;
1761
1762         builder.ensure(compile::Std::new(compiler, compiler.host));
1763
1764         // Do a breadth-first traversal of the `src/doc` directory and just run
1765         // tests for all files that end in `*.md`
1766         let mut stack = vec![builder.src.join(self.path)];
1767         let _time = util::timeit(&builder);
1768         let mut files = Vec::new();
1769         while let Some(p) = stack.pop() {
1770             if p.is_dir() {
1771                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
1772                 continue;
1773             }
1774
1775             if p.extension().and_then(|s| s.to_str()) != Some("md") {
1776                 continue;
1777             }
1778
1779             files.push(p);
1780         }
1781
1782         files.sort();
1783
1784         for file in files {
1785             markdown_test(builder, compiler, &file);
1786         }
1787     }
1788 }
1789
1790 macro_rules! test_book {
1791     ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
1792         $(
1793             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1794             pub struct $name {
1795                 compiler: Compiler,
1796             }
1797
1798             impl Step for $name {
1799                 type Output = ();
1800                 const DEFAULT: bool = $default;
1801                 const ONLY_HOSTS: bool = true;
1802
1803                 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1804                     run.path($path)
1805                 }
1806
1807                 fn make_run(run: RunConfig<'_>) {
1808                     run.builder.ensure($name {
1809                         compiler: run.builder.compiler(run.builder.top_stage, run.target),
1810                     });
1811                 }
1812
1813                 fn run(self, builder: &Builder<'_>) {
1814                     builder.ensure(BookTest {
1815                         compiler: self.compiler,
1816                         path: PathBuf::from($path),
1817                         name: $book_name,
1818                         is_ext_doc: !$default,
1819                     });
1820                 }
1821             }
1822         )+
1823     }
1824 }
1825
1826 test_book!(
1827     Nomicon, "src/doc/nomicon", "nomicon", default=false;
1828     Reference, "src/doc/reference", "reference", default=false;
1829     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1830     RustcBook, "src/doc/rustc", "rustc", default=true;
1831     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1832     EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1833     TheBook, "src/doc/book", "book", default=false;
1834     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
1835     EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1836 );
1837
1838 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1839 pub struct ErrorIndex {
1840     compiler: Compiler,
1841 }
1842
1843 impl Step for ErrorIndex {
1844     type Output = ();
1845     const DEFAULT: bool = true;
1846     const ONLY_HOSTS: bool = true;
1847
1848     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1849         run.path("src/tools/error_index_generator")
1850     }
1851
1852     fn make_run(run: RunConfig<'_>) {
1853         // error_index_generator depends on librustdoc. Use the compiler that
1854         // is normally used to build rustdoc for other tests (like compiletest
1855         // tests in src/test/rustdoc) so that it shares the same artifacts.
1856         let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
1857         run.builder.ensure(ErrorIndex { compiler });
1858     }
1859
1860     /// Runs the error index generator tool to execute the tests located in the error
1861     /// index.
1862     ///
1863     /// The `error_index_generator` tool lives in `src/tools` and is used to
1864     /// generate a markdown file from the error indexes of the code base which is
1865     /// then passed to `rustdoc --test`.
1866     fn run(self, builder: &Builder<'_>) {
1867         let compiler = self.compiler;
1868
1869         let dir = testdir(builder, compiler.host);
1870         t!(fs::create_dir_all(&dir));
1871         let output = dir.join("error-index.md");
1872
1873         let mut tool = tool::ErrorIndex::command(builder);
1874         tool.arg("markdown").arg(&output);
1875
1876         builder.info(&format!("Testing error-index stage{}", compiler.stage));
1877         let _time = util::timeit(&builder);
1878         builder.run_quiet(&mut tool);
1879         // The tests themselves need to link to std, so make sure it is
1880         // available.
1881         builder.ensure(compile::Std::new(compiler, compiler.host));
1882         markdown_test(builder, compiler, &output);
1883     }
1884 }
1885
1886 fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1887     if let Ok(contents) = fs::read_to_string(markdown) {
1888         if !contents.contains("```") {
1889             return true;
1890         }
1891     }
1892
1893     builder.info(&format!("doc tests for: {}", markdown.display()));
1894     let mut cmd = builder.rustdoc_cmd(compiler);
1895     builder.add_rust_test_threads(&mut cmd);
1896     // allow for unstable options such as new editions
1897     cmd.arg("-Z");
1898     cmd.arg("unstable-options");
1899     cmd.arg("--test");
1900     cmd.arg(markdown);
1901     cmd.env("RUSTC_BOOTSTRAP", "1");
1902
1903     let test_args = builder.config.cmd.test_args().join(" ");
1904     cmd.arg("--test-args").arg(test_args);
1905
1906     if builder.config.verbose_tests {
1907         try_run(builder, &mut cmd)
1908     } else {
1909         try_run_quiet(builder, &mut cmd)
1910     }
1911 }
1912
1913 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1914 pub struct RustcGuide;
1915
1916 impl Step for RustcGuide {
1917     type Output = ();
1918     const DEFAULT: bool = false;
1919     const ONLY_HOSTS: bool = true;
1920
1921     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1922         run.path("src/doc/rustc-dev-guide")
1923     }
1924
1925     fn make_run(run: RunConfig<'_>) {
1926         run.builder.ensure(RustcGuide);
1927     }
1928
1929     fn run(self, builder: &Builder<'_>) {
1930         let relative_path = Path::new("src").join("doc").join("rustc-dev-guide");
1931         builder.update_submodule(&relative_path);
1932
1933         let src = builder.src.join(relative_path);
1934         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1935         let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
1936             ToolState::TestPass
1937         } else {
1938             ToolState::TestFail
1939         };
1940         builder.save_toolstate("rustc-dev-guide", toolstate);
1941     }
1942 }
1943
1944 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1945 pub struct CrateLibrustc {
1946     compiler: Compiler,
1947     target: TargetSelection,
1948     test_kind: TestKind,
1949     crates: Vec<Interned<String>>,
1950 }
1951
1952 impl Step for CrateLibrustc {
1953     type Output = ();
1954     const DEFAULT: bool = true;
1955     const ONLY_HOSTS: bool = true;
1956
1957     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1958         run.crate_or_deps("rustc-main")
1959     }
1960
1961     fn make_run(run: RunConfig<'_>) {
1962         let builder = run.builder;
1963         let host = run.build_triple();
1964         let compiler = builder.compiler_for(builder.top_stage, host, host);
1965         let crates = run
1966             .paths
1967             .iter()
1968             .map(|p| builder.crate_paths[&p.assert_single_path().path].clone())
1969             .collect();
1970         let test_kind = builder.kind.into();
1971
1972         builder.ensure(CrateLibrustc { compiler, target: run.target, test_kind, crates });
1973     }
1974
1975     fn run(self, builder: &Builder<'_>) {
1976         builder.ensure(Crate {
1977             compiler: self.compiler,
1978             target: self.target,
1979             mode: Mode::Rustc,
1980             test_kind: self.test_kind,
1981             crates: self.crates,
1982         });
1983     }
1984 }
1985
1986 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1987 pub struct Crate {
1988     pub compiler: Compiler,
1989     pub target: TargetSelection,
1990     pub mode: Mode,
1991     pub test_kind: TestKind,
1992     pub crates: Vec<Interned<String>>,
1993 }
1994
1995 impl Step for Crate {
1996     type Output = ();
1997     const DEFAULT: bool = true;
1998
1999     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2000         run.crate_or_deps("test")
2001     }
2002
2003     fn make_run(run: RunConfig<'_>) {
2004         let builder = run.builder;
2005         let host = run.build_triple();
2006         let compiler = builder.compiler_for(builder.top_stage, host, host);
2007         let test_kind = builder.kind.into();
2008         let crates = run
2009             .paths
2010             .iter()
2011             .map(|p| builder.crate_paths[&p.assert_single_path().path].clone())
2012             .collect();
2013
2014         builder.ensure(Crate { compiler, target: run.target, mode: Mode::Std, test_kind, crates });
2015     }
2016
2017     /// Runs all unit tests plus documentation tests for a given crate defined
2018     /// by a `Cargo.toml` (single manifest)
2019     ///
2020     /// This is what runs tests for crates like the standard library, compiler, etc.
2021     /// It essentially is the driver for running `cargo test`.
2022     ///
2023     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
2024     /// arguments, and those arguments are discovered from `cargo metadata`.
2025     fn run(self, builder: &Builder<'_>) {
2026         let compiler = self.compiler;
2027         let target = self.target;
2028         let mode = self.mode;
2029         let test_kind = self.test_kind;
2030
2031         builder.ensure(compile::Std::new(compiler, target));
2032         builder.ensure(RemoteCopyLibs { compiler, target });
2033
2034         // If we're not doing a full bootstrap but we're testing a stage2
2035         // version of libstd, then what we're actually testing is the libstd
2036         // produced in stage1. Reflect that here by updating the compiler that
2037         // we're working with automatically.
2038         let compiler = builder.compiler_for(compiler.stage, compiler.host, target);
2039
2040         let mut cargo =
2041             builder.cargo(compiler, mode, SourceType::InTree, target, test_kind.subcommand());
2042         match mode {
2043             Mode::Std => {
2044                 compile::std_cargo(builder, target, compiler.stage, &mut cargo);
2045             }
2046             Mode::Rustc => {
2047                 compile::rustc_cargo(builder, &mut cargo, target);
2048             }
2049             _ => panic!("can only test libraries"),
2050         };
2051
2052         // Build up the base `cargo test` command.
2053         //
2054         // Pass in some standard flags then iterate over the graph we've discovered
2055         // in `cargo metadata` with the maps above and figure out what `-p`
2056         // arguments need to get passed.
2057         if test_kind.subcommand() == "test" && !builder.fail_fast {
2058             cargo.arg("--no-fail-fast");
2059         }
2060         match builder.doc_tests {
2061             DocTests::Only => {
2062                 cargo.arg("--doc");
2063             }
2064             DocTests::No => {
2065                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2066             }
2067             DocTests::Yes => {}
2068         }
2069
2070         for krate in &self.crates {
2071             cargo.arg("-p").arg(krate);
2072         }
2073
2074         // The tests are going to run with the *target* libraries, so we need to
2075         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
2076         //
2077         // Note that to run the compiler we need to run with the *host* libraries,
2078         // but our wrapper scripts arrange for that to be the case anyway.
2079         let mut dylib_path = dylib_path();
2080         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
2081         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
2082
2083         cargo.arg("--");
2084         cargo.args(&builder.config.cmd.test_args());
2085
2086         if !builder.config.verbose_tests {
2087             cargo.arg("--quiet");
2088         }
2089
2090         if target.contains("emscripten") {
2091             cargo.env(
2092                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2093                 builder.config.nodejs.as_ref().expect("nodejs not configured"),
2094             );
2095         } else if target.starts_with("wasm32") {
2096             let node = builder.config.nodejs.as_ref().expect("nodejs not configured");
2097             let runner =
2098                 format!("{} {}/src/etc/wasm32-shim.js", node.display(), builder.src.display());
2099             cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), &runner);
2100         } else if builder.remote_tested(target) {
2101             cargo.env(
2102                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2103                 format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
2104             );
2105         }
2106
2107         builder.info(&format!(
2108             "{} {:?} stage{} ({} -> {})",
2109             test_kind, self.crates, compiler.stage, &compiler.host, target
2110         ));
2111         let _time = util::timeit(&builder);
2112         try_run(builder, &mut cargo.into());
2113     }
2114 }
2115
2116 /// Rustdoc is special in various ways, which is why this step is different from `Crate`.
2117 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2118 pub struct CrateRustdoc {
2119     host: TargetSelection,
2120     test_kind: TestKind,
2121 }
2122
2123 impl Step for CrateRustdoc {
2124     type Output = ();
2125     const DEFAULT: bool = true;
2126     const ONLY_HOSTS: bool = true;
2127
2128     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2129         run.paths(&["src/librustdoc", "src/tools/rustdoc"])
2130     }
2131
2132     fn make_run(run: RunConfig<'_>) {
2133         let builder = run.builder;
2134
2135         let test_kind = builder.kind.into();
2136
2137         builder.ensure(CrateRustdoc { host: run.target, test_kind });
2138     }
2139
2140     fn run(self, builder: &Builder<'_>) {
2141         let test_kind = self.test_kind;
2142         let target = self.host;
2143
2144         let compiler = if builder.download_rustc() {
2145             builder.compiler(builder.top_stage, target)
2146         } else {
2147             // Use the previous stage compiler to reuse the artifacts that are
2148             // created when running compiletest for src/test/rustdoc. If this used
2149             // `compiler`, then it would cause rustdoc to be built *again*, which
2150             // isn't really necessary.
2151             builder.compiler_for(builder.top_stage, target, target)
2152         };
2153         builder.ensure(compile::Rustc::new(compiler, target));
2154
2155         let mut cargo = tool::prepare_tool_cargo(
2156             builder,
2157             compiler,
2158             Mode::ToolRustc,
2159             target,
2160             test_kind.subcommand(),
2161             "src/tools/rustdoc",
2162             SourceType::InTree,
2163             &[],
2164         );
2165         if test_kind.subcommand() == "test" && !builder.fail_fast {
2166             cargo.arg("--no-fail-fast");
2167         }
2168         match builder.doc_tests {
2169             DocTests::Only => {
2170                 cargo.arg("--doc");
2171             }
2172             DocTests::No => {
2173                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2174             }
2175             DocTests::Yes => {}
2176         }
2177
2178         cargo.arg("-p").arg("rustdoc:0.0.0");
2179
2180         cargo.arg("--");
2181         cargo.args(&builder.config.cmd.test_args());
2182
2183         if self.host.contains("musl") {
2184             cargo.arg("'-Ctarget-feature=-crt-static'");
2185         }
2186
2187         // This is needed for running doctests on librustdoc. This is a bit of
2188         // an unfortunate interaction with how bootstrap works and how cargo
2189         // sets up the dylib path, and the fact that the doctest (in
2190         // html/markdown.rs) links to rustc-private libs. For stage1, the
2191         // compiler host dylibs (in stage1/lib) are not the same as the target
2192         // dylibs (in stage1/lib/rustlib/...). This is different from a normal
2193         // rust distribution where they are the same.
2194         //
2195         // On the cargo side, normal tests use `target_process` which handles
2196         // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
2197         // case). However, for doctests it uses `rustdoc_process` which only
2198         // sets up the dylib path for the *host* (stage1/lib), which is the
2199         // wrong directory.
2200         //
2201         // Recall that we special-cased `compiler_for(top_stage)` above, so we always use stage1.
2202         //
2203         // It should be considered to just stop running doctests on
2204         // librustdoc. There is only one test, and it doesn't look too
2205         // important. There might be other ways to avoid this, but it seems
2206         // pretty convoluted.
2207         //
2208         // See also https://github.com/rust-lang/rust/issues/13983 where the
2209         // host vs target dylibs for rustdoc are consistently tricky to deal
2210         // with.
2211         //
2212         // Note that this set the host libdir for `download_rustc`, which uses a normal rust distribution.
2213         let libdir = if builder.download_rustc() {
2214             builder.rustc_libdir(compiler)
2215         } else {
2216             builder.sysroot_libdir(compiler, target).to_path_buf()
2217         };
2218         let mut dylib_path = dylib_path();
2219         dylib_path.insert(0, PathBuf::from(&*libdir));
2220         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
2221
2222         if !builder.config.verbose_tests {
2223             cargo.arg("--quiet");
2224         }
2225
2226         builder.info(&format!(
2227             "{} rustdoc stage{} ({} -> {})",
2228             test_kind, compiler.stage, &compiler.host, target
2229         ));
2230         let _time = util::timeit(&builder);
2231
2232         try_run(builder, &mut cargo.into());
2233     }
2234 }
2235
2236 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2237 pub struct CrateRustdocJsonTypes {
2238     host: TargetSelection,
2239     test_kind: TestKind,
2240 }
2241
2242 impl Step for CrateRustdocJsonTypes {
2243     type Output = ();
2244     const DEFAULT: bool = true;
2245     const ONLY_HOSTS: bool = true;
2246
2247     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2248         run.path("src/rustdoc-json-types")
2249     }
2250
2251     fn make_run(run: RunConfig<'_>) {
2252         let builder = run.builder;
2253
2254         let test_kind = builder.kind.into();
2255
2256         builder.ensure(CrateRustdocJsonTypes { host: run.target, test_kind });
2257     }
2258
2259     fn run(self, builder: &Builder<'_>) {
2260         let test_kind = self.test_kind;
2261         let target = self.host;
2262
2263         // Use the previous stage compiler to reuse the artifacts that are
2264         // created when running compiletest for src/test/rustdoc. If this used
2265         // `compiler`, then it would cause rustdoc to be built *again*, which
2266         // isn't really necessary.
2267         let compiler = builder.compiler_for(builder.top_stage, target, target);
2268         builder.ensure(compile::Rustc::new(compiler, target));
2269
2270         let mut cargo = tool::prepare_tool_cargo(
2271             builder,
2272             compiler,
2273             Mode::ToolRustc,
2274             target,
2275             test_kind.subcommand(),
2276             "src/rustdoc-json-types",
2277             SourceType::InTree,
2278             &[],
2279         );
2280         if test_kind.subcommand() == "test" && !builder.fail_fast {
2281             cargo.arg("--no-fail-fast");
2282         }
2283
2284         cargo.arg("-p").arg("rustdoc-json-types");
2285
2286         cargo.arg("--");
2287         cargo.args(&builder.config.cmd.test_args());
2288
2289         if self.host.contains("musl") {
2290             cargo.arg("'-Ctarget-feature=-crt-static'");
2291         }
2292
2293         if !builder.config.verbose_tests {
2294             cargo.arg("--quiet");
2295         }
2296
2297         builder.info(&format!(
2298             "{} rustdoc-json-types stage{} ({} -> {})",
2299             test_kind, compiler.stage, &compiler.host, target
2300         ));
2301         let _time = util::timeit(&builder);
2302
2303         try_run(builder, &mut cargo.into());
2304     }
2305 }
2306
2307 /// Some test suites are run inside emulators or on remote devices, and most
2308 /// of our test binaries are linked dynamically which means we need to ship
2309 /// the standard library and such to the emulator ahead of time. This step
2310 /// represents this and is a dependency of all test suites.
2311 ///
2312 /// Most of the time this is a no-op. For some steps such as shipping data to
2313 /// QEMU we have to build our own tools so we've got conditional dependencies
2314 /// on those programs as well. Note that the remote test client is built for
2315 /// the build target (us) and the server is built for the target.
2316 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2317 pub struct RemoteCopyLibs {
2318     compiler: Compiler,
2319     target: TargetSelection,
2320 }
2321
2322 impl Step for RemoteCopyLibs {
2323     type Output = ();
2324
2325     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2326         run.never()
2327     }
2328
2329     fn run(self, builder: &Builder<'_>) {
2330         let compiler = self.compiler;
2331         let target = self.target;
2332         if !builder.remote_tested(target) {
2333             return;
2334         }
2335
2336         builder.ensure(compile::Std::new(compiler, target));
2337
2338         builder.info(&format!("REMOTE copy libs to emulator ({})", target));
2339
2340         let server = builder.ensure(tool::RemoteTestServer { compiler, target });
2341
2342         // Spawn the emulator and wait for it to come online
2343         let tool = builder.tool_exe(Tool::RemoteTestClient);
2344         let mut cmd = Command::new(&tool);
2345         cmd.arg("spawn-emulator").arg(target.triple).arg(&server).arg(builder.tempdir());
2346         if let Some(rootfs) = builder.qemu_rootfs(target) {
2347             cmd.arg(rootfs);
2348         }
2349         builder.run(&mut cmd);
2350
2351         // Push all our dylibs to the emulator
2352         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
2353             let f = t!(f);
2354             let name = f.file_name().into_string().unwrap();
2355             if util::is_dylib(&name) {
2356                 builder.run(Command::new(&tool).arg("push").arg(f.path()));
2357             }
2358         }
2359     }
2360 }
2361
2362 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2363 pub struct Distcheck;
2364
2365 impl Step for Distcheck {
2366     type Output = ();
2367
2368     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2369         run.alias("distcheck")
2370     }
2371
2372     fn make_run(run: RunConfig<'_>) {
2373         run.builder.ensure(Distcheck);
2374     }
2375
2376     /// Runs "distcheck", a 'make check' from a tarball
2377     fn run(self, builder: &Builder<'_>) {
2378         builder.info("Distcheck");
2379         let dir = builder.tempdir().join("distcheck");
2380         let _ = fs::remove_dir_all(&dir);
2381         t!(fs::create_dir_all(&dir));
2382
2383         // Guarantee that these are built before we begin running.
2384         builder.ensure(dist::PlainSourceTarball);
2385         builder.ensure(dist::Src);
2386
2387         let mut cmd = Command::new("tar");
2388         cmd.arg("-xf")
2389             .arg(builder.ensure(dist::PlainSourceTarball).tarball())
2390             .arg("--strip-components=1")
2391             .current_dir(&dir);
2392         builder.run(&mut cmd);
2393         builder.run(
2394             Command::new("./configure")
2395                 .args(&builder.config.configure_args)
2396                 .arg("--enable-vendor")
2397                 .current_dir(&dir),
2398         );
2399         builder.run(
2400             Command::new(util::make(&builder.config.build.triple)).arg("check").current_dir(&dir),
2401         );
2402
2403         // Now make sure that rust-src has all of libstd's dependencies
2404         builder.info("Distcheck rust-src");
2405         let dir = builder.tempdir().join("distcheck-src");
2406         let _ = fs::remove_dir_all(&dir);
2407         t!(fs::create_dir_all(&dir));
2408
2409         let mut cmd = Command::new("tar");
2410         cmd.arg("-xf")
2411             .arg(builder.ensure(dist::Src).tarball())
2412             .arg("--strip-components=1")
2413             .current_dir(&dir);
2414         builder.run(&mut cmd);
2415
2416         let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
2417         builder.run(
2418             Command::new(&builder.initial_cargo)
2419                 .arg("generate-lockfile")
2420                 .arg("--manifest-path")
2421                 .arg(&toml)
2422                 .current_dir(&dir),
2423         );
2424     }
2425 }
2426
2427 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2428 pub struct Bootstrap;
2429
2430 impl Step for Bootstrap {
2431     type Output = ();
2432     const DEFAULT: bool = true;
2433     const ONLY_HOSTS: bool = true;
2434
2435     /// Tests the build system itself.
2436     fn run(self, builder: &Builder<'_>) {
2437         let mut check_bootstrap = Command::new(&builder.python());
2438         check_bootstrap.arg("bootstrap_test.py").current_dir(builder.src.join("src/bootstrap/"));
2439         try_run(builder, &mut check_bootstrap);
2440
2441         let mut cmd = Command::new(&builder.initial_cargo);
2442         cmd.arg("test")
2443             .current_dir(builder.src.join("src/bootstrap"))
2444             .env("RUSTFLAGS", "-Cdebuginfo=2")
2445             .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2446             .env("RUSTC_BOOTSTRAP", "1")
2447             .env("RUSTDOC", builder.rustdoc(builder.compiler(0, builder.build.build)))
2448             .env("RUSTC", &builder.initial_rustc);
2449         if let Some(flags) = option_env!("RUSTFLAGS") {
2450             // Use the same rustc flags for testing as for "normal" compilation,
2451             // so that Cargo doesn’t recompile the entire dependency graph every time:
2452             // https://github.com/rust-lang/rust/issues/49215
2453             cmd.env("RUSTFLAGS", flags);
2454         }
2455         if !builder.fail_fast {
2456             cmd.arg("--no-fail-fast");
2457         }
2458         match builder.doc_tests {
2459             DocTests::Only => {
2460                 cmd.arg("--doc");
2461             }
2462             DocTests::No => {
2463                 cmd.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2464             }
2465             DocTests::Yes => {}
2466         }
2467
2468         cmd.arg("--").args(&builder.config.cmd.test_args());
2469         // rustbuild tests are racy on directory creation so just run them one at a time.
2470         // Since there's not many this shouldn't be a problem.
2471         cmd.arg("--test-threads=1");
2472         try_run(builder, &mut cmd);
2473     }
2474
2475     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2476         run.path("src/bootstrap")
2477     }
2478
2479     fn make_run(run: RunConfig<'_>) {
2480         run.builder.ensure(Bootstrap);
2481     }
2482 }
2483
2484 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2485 pub struct TierCheck {
2486     pub compiler: Compiler,
2487 }
2488
2489 impl Step for TierCheck {
2490     type Output = ();
2491     const DEFAULT: bool = true;
2492     const ONLY_HOSTS: bool = true;
2493
2494     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2495         run.path("src/tools/tier-check")
2496     }
2497
2498     fn make_run(run: RunConfig<'_>) {
2499         let compiler =
2500             run.builder.compiler_for(run.builder.top_stage, run.builder.build.build, run.target);
2501         run.builder.ensure(TierCheck { compiler });
2502     }
2503
2504     /// Tests the Platform Support page in the rustc book.
2505     fn run(self, builder: &Builder<'_>) {
2506         builder.ensure(compile::Std::new(self.compiler, self.compiler.host));
2507         let mut cargo = tool::prepare_tool_cargo(
2508             builder,
2509             self.compiler,
2510             Mode::ToolStd,
2511             self.compiler.host,
2512             "run",
2513             "src/tools/tier-check",
2514             SourceType::InTree,
2515             &[],
2516         );
2517         cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
2518         cargo.arg(&builder.rustc(self.compiler));
2519         if builder.is_verbose() {
2520             cargo.arg("--verbose");
2521         }
2522
2523         builder.info("platform support check");
2524         try_run(builder, &mut cargo.into());
2525     }
2526 }
2527
2528 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2529 pub struct ReplacePlaceholderTest;
2530
2531 impl Step for ReplacePlaceholderTest {
2532     type Output = ();
2533     const ONLY_HOSTS: bool = true;
2534     const DEFAULT: bool = true;
2535
2536     /// Ensure the version placeholder replacement tool builds
2537     fn run(self, builder: &Builder<'_>) {
2538         builder.info("build check for version replacement placeholder");
2539
2540         // Test the version placeholder replacement tool itself.
2541         let bootstrap_host = builder.config.build;
2542         let compiler = builder.compiler(0, bootstrap_host);
2543         let cargo = tool::prepare_tool_cargo(
2544             builder,
2545             compiler,
2546             Mode::ToolBootstrap,
2547             bootstrap_host,
2548             "test",
2549             "src/tools/replace-version-placeholder",
2550             SourceType::InTree,
2551             &[],
2552         );
2553         try_run(builder, &mut cargo.into());
2554     }
2555
2556     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2557         run.path("src/tools/replace-version-placeholder")
2558     }
2559
2560     fn make_run(run: RunConfig<'_>) {
2561         run.builder.ensure(Self);
2562     }
2563 }
2564
2565 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2566 pub struct LintDocs {
2567     pub compiler: Compiler,
2568     pub target: TargetSelection,
2569 }
2570
2571 impl Step for LintDocs {
2572     type Output = ();
2573     const DEFAULT: bool = true;
2574     const ONLY_HOSTS: bool = true;
2575
2576     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2577         run.path("src/tools/lint-docs")
2578     }
2579
2580     fn make_run(run: RunConfig<'_>) {
2581         run.builder.ensure(LintDocs {
2582             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
2583             target: run.target,
2584         });
2585     }
2586
2587     /// Tests that the lint examples in the rustc book generate the correct
2588     /// lints and have the expected format.
2589     fn run(self, builder: &Builder<'_>) {
2590         builder.ensure(crate::doc::RustcBook {
2591             compiler: self.compiler,
2592             target: self.target,
2593             validate: true,
2594         });
2595     }
2596 }