bootstrap/core/build_steps/
test.rs

1//! Build-and-run steps for `./x.py test` test fixtures
2//!
3//! `./x.py test` (aka [`Kind::Test`]) is currently allowed to reach build steps in other modules.
4//! However, this contains ~all test parts we expect people to be able to build and run locally.
5
6// (This file should be split up, but having tidy block all changes is not helpful.)
7// ignore-tidy-filelength
8
9use std::collections::HashSet;
10use std::env::split_paths;
11use std::ffi::{OsStr, OsString};
12use std::path::{Path, PathBuf};
13use std::{env, fs, iter};
14
15use build_helper::exit;
16
17use crate::core::build_steps::compile::{Std, run_cargo};
18use crate::core::build_steps::doc::{DocumentationFormat, prepare_doc_compiler};
19use crate::core::build_steps::gcc::{Gcc, add_cg_gcc_cargo_flags};
20use crate::core::build_steps::llvm::get_llvm_version;
21use crate::core::build_steps::run::{get_completion_paths, get_help_path};
22use crate::core::build_steps::synthetic_targets::MirOptPanicAbortSyntheticTarget;
23use crate::core::build_steps::test::compiletest::CompiletestMode;
24use crate::core::build_steps::tool::{
25    self, RustcPrivateCompilers, SourceType, TEST_FLOAT_PARSE_ALLOW_FEATURES, Tool,
26    ToolTargetBuildMode, get_tool_target_compiler,
27};
28use crate::core::build_steps::toolstate::ToolState;
29use crate::core::build_steps::{compile, dist, llvm};
30use crate::core::builder::{
31    self, Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, StepMetadata,
32    crate_description,
33};
34use crate::core::config::TargetSelection;
35use crate::core::config::flags::{Subcommand, get_completion, top_level_help};
36use crate::core::{android, debuggers};
37use crate::utils::build_stamp::{self, BuildStamp};
38use crate::utils::exec::{BootstrapCommand, command};
39use crate::utils::helpers::{
40    self, LldThreads, add_dylib_path, add_rustdoc_cargo_linker_args, dylib_path, dylib_path_var,
41    linker_args, linker_flags, t, target_supports_cranelift_backend, up_to_date,
42};
43use crate::utils::render_tests::{add_flags_and_try_run_tests, try_run_tests};
44use crate::{CLang, CodegenBackendKind, DocTests, GitRepo, Mode, PathSet, envify};
45
46mod compiletest;
47
48/// Runs `cargo test` on various internal tools used by bootstrap.
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub struct CrateBootstrap {
51    path: PathBuf,
52    host: TargetSelection,
53}
54
55impl Step for CrateBootstrap {
56    type Output = ();
57    const IS_HOST: bool = true;
58
59    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
60        // This step is responsible for several different tool paths.
61        //
62        // By default, it will test all of them, but requesting specific tools on the command-line
63        // (e.g. `./x test src/tools/coverage-dump`) will test only the specified tools.
64        run.path("src/tools/jsondoclint")
65            .path("src/tools/replace-version-placeholder")
66            .path("src/tools/coverage-dump")
67            // We want `./x test tidy` to _run_ the tidy tool, not its tests.
68            // So we need a separate alias to test the tidy tool itself.
69            .alias("tidyselftest")
70    }
71
72    fn is_default_step(_builder: &Builder<'_>) -> bool {
73        true
74    }
75
76    fn make_run(run: RunConfig<'_>) {
77        // Create and ensure a separate instance of this step for each path
78        // that was selected on the command-line (or selected by default).
79        for path in run.paths {
80            let path = path.assert_single_path().path.clone();
81            run.builder.ensure(CrateBootstrap { host: run.target, path });
82        }
83    }
84
85    fn run(self, builder: &Builder<'_>) {
86        let bootstrap_host = builder.config.host_target;
87        let compiler = builder.compiler(0, bootstrap_host);
88        let mut path = self.path.to_str().unwrap();
89
90        // Map alias `tidyselftest` back to the actual crate path of tidy.
91        if path == "tidyselftest" {
92            path = "src/tools/tidy";
93        }
94
95        let cargo = tool::prepare_tool_cargo(
96            builder,
97            compiler,
98            Mode::ToolBootstrap,
99            bootstrap_host,
100            Kind::Test,
101            path,
102            SourceType::InTree,
103            &[],
104        );
105
106        let crate_name = path.rsplit_once('/').unwrap().1;
107        run_cargo_test(cargo, &[], &[], crate_name, bootstrap_host, builder);
108    }
109
110    fn metadata(&self) -> Option<StepMetadata> {
111        Some(
112            StepMetadata::test("crate-bootstrap", self.host)
113                .with_metadata(self.path.as_path().to_string_lossy().to_string()),
114        )
115    }
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub struct Linkcheck {
120    host: TargetSelection,
121}
122
123impl Step for Linkcheck {
124    type Output = ();
125    const IS_HOST: bool = true;
126
127    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
128        run.path("src/tools/linkchecker")
129    }
130
131    fn is_default_step(builder: &Builder<'_>) -> bool {
132        builder.config.docs
133    }
134
135    fn make_run(run: RunConfig<'_>) {
136        run.builder.ensure(Linkcheck { host: run.target });
137    }
138
139    /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
140    ///
141    /// This tool in `src/tools` will verify the validity of all our links in the
142    /// documentation to ensure we don't have a bunch of dead ones.
143    fn run(self, builder: &Builder<'_>) {
144        let host = self.host;
145        let hosts = &builder.hosts;
146        let targets = &builder.targets;
147
148        // if we have different hosts and targets, some things may be built for
149        // the host (e.g. rustc) and others for the target (e.g. std). The
150        // documentation built for each will contain broken links to
151        // docs built for the other platform (e.g. rustc linking to cargo)
152        if (hosts != targets) && !hosts.is_empty() && !targets.is_empty() {
153            panic!(
154                "Linkcheck currently does not support builds with different hosts and targets.
155You can skip linkcheck with --skip src/tools/linkchecker"
156            );
157        }
158
159        builder.info(&format!("Linkcheck ({host})"));
160
161        // Test the linkchecker itself.
162        let bootstrap_host = builder.config.host_target;
163        let compiler = builder.compiler(0, bootstrap_host);
164
165        let cargo = tool::prepare_tool_cargo(
166            builder,
167            compiler,
168            Mode::ToolBootstrap,
169            bootstrap_host,
170            Kind::Test,
171            "src/tools/linkchecker",
172            SourceType::InTree,
173            &[],
174        );
175        run_cargo_test(cargo, &[], &[], "linkchecker self tests", bootstrap_host, builder);
176
177        if builder.doc_tests == DocTests::No {
178            return;
179        }
180
181        // Build all the default documentation.
182        builder.run_default_doc_steps();
183
184        // Build the linkchecker before calling `msg`, since GHA doesn't support nested groups.
185        let linkchecker = builder.tool_cmd(Tool::Linkchecker);
186
187        // Run the linkchecker.
188        let _guard = builder.msg_test("Linkcheck", bootstrap_host, 1);
189        let _time = helpers::timeit(builder);
190        linkchecker.delay_failure().arg(builder.out.join(host).join("doc")).run(builder);
191    }
192
193    fn metadata(&self) -> Option<StepMetadata> {
194        Some(StepMetadata::test("link-check", self.host))
195    }
196}
197
198fn check_if_tidy_is_installed(builder: &Builder<'_>) -> bool {
199    command("tidy")
200        .allow_failure()
201        .arg("--version")
202        // Cache the output to avoid running this command more than once (per builder).
203        .cached()
204        .run_capture_stdout(builder)
205        .is_success()
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, Hash)]
209pub struct HtmlCheck {
210    target: TargetSelection,
211}
212
213impl Step for HtmlCheck {
214    type Output = ();
215    const IS_HOST: bool = true;
216
217    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
218        run.path("src/tools/html-checker")
219    }
220
221    fn is_default_step(builder: &Builder<'_>) -> bool {
222        check_if_tidy_is_installed(builder)
223    }
224
225    fn make_run(run: RunConfig<'_>) {
226        run.builder.ensure(HtmlCheck { target: run.target });
227    }
228
229    fn run(self, builder: &Builder<'_>) {
230        if !check_if_tidy_is_installed(builder) {
231            eprintln!("not running HTML-check tool because `tidy` is missing");
232            eprintln!(
233                "You need the HTML tidy tool https://www.html-tidy.org/, this tool is *not* part of the rust project and needs to be installed separately, for example via your package manager."
234            );
235            panic!("Cannot run html-check tests");
236        }
237        // Ensure that a few different kinds of documentation are available.
238        builder.run_default_doc_steps();
239        builder.ensure(crate::core::build_steps::doc::Rustc::for_stage(
240            builder,
241            builder.top_stage,
242            self.target,
243        ));
244
245        builder
246            .tool_cmd(Tool::HtmlChecker)
247            .delay_failure()
248            .arg(builder.doc_out(self.target))
249            .run(builder);
250    }
251
252    fn metadata(&self) -> Option<StepMetadata> {
253        Some(StepMetadata::test("html-check", self.target))
254    }
255}
256
257/// Builds cargo and then runs the `src/tools/cargotest` tool, which checks out
258/// some representative crate repositories and runs `cargo test` on them, in
259/// order to test cargo.
260#[derive(Debug, Clone, PartialEq, Eq, Hash)]
261pub struct Cargotest {
262    build_compiler: Compiler,
263    host: TargetSelection,
264}
265
266impl Step for Cargotest {
267    type Output = ();
268    const IS_HOST: bool = true;
269
270    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
271        run.path("src/tools/cargotest")
272    }
273
274    fn make_run(run: RunConfig<'_>) {
275        if run.builder.top_stage == 0 {
276            eprintln!(
277                "ERROR: running cargotest with stage 0 is currently unsupported. Use at least stage 1."
278            );
279            exit!(1);
280        }
281        // We want to build cargo stage N (where N == top_stage), and rustc stage N,
282        // and test both of these together.
283        // So we need to get a build compiler stage N-1 to build the stage N components.
284        run.builder.ensure(Cargotest {
285            build_compiler: run.builder.compiler(run.builder.top_stage - 1, run.target),
286            host: run.target,
287        });
288    }
289
290    /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
291    ///
292    /// This tool in `src/tools` will check out a few Rust projects and run `cargo
293    /// test` to ensure that we don't regress the test suites there.
294    fn run(self, builder: &Builder<'_>) {
295        // cargotest's staging has several pieces:
296        // consider ./x test cargotest --stage=2.
297        //
298        // The test goal is to exercise a (stage 2 cargo, stage 2 rustc) pair through a stage 2
299        // cargotest tool.
300        // To produce the stage 2 cargo and cargotest, we need to do so with the stage 1 rustc and std.
301        // Importantly, the stage 2 rustc being tested (`tested_compiler`) via stage 2 cargotest is
302        // the rustc built by an earlier stage 1 rustc (the build_compiler). These are two different
303        // compilers!
304        let cargo =
305            builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host));
306        let tested_compiler = builder.compiler(self.build_compiler.stage + 1, self.host);
307        builder.std(tested_compiler, self.host);
308
309        // Note that this is a short, cryptic, and not scoped directory name. This
310        // is currently to minimize the length of path on Windows where we otherwise
311        // quickly run into path name limit constraints.
312        let out_dir = builder.out.join("ct");
313        t!(fs::create_dir_all(&out_dir));
314
315        let _time = helpers::timeit(builder);
316        let mut cmd = builder.tool_cmd(Tool::CargoTest);
317        cmd.arg(&cargo.tool_path)
318            .arg(&out_dir)
319            .args(builder.config.test_args())
320            .env("RUSTC", builder.rustc(tested_compiler))
321            .env("RUSTDOC", builder.rustdoc_for_compiler(tested_compiler));
322        add_rustdoc_cargo_linker_args(&mut cmd, builder, tested_compiler.host, LldThreads::No);
323        cmd.delay_failure().run(builder);
324    }
325
326    fn metadata(&self) -> Option<StepMetadata> {
327        Some(StepMetadata::test("cargotest", self.host).stage(self.build_compiler.stage + 1))
328    }
329}
330
331/// Runs `cargo test` for cargo itself.
332/// We label these tests as "cargo self-tests".
333#[derive(Debug, Clone, PartialEq, Eq, Hash)]
334pub struct Cargo {
335    build_compiler: Compiler,
336    host: TargetSelection,
337}
338
339impl Cargo {
340    const CRATE_PATH: &str = "src/tools/cargo";
341}
342
343impl Step for Cargo {
344    type Output = ();
345    const IS_HOST: bool = true;
346
347    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
348        run.path(Self::CRATE_PATH)
349    }
350
351    fn make_run(run: RunConfig<'_>) {
352        run.builder.ensure(Cargo {
353            build_compiler: get_tool_target_compiler(
354                run.builder,
355                ToolTargetBuildMode::Build(run.target),
356            ),
357            host: run.target,
358        });
359    }
360
361    /// Runs `cargo test` for `cargo` packaged with Rust.
362    fn run(self, builder: &Builder<'_>) {
363        // When we do a "stage 1 cargo self-test", it means that we test the stage 1 rustc
364        // using stage 1 cargo. So we actually build cargo using the stage 0 compiler, and then
365        // run its tests against the stage 1 compiler (called `tested_compiler` below).
366        builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host));
367
368        let tested_compiler = builder.compiler(self.build_compiler.stage + 1, self.host);
369        builder.std(tested_compiler, self.host);
370        // We also need to build rustdoc for cargo tests
371        // It will be located in the bindir of `tested_compiler`, so we don't need to explicitly
372        // pass its path to Cargo.
373        builder.rustdoc_for_compiler(tested_compiler);
374
375        let cargo = tool::prepare_tool_cargo(
376            builder,
377            self.build_compiler,
378            Mode::ToolTarget,
379            self.host,
380            Kind::Test,
381            Self::CRATE_PATH,
382            SourceType::Submodule,
383            &[],
384        );
385
386        // NOTE: can't use `run_cargo_test` because we need to overwrite `PATH`
387        let mut cargo = prepare_cargo_test(cargo, &[], &[], self.host, builder);
388
389        // Don't run cross-compile tests, we may not have cross-compiled libstd libs
390        // available.
391        cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
392        // Forcibly disable tests using nightly features since any changes to
393        // those features won't be able to land.
394        cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1");
395
396        // Configure PATH to find the right rustc. NB. we have to use PATH
397        // and not RUSTC because the Cargo test suite has tests that will
398        // fail if rustc is not spelled `rustc`.
399        cargo.env("PATH", bin_path_for_cargo(builder, tested_compiler));
400
401        // The `cargo` command configured above has dylib dir path set to the `build_compiler`'s
402        // libdir. That causes issues in cargo test, because the programs that cargo compiles are
403        // incorrectly picking that libdir, even though they should be picking the
404        // `tested_compiler`'s libdir. We thus have to override the precedence here.
405        let mut existing_dylib_paths = cargo
406            .get_envs()
407            .find(|(k, _)| *k == OsStr::new(dylib_path_var()))
408            .and_then(|(_, v)| v)
409            .map(|value| split_paths(value).collect::<Vec<PathBuf>>())
410            .unwrap_or_default();
411        existing_dylib_paths.insert(0, builder.rustc_libdir(tested_compiler));
412        add_dylib_path(existing_dylib_paths, &mut cargo);
413
414        // Cargo's test suite uses `CARGO_RUSTC_CURRENT_DIR` to determine the path that `file!` is
415        // relative to. Cargo no longer sets this env var, so we have to do that. This has to be the
416        // same value as `-Zroot-dir`.
417        cargo.env("CARGO_RUSTC_CURRENT_DIR", builder.src.display().to_string());
418
419        #[cfg(feature = "build-metrics")]
420        builder.metrics.begin_test_suite(
421            build_helper::metrics::TestSuiteMetadata::CargoPackage {
422                crates: vec!["cargo".into()],
423                target: self.host.triple.to_string(),
424                host: self.host.triple.to_string(),
425                stage: self.build_compiler.stage + 1,
426            },
427            builder,
428        );
429
430        let _time = helpers::timeit(builder);
431        add_flags_and_try_run_tests(builder, &mut cargo);
432    }
433
434    fn metadata(&self) -> Option<StepMetadata> {
435        Some(StepMetadata::test("cargo", self.host).built_by(self.build_compiler))
436    }
437}
438
439#[derive(Debug, Clone, PartialEq, Eq, Hash)]
440pub struct RustAnalyzer {
441    compilers: RustcPrivateCompilers,
442}
443
444impl Step for RustAnalyzer {
445    type Output = ();
446    const IS_HOST: bool = true;
447
448    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
449        run.path("src/tools/rust-analyzer")
450    }
451
452    fn is_default_step(_builder: &Builder<'_>) -> bool {
453        true
454    }
455
456    fn make_run(run: RunConfig<'_>) {
457        run.builder.ensure(Self {
458            compilers: RustcPrivateCompilers::new(
459                run.builder,
460                run.builder.top_stage,
461                run.builder.host_target,
462            ),
463        });
464    }
465
466    /// Runs `cargo test` for rust-analyzer
467    fn run(self, builder: &Builder<'_>) {
468        let build_compiler = self.compilers.build_compiler();
469        let target = self.compilers.target();
470
471        // NOTE: rust-analyzer repo currently (as of 2025-12-11) does not run tests against 32-bit
472        // targets, so we also don't run them in rust-lang/rust CI (because that will just mean that
473        // subtree syncs will keep getting 32-bit-specific failures that are not observed in
474        // rust-analyzer repo CI).
475        //
476        // Some 32-bit specific failures include e.g. target pointer width specific hashes.
477
478        // FIXME: eventually, we should probably reduce the amount of target tuple substring
479        // matching in bootstrap.
480        if target.starts_with("i686") {
481            return;
482        }
483
484        let mut cargo = tool::prepare_tool_cargo(
485            builder,
486            build_compiler,
487            Mode::ToolRustcPrivate,
488            target,
489            Kind::Test,
490            "src/tools/rust-analyzer",
491            SourceType::InTree,
492            &["in-rust-tree".to_owned()],
493        );
494        cargo.allow_features(tool::RustAnalyzer::ALLOW_FEATURES);
495
496        // N.B. it turns out _setting_ `CARGO_WORKSPACE_DIR` actually somehow breaks `expect-test`,
497        // even though previously we actually needed to set that hack to allow `expect-test` to
498        // correctly discover the r-a workspace instead of the outer r-l/r workspace.
499
500        // FIXME: RA's test suite tries to write to the source directory, that can't work in Rust CI
501        // without properly wiring up the writable test dir.
502        cargo.env("SKIP_SLOW_TESTS", "1");
503
504        // NOTE: we need to skip `src/tools/rust-analyzer/xtask` as they seem to exercise rustup /
505        // stable rustfmt.
506        //
507        // NOTE: you can only skip a specific workspace package via `--exclude=...` if you *also*
508        // specify `--workspace`.
509        cargo.arg("--workspace");
510        cargo.arg("--exclude=xtask");
511
512        let mut skip_tests = vec![];
513
514        // NOTE: the following test skips is a bit cheeky in that it assumes there are no
515        // identically named tests across different r-a packages, where we want to run the
516        // identically named test in one package but not another. If we want to support that use
517        // case, we'd have to run the r-a tests in two batches (with one excluding the package that
518        // we *don't* want to run the test for, and the other batch including).
519
520        // Across all platforms.
521        skip_tests.extend_from_slice(&[
522            // FIXME: this test wants to find a `rustc`. We need to provide it with a path to staged
523            // in-tree `rustc`, but setting `RUSTC` env var requires some reworking of bootstrap.
524            "tests::smoke_test_real_sysroot_cargo",
525            // NOTE: part of `smol-str` test suite; this tries to access a stable rustfmt from the
526            // environment, which is not something we want to do.
527            "check_code_formatting",
528        ]);
529
530        let skip_tests = skip_tests.iter().map(|name| format!("--skip={name}")).collect::<Vec<_>>();
531        let skip_tests = skip_tests.iter().map(|s| s.as_str()).collect::<Vec<_>>();
532
533        cargo.add_rustc_lib_path(builder);
534        run_cargo_test(cargo, skip_tests.as_slice(), &[], "rust-analyzer", target, builder);
535    }
536
537    fn metadata(&self) -> Option<StepMetadata> {
538        Some(
539            StepMetadata::test("rust-analyzer", self.compilers.target())
540                .built_by(self.compilers.build_compiler()),
541        )
542    }
543}
544
545/// Runs `cargo test` for rustfmt.
546#[derive(Debug, Clone, PartialEq, Eq, Hash)]
547pub struct Rustfmt {
548    compilers: RustcPrivateCompilers,
549}
550
551impl Step for Rustfmt {
552    type Output = ();
553    const IS_HOST: bool = true;
554
555    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
556        run.path("src/tools/rustfmt")
557    }
558
559    fn make_run(run: RunConfig<'_>) {
560        run.builder.ensure(Rustfmt {
561            compilers: RustcPrivateCompilers::new(
562                run.builder,
563                run.builder.top_stage,
564                run.builder.host_target,
565            ),
566        });
567    }
568
569    /// Runs `cargo test` for rustfmt.
570    fn run(self, builder: &Builder<'_>) {
571        let build_compiler = self.compilers.build_compiler();
572        let target = self.compilers.target();
573
574        let mut cargo = tool::prepare_tool_cargo(
575            builder,
576            build_compiler,
577            Mode::ToolRustcPrivate,
578            target,
579            Kind::Test,
580            "src/tools/rustfmt",
581            SourceType::InTree,
582            &[],
583        );
584
585        let dir = testdir(builder, target);
586        t!(fs::create_dir_all(&dir));
587        cargo.env("RUSTFMT_TEST_DIR", dir);
588
589        cargo.add_rustc_lib_path(builder);
590
591        run_cargo_test(cargo, &[], &[], "rustfmt", target, builder);
592    }
593
594    fn metadata(&self) -> Option<StepMetadata> {
595        Some(
596            StepMetadata::test("rustfmt", self.compilers.target())
597                .built_by(self.compilers.build_compiler()),
598        )
599    }
600}
601
602#[derive(Debug, Clone, PartialEq, Eq, Hash)]
603pub struct Miri {
604    target: TargetSelection,
605}
606
607impl Miri {
608    /// Run `cargo miri setup` for the given target, return where the Miri sysroot was put.
609    pub fn build_miri_sysroot(
610        builder: &Builder<'_>,
611        compiler: Compiler,
612        target: TargetSelection,
613    ) -> PathBuf {
614        let miri_sysroot = builder.out.join(compiler.host).join("miri-sysroot");
615        let mut cargo = builder::Cargo::new(
616            builder,
617            compiler,
618            Mode::Std,
619            SourceType::Submodule,
620            target,
621            Kind::MiriSetup,
622        );
623
624        // Tell `cargo miri setup` where to find the sources.
625        cargo.env("MIRI_LIB_SRC", builder.src.join("library"));
626        // Tell it where to put the sysroot.
627        cargo.env("MIRI_SYSROOT", &miri_sysroot);
628
629        let mut cargo = BootstrapCommand::from(cargo);
630        let _guard =
631            builder.msg(Kind::Build, "miri sysroot", Mode::ToolRustcPrivate, compiler, target);
632        cargo.run(builder);
633
634        // # Determine where Miri put its sysroot.
635        // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
636        // (We do this separately from the above so that when the setup actually
637        // happens we get some output.)
638        // We re-use the `cargo` from above.
639        cargo.arg("--print-sysroot");
640
641        builder.do_if_verbose(|| println!("running: {cargo:?}"));
642        let stdout = cargo.run_capture_stdout(builder).stdout();
643        // Output is "<sysroot>\n".
644        let sysroot = stdout.trim_end();
645        builder.do_if_verbose(|| println!("`cargo miri setup --print-sysroot` said: {sysroot:?}"));
646        PathBuf::from(sysroot)
647    }
648}
649
650impl Step for Miri {
651    type Output = ();
652
653    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
654        run.path("src/tools/miri")
655    }
656
657    fn make_run(run: RunConfig<'_>) {
658        run.builder.ensure(Miri { target: run.target });
659    }
660
661    /// Runs `cargo test` for miri.
662    fn run(self, builder: &Builder<'_>) {
663        let host = builder.build.host_target;
664        let target = self.target;
665        let stage = builder.top_stage;
666        if stage == 0 {
667            eprintln!("miri cannot be tested at stage 0");
668            std::process::exit(1);
669        }
670
671        // This compiler runs on the host, we'll just use it for the target.
672        let compilers = RustcPrivateCompilers::new(builder, stage, host);
673
674        // Build our tools.
675        let miri = builder.ensure(tool::Miri::from_compilers(compilers));
676        // the ui tests also assume cargo-miri has been built
677        builder.ensure(tool::CargoMiri::from_compilers(compilers));
678
679        let target_compiler = compilers.target_compiler();
680
681        // We also need sysroots, for Miri and for the host (the latter for build scripts).
682        // This is for the tests so everything is done with the target compiler.
683        let miri_sysroot = Miri::build_miri_sysroot(builder, target_compiler, target);
684        builder.std(target_compiler, host);
685        let host_sysroot = builder.sysroot(target_compiler);
686
687        // Miri has its own "target dir" for ui test dependencies. Make sure it gets cleared when
688        // the sysroot gets rebuilt, to avoid "found possibly newer version of crate `std`" errors.
689        if !builder.config.dry_run() {
690            // This has to match `CARGO_TARGET_TMPDIR` in Miri's `ui.rs`.
691            // This means we need `host` here as that's the target `ui.rs` is built for.
692            let ui_test_dep_dir = builder
693                .stage_out(miri.build_compiler, Mode::ToolStd)
694                .join(host)
695                .join("tmp")
696                .join("miri_ui");
697            // The mtime of `miri_sysroot` changes when the sysroot gets rebuilt (also see
698            // <https://github.com/RalfJung/rustc-build-sysroot/commit/10ebcf60b80fe2c3dc765af0ff19fdc0da4b7466>).
699            // We can hence use that directly as a signal to clear the ui test dir.
700            build_stamp::clear_if_dirty(builder, &ui_test_dep_dir, &miri_sysroot);
701        }
702
703        // Run `cargo test`.
704        // This is with the Miri crate, so it uses the host compiler.
705        let mut cargo = tool::prepare_tool_cargo(
706            builder,
707            miri.build_compiler,
708            Mode::ToolRustcPrivate,
709            host,
710            Kind::Test,
711            "src/tools/miri",
712            SourceType::InTree,
713            &[],
714        );
715
716        cargo.add_rustc_lib_path(builder);
717
718        // We can NOT use `run_cargo_test` since Miri's integration tests do not use the usual test
719        // harness and therefore do not understand the flags added by `add_flags_and_try_run_test`.
720        let mut cargo = prepare_cargo_test(cargo, &[], &[], host, builder);
721
722        // miri tests need to know about the stage sysroot
723        cargo.env("MIRI_SYSROOT", &miri_sysroot);
724        cargo.env("MIRI_HOST_SYSROOT", &host_sysroot);
725        cargo.env("MIRI", &miri.tool_path);
726
727        // Set the target.
728        cargo.env("MIRI_TEST_TARGET", target.rustc_target_arg());
729
730        {
731            let _guard = builder.msg_test("miri", target, target_compiler.stage);
732            let _time = helpers::timeit(builder);
733            cargo.run(builder);
734        }
735
736        // Run it again for mir-opt-level 4 to catch some miscompilations.
737        if builder.config.test_args().is_empty() {
738            cargo.env("MIRIFLAGS", "-O -Zmir-opt-level=4 -Cdebug-assertions=yes");
739            // Optimizations can change backtraces
740            cargo.env("MIRI_SKIP_UI_CHECKS", "1");
741            // `MIRI_SKIP_UI_CHECKS` and `RUSTC_BLESS` are incompatible
742            cargo.env_remove("RUSTC_BLESS");
743            // Optimizations can change error locations and remove UB so don't run `fail` tests.
744            cargo.args(["tests/pass", "tests/panic"]);
745
746            {
747                let _guard =
748                    builder.msg_test("miri (mir-opt-level 4)", target, target_compiler.stage);
749                let _time = helpers::timeit(builder);
750                cargo.run(builder);
751            }
752        }
753    }
754}
755
756/// Runs `cargo miri test` to demonstrate that `src/tools/miri/cargo-miri`
757/// works and that libtest works under miri.
758#[derive(Debug, Clone, PartialEq, Eq, Hash)]
759pub struct CargoMiri {
760    target: TargetSelection,
761}
762
763impl Step for CargoMiri {
764    type Output = ();
765
766    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
767        run.path("src/tools/miri/cargo-miri")
768    }
769
770    fn make_run(run: RunConfig<'_>) {
771        run.builder.ensure(CargoMiri { target: run.target });
772    }
773
774    /// Tests `cargo miri test`.
775    fn run(self, builder: &Builder<'_>) {
776        let host = builder.build.host_target;
777        let target = self.target;
778        let stage = builder.top_stage;
779        if stage == 0 {
780            eprintln!("cargo-miri cannot be tested at stage 0");
781            std::process::exit(1);
782        }
783
784        // This compiler runs on the host, we'll just use it for the target.
785        let build_compiler = builder.compiler(stage, host);
786
787        // Run `cargo miri test`.
788        // This is just a smoke test (Miri's own CI invokes this in a bunch of different ways and ensures
789        // that we get the desired output), but that is sufficient to make sure that the libtest harness
790        // itself executes properly under Miri, and that all the logic in `cargo-miri` does not explode.
791        let mut cargo = tool::prepare_tool_cargo(
792            builder,
793            build_compiler,
794            Mode::ToolStd, // it's unclear what to use here, we're not building anything just doing a smoke test!
795            target,
796            Kind::MiriTest,
797            "src/tools/miri/test-cargo-miri",
798            SourceType::Submodule,
799            &[],
800        );
801
802        // We're not using `prepare_cargo_test` so we have to do this ourselves.
803        // (We're not using that as the test-cargo-miri crate is not known to bootstrap.)
804        match builder.doc_tests {
805            DocTests::Yes => {}
806            DocTests::No => {
807                cargo.args(["--lib", "--bins", "--examples", "--tests", "--benches"]);
808            }
809            DocTests::Only => {
810                cargo.arg("--doc");
811            }
812        }
813        cargo.arg("--").args(builder.config.test_args());
814
815        // Finally, run everything.
816        let mut cargo = BootstrapCommand::from(cargo);
817        {
818            let _guard = builder.msg_test("cargo-miri", target, stage);
819            let _time = helpers::timeit(builder);
820            cargo.run(builder);
821        }
822    }
823}
824
825#[derive(Debug, Clone, PartialEq, Eq, Hash)]
826pub struct CompiletestTest {
827    host: TargetSelection,
828}
829
830impl Step for CompiletestTest {
831    type Output = ();
832
833    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
834        run.path("src/tools/compiletest")
835    }
836
837    fn make_run(run: RunConfig<'_>) {
838        run.builder.ensure(CompiletestTest { host: run.target });
839    }
840
841    /// Runs `cargo test` for compiletest.
842    fn run(self, builder: &Builder<'_>) {
843        let host = self.host;
844
845        // Now that compiletest uses only stable Rust, building it always uses
846        // the stage 0 compiler. However, some of its unit tests need to be able
847        // to query information from an in-tree compiler, so we treat `--stage`
848        // as selecting the stage of that secondary compiler.
849
850        if builder.top_stage == 0 && !builder.config.compiletest_allow_stage0 {
851            eprintln!("\
852ERROR: `--stage 0` causes compiletest to query information from the stage0 (precompiled) compiler, instead of the in-tree compiler, which can cause some tests to fail inappropriately
853NOTE: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `--set build.compiletest-allow-stage0=true`."
854            );
855            crate::exit!(1);
856        }
857
858        let bootstrap_compiler = builder.compiler(0, host);
859        let staged_compiler = builder.compiler(builder.top_stage, host);
860
861        let mut cargo = tool::prepare_tool_cargo(
862            builder,
863            bootstrap_compiler,
864            Mode::ToolBootstrap,
865            host,
866            Kind::Test,
867            "src/tools/compiletest",
868            SourceType::InTree,
869            &[],
870        );
871
872        // Used for `compiletest` self-tests to have the path to the *staged* compiler. Getting this
873        // right is important, as `compiletest` is intended to only support one target spec JSON
874        // format, namely that of the staged compiler.
875        cargo.env("TEST_RUSTC", builder.rustc(staged_compiler));
876
877        run_cargo_test(cargo, &[], &[], "compiletest self test", host, builder);
878    }
879}
880
881#[derive(Debug, Clone, PartialEq, Eq, Hash)]
882pub struct Clippy {
883    compilers: RustcPrivateCompilers,
884}
885
886impl Step for Clippy {
887    type Output = ();
888    const IS_HOST: bool = true;
889
890    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
891        run.suite_path("src/tools/clippy/tests").path("src/tools/clippy")
892    }
893
894    fn is_default_step(_builder: &Builder<'_>) -> bool {
895        false
896    }
897
898    fn make_run(run: RunConfig<'_>) {
899        run.builder.ensure(Clippy {
900            compilers: RustcPrivateCompilers::new(
901                run.builder,
902                run.builder.top_stage,
903                run.builder.host_target,
904            ),
905        });
906    }
907
908    /// Runs `cargo test` for clippy.
909    fn run(self, builder: &Builder<'_>) {
910        let target = self.compilers.target();
911
912        // We need to carefully distinguish the compiler that builds clippy, and the compiler
913        // that is linked into the clippy being tested. `target_compiler` is the latter,
914        // and it must also be used by clippy's test runner to build tests and their dependencies.
915        let target_compiler = self.compilers.target_compiler();
916        let build_compiler = self.compilers.build_compiler();
917
918        let mut cargo = tool::prepare_tool_cargo(
919            builder,
920            build_compiler,
921            Mode::ToolRustcPrivate,
922            target,
923            Kind::Test,
924            "src/tools/clippy",
925            SourceType::InTree,
926            &[],
927        );
928
929        cargo.env("RUSTC_TEST_SUITE", builder.rustc(build_compiler));
930        cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(build_compiler));
931        let host_libs =
932            builder.stage_out(build_compiler, Mode::ToolRustcPrivate).join(builder.cargo_dir());
933        cargo.env("HOST_LIBS", host_libs);
934
935        // Build the standard library that the tests can use.
936        builder.std(target_compiler, target);
937        cargo.env("TEST_SYSROOT", builder.sysroot(target_compiler));
938        cargo.env("TEST_RUSTC", builder.rustc(target_compiler));
939        cargo.env("TEST_RUSTC_LIB", builder.rustc_libdir(target_compiler));
940
941        // Collect paths of tests to run
942        'partially_test: {
943            let paths = &builder.config.paths[..];
944            let mut test_names = Vec::new();
945            for path in paths {
946                if let Some(path) =
947                    helpers::is_valid_test_suite_arg(path, "src/tools/clippy/tests", builder)
948                {
949                    test_names.push(path);
950                } else if path.ends_with("src/tools/clippy") {
951                    // When src/tools/clippy is called directly, all tests should be run.
952                    break 'partially_test;
953                }
954            }
955            cargo.env("TESTNAME", test_names.join(","));
956        }
957
958        cargo.add_rustc_lib_path(builder);
959        let cargo = prepare_cargo_test(cargo, &[], &[], target, builder);
960
961        let _guard = builder.msg_test("clippy", target, target_compiler.stage);
962
963        // Clippy reports errors if it blessed the outputs
964        if cargo.allow_failure().run(builder) {
965            // The tests succeeded; nothing to do.
966            return;
967        }
968
969        if !builder.config.cmd.bless() {
970            crate::exit!(1);
971        }
972    }
973
974    fn metadata(&self) -> Option<StepMetadata> {
975        Some(
976            StepMetadata::test("clippy", self.compilers.target())
977                .built_by(self.compilers.build_compiler()),
978        )
979    }
980}
981
982fn bin_path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString {
983    let path = builder.sysroot(compiler).join("bin");
984    let old_path = env::var_os("PATH").unwrap_or_default();
985    env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
986}
987
988/// Run the rustdoc-themes tool to test a given compiler.
989#[derive(Debug, Clone, Hash, PartialEq, Eq)]
990pub struct RustdocTheme {
991    /// The compiler (more accurately, its rustdoc) that we test.
992    test_compiler: Compiler,
993}
994
995impl Step for RustdocTheme {
996    type Output = ();
997    const IS_HOST: bool = true;
998
999    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1000        run.path("src/tools/rustdoc-themes")
1001    }
1002
1003    fn is_default_step(_builder: &Builder<'_>) -> bool {
1004        true
1005    }
1006
1007    fn make_run(run: RunConfig<'_>) {
1008        let test_compiler = run.builder.compiler(run.builder.top_stage, run.target);
1009
1010        run.builder.ensure(RustdocTheme { test_compiler });
1011    }
1012
1013    fn run(self, builder: &Builder<'_>) {
1014        let rustdoc = builder.bootstrap_out.join("rustdoc");
1015        let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
1016        cmd.arg(rustdoc.to_str().unwrap())
1017            .arg(builder.src.join("src/librustdoc/html/static/css/rustdoc.css").to_str().unwrap())
1018            .env("RUSTC_STAGE", self.test_compiler.stage.to_string())
1019            .env("RUSTC_SYSROOT", builder.sysroot(self.test_compiler))
1020            .env(
1021                "RUSTDOC_LIBDIR",
1022                builder.sysroot_target_libdir(self.test_compiler, self.test_compiler.host),
1023            )
1024            .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1025            .env("RUSTDOC_REAL", builder.rustdoc_for_compiler(self.test_compiler))
1026            .env("RUSTC_BOOTSTRAP", "1");
1027        cmd.args(linker_args(builder, self.test_compiler.host, LldThreads::No));
1028
1029        cmd.delay_failure().run(builder);
1030    }
1031
1032    fn metadata(&self) -> Option<StepMetadata> {
1033        Some(
1034            StepMetadata::test("rustdoc-theme", self.test_compiler.host)
1035                .stage(self.test_compiler.stage),
1036        )
1037    }
1038}
1039
1040/// Test rustdoc JS for the standard library.
1041#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1042pub struct RustdocJSStd {
1043    /// Compiler that will build the standary library.
1044    build_compiler: Compiler,
1045    target: TargetSelection,
1046}
1047
1048impl Step for RustdocJSStd {
1049    type Output = ();
1050    const IS_HOST: bool = true;
1051
1052    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1053        run.suite_path("tests/rustdoc-js-std")
1054    }
1055
1056    fn is_default_step(builder: &Builder<'_>) -> bool {
1057        builder.config.nodejs.is_some()
1058    }
1059
1060    fn make_run(run: RunConfig<'_>) {
1061        run.builder.ensure(RustdocJSStd {
1062            build_compiler: run.builder.compiler(run.builder.top_stage, run.builder.host_target),
1063            target: run.target,
1064        });
1065    }
1066
1067    fn run(self, builder: &Builder<'_>) {
1068        let nodejs =
1069            builder.config.nodejs.as_ref().expect("need nodejs to run rustdoc-js-std tests");
1070        let mut command = command(nodejs);
1071        command
1072            .arg(builder.src.join("src/tools/rustdoc-js/tester.js"))
1073            .arg("--crate-name")
1074            .arg("std")
1075            .arg("--resource-suffix")
1076            .arg(&builder.version)
1077            .arg("--doc-folder")
1078            .arg(builder.doc_out(self.target))
1079            .arg("--test-folder")
1080            .arg(builder.src.join("tests/rustdoc-js-std"));
1081        for path in &builder.paths {
1082            if let Some(p) = helpers::is_valid_test_suite_arg(path, "tests/rustdoc-js-std", builder)
1083            {
1084                if !p.ends_with(".js") {
1085                    eprintln!("A non-js file was given: `{}`", path.display());
1086                    panic!("Cannot run rustdoc-js-std tests");
1087                }
1088                command.arg("--test-file").arg(path);
1089            }
1090        }
1091        builder.ensure(crate::core::build_steps::doc::Std::from_build_compiler(
1092            self.build_compiler,
1093            self.target,
1094            DocumentationFormat::Html,
1095        ));
1096        let _guard = builder.msg_test("rustdoc-js-std", self.target, self.build_compiler.stage);
1097        command.run(builder);
1098    }
1099
1100    fn metadata(&self) -> Option<StepMetadata> {
1101        Some(StepMetadata::test("rustdoc-js-std", self.target).stage(self.build_compiler.stage))
1102    }
1103}
1104
1105#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1106pub struct RustdocJSNotStd {
1107    pub target: TargetSelection,
1108    pub compiler: Compiler,
1109}
1110
1111impl Step for RustdocJSNotStd {
1112    type Output = ();
1113    const IS_HOST: bool = true;
1114
1115    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1116        run.suite_path("tests/rustdoc-js")
1117    }
1118
1119    fn is_default_step(builder: &Builder<'_>) -> bool {
1120        builder.config.nodejs.is_some()
1121    }
1122
1123    fn make_run(run: RunConfig<'_>) {
1124        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1125        run.builder.ensure(RustdocJSNotStd { target: run.target, compiler });
1126    }
1127
1128    fn run(self, builder: &Builder<'_>) {
1129        builder.ensure(Compiletest {
1130            test_compiler: self.compiler,
1131            target: self.target,
1132            mode: CompiletestMode::RustdocJs,
1133            suite: "rustdoc-js",
1134            path: "tests/rustdoc-js",
1135            compare_mode: None,
1136        });
1137    }
1138}
1139
1140fn get_browser_ui_test_version_inner(
1141    builder: &Builder<'_>,
1142    yarn: &Path,
1143    global: bool,
1144) -> Option<String> {
1145    let mut command = command(yarn);
1146    command
1147        .arg("--cwd")
1148        .arg(&builder.build.out)
1149        .arg("list")
1150        .arg("--parseable")
1151        .arg("--long")
1152        .arg("--depth=0");
1153    if global {
1154        command.arg("--global");
1155    }
1156    // Cache the command output so that `test::RustdocGUI` only performs these
1157    // command-line probes once.
1158    let lines = command.allow_failure().cached().run_capture(builder).stdout();
1159    lines
1160        .lines()
1161        .find_map(|l| l.split(':').nth(1)?.strip_prefix("browser-ui-test@"))
1162        .map(|v| v.to_owned())
1163}
1164
1165fn get_browser_ui_test_version(builder: &Builder<'_>) -> Option<String> {
1166    let yarn = builder.config.yarn.as_deref()?;
1167    get_browser_ui_test_version_inner(builder, yarn, false)
1168        .or_else(|| get_browser_ui_test_version_inner(builder, yarn, true))
1169}
1170
1171/// Run GUI tests on a given rustdoc.
1172#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1173pub struct RustdocGUI {
1174    /// The compiler whose rustdoc we are testing.
1175    test_compiler: Compiler,
1176    target: TargetSelection,
1177}
1178
1179impl Step for RustdocGUI {
1180    type Output = ();
1181    const IS_HOST: bool = true;
1182
1183    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1184        run.suite_path("tests/rustdoc-gui")
1185    }
1186
1187    fn is_default_step(builder: &Builder<'_>) -> bool {
1188        builder.config.nodejs.is_some()
1189            && builder.doc_tests != DocTests::Only
1190            && get_browser_ui_test_version(builder).is_some()
1191    }
1192
1193    fn make_run(run: RunConfig<'_>) {
1194        let test_compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1195        run.builder.ensure(RustdocGUI { test_compiler, target: run.target });
1196    }
1197
1198    fn run(self, builder: &Builder<'_>) {
1199        builder.std(self.test_compiler, self.target);
1200
1201        let mut cmd = builder.tool_cmd(Tool::RustdocGUITest);
1202
1203        let out_dir = builder.test_out(self.target).join("rustdoc-gui");
1204        build_stamp::clear_if_dirty(
1205            builder,
1206            &out_dir,
1207            &builder.rustdoc_for_compiler(self.test_compiler),
1208        );
1209
1210        if let Some(src) = builder.config.src.to_str() {
1211            cmd.arg("--rust-src").arg(src);
1212        }
1213
1214        if let Some(out_dir) = out_dir.to_str() {
1215            cmd.arg("--out-dir").arg(out_dir);
1216        }
1217
1218        if let Some(initial_cargo) = builder.config.initial_cargo.to_str() {
1219            cmd.arg("--initial-cargo").arg(initial_cargo);
1220        }
1221
1222        cmd.arg("--jobs").arg(builder.jobs().to_string());
1223
1224        cmd.env("RUSTDOC", builder.rustdoc_for_compiler(self.test_compiler))
1225            .env("RUSTC", builder.rustc(self.test_compiler));
1226
1227        add_rustdoc_cargo_linker_args(&mut cmd, builder, self.test_compiler.host, LldThreads::No);
1228
1229        for path in &builder.paths {
1230            if let Some(p) = helpers::is_valid_test_suite_arg(path, "tests/rustdoc-gui", builder) {
1231                if !p.ends_with(".goml") {
1232                    eprintln!("A non-goml file was given: `{}`", path.display());
1233                    panic!("Cannot run rustdoc-gui tests");
1234                }
1235                if let Some(name) = path.file_name().and_then(|f| f.to_str()) {
1236                    cmd.arg("--goml-file").arg(name);
1237                }
1238            }
1239        }
1240
1241        for test_arg in builder.config.test_args() {
1242            cmd.arg("--test-arg").arg(test_arg);
1243        }
1244
1245        if let Some(ref nodejs) = builder.config.nodejs {
1246            cmd.arg("--nodejs").arg(nodejs);
1247        }
1248
1249        if let Some(ref yarn) = builder.config.yarn {
1250            cmd.arg("--yarn").arg(yarn);
1251        }
1252
1253        let _time = helpers::timeit(builder);
1254        let _guard = builder.msg_test("rustdoc-gui", self.target, self.test_compiler.stage);
1255        try_run_tests(builder, &mut cmd, true);
1256    }
1257
1258    fn metadata(&self) -> Option<StepMetadata> {
1259        Some(StepMetadata::test("rustdoc-gui", self.target).stage(self.test_compiler.stage))
1260    }
1261}
1262
1263/// Runs `src/tools/tidy` and `cargo fmt --check` to detect various style
1264/// problems in the repository.
1265///
1266/// (To run the tidy tool's internal tests, use the alias "tidyselftest" instead.)
1267#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1268pub struct Tidy;
1269
1270impl Step for Tidy {
1271    type Output = ();
1272    const IS_HOST: bool = true;
1273
1274    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1275        run.path("src/tools/tidy")
1276    }
1277
1278    fn is_default_step(builder: &Builder<'_>) -> bool {
1279        builder.doc_tests != DocTests::Only
1280    }
1281
1282    fn make_run(run: RunConfig<'_>) {
1283        run.builder.ensure(Tidy);
1284    }
1285
1286    /// Runs the `tidy` tool.
1287    ///
1288    /// This tool in `src/tools` checks up on various bits and pieces of style and
1289    /// otherwise just implements a few lint-like checks that are specific to the
1290    /// compiler itself.
1291    ///
1292    /// Once tidy passes, this step also runs `fmt --check` if tests are being run
1293    /// for the `dev` or `nightly` channels.
1294    fn run(self, builder: &Builder<'_>) {
1295        let mut cmd = builder.tool_cmd(Tool::Tidy);
1296        cmd.arg(&builder.src);
1297        cmd.arg(&builder.initial_cargo);
1298        cmd.arg(&builder.out);
1299        // Tidy is heavily IO constrained. Still respect `-j`, but use a higher limit if `jobs` hasn't been configured.
1300        let jobs = builder.config.jobs.unwrap_or_else(|| {
1301            8 * std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1302        });
1303        cmd.arg(jobs.to_string());
1304        // pass the path to the yarn command used for installing js deps.
1305        if let Some(yarn) = &builder.config.yarn {
1306            cmd.arg(yarn);
1307        } else {
1308            cmd.arg("yarn");
1309        }
1310        if builder.is_verbose() {
1311            cmd.arg("--verbose");
1312        }
1313        if builder.config.cmd.bless() {
1314            cmd.arg("--bless");
1315        }
1316        if let Some(s) =
1317            builder.config.cmd.extra_checks().or(builder.config.tidy_extra_checks.as_deref())
1318        {
1319            cmd.arg(format!("--extra-checks={s}"));
1320        }
1321        let mut args = std::env::args_os();
1322        if args.any(|arg| arg == OsStr::new("--")) {
1323            cmd.arg("--");
1324            cmd.args(args);
1325        }
1326
1327        if builder.config.channel == "dev" || builder.config.channel == "nightly" {
1328            if !builder.config.json_output {
1329                builder.info("fmt check");
1330                if builder.config.initial_rustfmt.is_none() {
1331                    let inferred_rustfmt_dir = builder.initial_sysroot.join("bin");
1332                    eprintln!(
1333                        "\
1334ERROR: no `rustfmt` binary found in {PATH}
1335INFO: `rust.channel` is currently set to \"{CHAN}\"
1336HELP: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `bootstrap.toml` file
1337HELP: to skip test's attempt to check tidiness, pass `--skip src/tools/tidy` to `x.py test`",
1338                        PATH = inferred_rustfmt_dir.display(),
1339                        CHAN = builder.config.channel,
1340                    );
1341                    crate::exit!(1);
1342                }
1343                let all = false;
1344                crate::core::build_steps::format::format(
1345                    builder,
1346                    !builder.config.cmd.bless(),
1347                    all,
1348                    &[],
1349                );
1350            } else {
1351                eprintln!(
1352                    "WARNING: `--json-output` is not supported on rustfmt, formatting will be skipped"
1353                );
1354            }
1355        }
1356
1357        builder.info("tidy check");
1358        cmd.delay_failure().run(builder);
1359
1360        builder.info("x.py completions check");
1361        let completion_paths = get_completion_paths(builder);
1362        if builder.config.cmd.bless() {
1363            builder.ensure(crate::core::build_steps::run::GenerateCompletions);
1364        } else if completion_paths
1365            .into_iter()
1366            .any(|(shell, path)| get_completion(shell, &path).is_some())
1367        {
1368            eprintln!(
1369                "x.py completions were changed; run `x.py run generate-completions` to update them"
1370            );
1371            crate::exit!(1);
1372        }
1373
1374        builder.info("x.py help check");
1375        if builder.config.cmd.bless() {
1376            builder.ensure(crate::core::build_steps::run::GenerateHelp);
1377        } else {
1378            let help_path = get_help_path(builder);
1379            let cur_help = std::fs::read_to_string(&help_path).unwrap_or_else(|err| {
1380                eprintln!("couldn't read {}: {}", help_path.display(), err);
1381                crate::exit!(1);
1382            });
1383            let new_help = top_level_help();
1384
1385            if new_help != cur_help {
1386                eprintln!("x.py help was changed; run `x.py run generate-help` to update it");
1387                crate::exit!(1);
1388            }
1389        }
1390    }
1391
1392    fn metadata(&self) -> Option<StepMetadata> {
1393        Some(StepMetadata::test("tidy", TargetSelection::default()))
1394    }
1395}
1396
1397/// Runs `cargo test` on the `src/tools/run-make-support` crate.
1398/// That crate is used by run-make tests.
1399#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1400pub struct CrateRunMakeSupport {
1401    host: TargetSelection,
1402}
1403
1404impl Step for CrateRunMakeSupport {
1405    type Output = ();
1406    const IS_HOST: bool = true;
1407
1408    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1409        run.path("src/tools/run-make-support")
1410    }
1411
1412    fn make_run(run: RunConfig<'_>) {
1413        run.builder.ensure(CrateRunMakeSupport { host: run.target });
1414    }
1415
1416    /// Runs `cargo test` for run-make-support.
1417    fn run(self, builder: &Builder<'_>) {
1418        let host = self.host;
1419        let compiler = builder.compiler(0, host);
1420
1421        let mut cargo = tool::prepare_tool_cargo(
1422            builder,
1423            compiler,
1424            Mode::ToolBootstrap,
1425            host,
1426            Kind::Test,
1427            "src/tools/run-make-support",
1428            SourceType::InTree,
1429            &[],
1430        );
1431        cargo.allow_features("test");
1432        run_cargo_test(cargo, &[], &[], "run-make-support self test", host, builder);
1433    }
1434}
1435
1436#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1437pub struct CrateBuildHelper {
1438    host: TargetSelection,
1439}
1440
1441impl Step for CrateBuildHelper {
1442    type Output = ();
1443    const IS_HOST: bool = true;
1444
1445    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1446        run.path("src/build_helper")
1447    }
1448
1449    fn make_run(run: RunConfig<'_>) {
1450        run.builder.ensure(CrateBuildHelper { host: run.target });
1451    }
1452
1453    /// Runs `cargo test` for build_helper.
1454    fn run(self, builder: &Builder<'_>) {
1455        let host = self.host;
1456        let compiler = builder.compiler(0, host);
1457
1458        let mut cargo = tool::prepare_tool_cargo(
1459            builder,
1460            compiler,
1461            Mode::ToolBootstrap,
1462            host,
1463            Kind::Test,
1464            "src/build_helper",
1465            SourceType::InTree,
1466            &[],
1467        );
1468        cargo.allow_features("test");
1469        run_cargo_test(cargo, &[], &[], "build_helper self test", host, builder);
1470    }
1471}
1472
1473fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
1474    builder.out.join(host).join("test")
1475}
1476
1477/// Declares a test step that invokes compiletest on a particular test suite.
1478macro_rules! test {
1479    (
1480        $( #[$attr:meta] )* // allow docstrings and attributes
1481        $name:ident {
1482            path: $path:expr,
1483            mode: $mode:expr,
1484            suite: $suite:expr,
1485            default: $default:expr
1486            $( , IS_HOST: $IS_HOST:expr )? // default: false
1487            $( , compare_mode: $compare_mode:expr )? // default: None
1488            $( , )? // optional trailing comma
1489        }
1490    ) => {
1491        $( #[$attr] )*
1492        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1493        pub struct $name {
1494            test_compiler: Compiler,
1495            target: TargetSelection,
1496        }
1497
1498        impl Step for $name {
1499            type Output = ();
1500            const IS_HOST: bool = (const {
1501                #[allow(unused_assignments, unused_mut)]
1502                let mut value = false;
1503                $( value = $IS_HOST; )?
1504                value
1505            });
1506
1507            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1508                run.suite_path($path)
1509            }
1510
1511            fn is_default_step(_builder: &Builder<'_>) -> bool {
1512                const { $default }
1513            }
1514
1515            fn make_run(run: RunConfig<'_>) {
1516                let test_compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1517
1518                run.builder.ensure($name { test_compiler, target: run.target });
1519            }
1520
1521            fn run(self, builder: &Builder<'_>) {
1522                builder.ensure(Compiletest {
1523                    test_compiler: self.test_compiler,
1524                    target: self.target,
1525                    mode: const { $mode },
1526                    suite: $suite,
1527                    path: $path,
1528                    compare_mode: (const {
1529                        #[allow(unused_assignments, unused_mut)]
1530                        let mut value = None;
1531                        $( value = $compare_mode; )?
1532                        value
1533                    }),
1534                })
1535            }
1536        }
1537    };
1538}
1539
1540test!(Ui { path: "tests/ui", mode: CompiletestMode::Ui, suite: "ui", default: true });
1541
1542test!(Crashes {
1543    path: "tests/crashes",
1544    mode: CompiletestMode::Crashes,
1545    suite: "crashes",
1546    default: true,
1547});
1548
1549test!(CodegenLlvm {
1550    path: "tests/codegen-llvm",
1551    mode: CompiletestMode::Codegen,
1552    suite: "codegen-llvm",
1553    default: true
1554});
1555
1556test!(CodegenUnits {
1557    path: "tests/codegen-units",
1558    mode: CompiletestMode::CodegenUnits,
1559    suite: "codegen-units",
1560    default: true,
1561});
1562
1563test!(Incremental {
1564    path: "tests/incremental",
1565    mode: CompiletestMode::Incremental,
1566    suite: "incremental",
1567    default: true,
1568});
1569
1570test!(Debuginfo {
1571    path: "tests/debuginfo",
1572    mode: CompiletestMode::Debuginfo,
1573    suite: "debuginfo",
1574    default: true,
1575    compare_mode: Some("split-dwarf"),
1576});
1577
1578test!(UiFullDeps {
1579    path: "tests/ui-fulldeps",
1580    mode: CompiletestMode::Ui,
1581    suite: "ui-fulldeps",
1582    default: true,
1583    IS_HOST: true,
1584});
1585
1586test!(Rustdoc {
1587    path: "tests/rustdoc",
1588    mode: CompiletestMode::Rustdoc,
1589    suite: "rustdoc",
1590    default: true,
1591    IS_HOST: true,
1592});
1593test!(RustdocUi {
1594    path: "tests/rustdoc-ui",
1595    mode: CompiletestMode::Ui,
1596    suite: "rustdoc-ui",
1597    default: true,
1598    IS_HOST: true,
1599});
1600
1601test!(RustdocJson {
1602    path: "tests/rustdoc-json",
1603    mode: CompiletestMode::RustdocJson,
1604    suite: "rustdoc-json",
1605    default: true,
1606    IS_HOST: true,
1607});
1608
1609test!(Pretty {
1610    path: "tests/pretty",
1611    mode: CompiletestMode::Pretty,
1612    suite: "pretty",
1613    default: true,
1614    IS_HOST: true,
1615});
1616
1617test!(RunMake {
1618    path: "tests/run-make",
1619    mode: CompiletestMode::RunMake,
1620    suite: "run-make",
1621    default: true,
1622});
1623test!(RunMakeCargo {
1624    path: "tests/run-make-cargo",
1625    mode: CompiletestMode::RunMake,
1626    suite: "run-make-cargo",
1627    default: true
1628});
1629
1630test!(AssemblyLlvm {
1631    path: "tests/assembly-llvm",
1632    mode: CompiletestMode::Assembly,
1633    suite: "assembly-llvm",
1634    default: true
1635});
1636
1637/// Runs the coverage test suite at `tests/coverage` in some or all of the
1638/// coverage test modes.
1639#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1640pub struct Coverage {
1641    pub compiler: Compiler,
1642    pub target: TargetSelection,
1643    pub(crate) mode: CompiletestMode,
1644}
1645
1646impl Coverage {
1647    const PATH: &'static str = "tests/coverage";
1648    const SUITE: &'static str = "coverage";
1649    const ALL_MODES: &[CompiletestMode] =
1650        &[CompiletestMode::CoverageMap, CompiletestMode::CoverageRun];
1651}
1652
1653impl Step for Coverage {
1654    type Output = ();
1655    /// Compiletest will automatically skip the "coverage-run" tests if necessary.
1656    const IS_HOST: bool = false;
1657
1658    fn should_run(mut run: ShouldRun<'_>) -> ShouldRun<'_> {
1659        // Support various invocation styles, including:
1660        // - `./x test coverage`
1661        // - `./x test tests/coverage/trivial.rs`
1662        // - `./x test coverage-map`
1663        // - `./x test coverage-run -- tests/coverage/trivial.rs`
1664        run = run.suite_path(Self::PATH);
1665        for mode in Self::ALL_MODES {
1666            run = run.alias(mode.as_str());
1667        }
1668        run
1669    }
1670
1671    fn is_default_step(_builder: &Builder<'_>) -> bool {
1672        true
1673    }
1674
1675    fn make_run(run: RunConfig<'_>) {
1676        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1677        let target = run.target;
1678
1679        // List of (coverage) test modes that the coverage test suite will be
1680        // run in. It's OK for this to contain duplicates, because the call to
1681        // `Builder::ensure` below will take care of deduplication.
1682        let mut modes = vec![];
1683
1684        // From the pathsets that were selected on the command-line (or by default),
1685        // determine which modes to run in.
1686        for path in &run.paths {
1687            match path {
1688                PathSet::Set(_) => {
1689                    for &mode in Self::ALL_MODES {
1690                        if path.assert_single_path().path == Path::new(mode.as_str()) {
1691                            modes.push(mode);
1692                            break;
1693                        }
1694                    }
1695                }
1696                PathSet::Suite(_) => {
1697                    modes.extend_from_slice(Self::ALL_MODES);
1698                    break;
1699                }
1700            }
1701        }
1702
1703        // Skip any modes that were explicitly skipped/excluded on the command-line.
1704        // FIXME(Zalathar): Integrate this into central skip handling somehow?
1705        modes.retain(|mode| {
1706            !run.builder.config.skip.iter().any(|skip| skip == Path::new(mode.as_str()))
1707        });
1708
1709        // FIXME(Zalathar): Make these commands skip all coverage tests, as expected:
1710        // - `./x test --skip=tests`
1711        // - `./x test --skip=tests/coverage`
1712        // - `./x test --skip=coverage`
1713        // Skip handling currently doesn't have a way to know that skipping the coverage
1714        // suite should also skip the `coverage-map` and `coverage-run` aliases.
1715
1716        for mode in modes {
1717            run.builder.ensure(Coverage { compiler, target, mode });
1718        }
1719    }
1720
1721    fn run(self, builder: &Builder<'_>) {
1722        let Self { compiler, target, mode } = self;
1723        // Like other compiletest suite test steps, delegate to an internal
1724        // compiletest task to actually run the tests.
1725        builder.ensure(Compiletest {
1726            test_compiler: compiler,
1727            target,
1728            mode,
1729            suite: Self::SUITE,
1730            path: Self::PATH,
1731            compare_mode: None,
1732        });
1733    }
1734}
1735
1736test!(CoverageRunRustdoc {
1737    path: "tests/coverage-run-rustdoc",
1738    mode: CompiletestMode::CoverageRun,
1739    suite: "coverage-run-rustdoc",
1740    default: true,
1741    IS_HOST: true,
1742});
1743
1744// For the mir-opt suite we do not use macros, as we need custom behavior when blessing.
1745#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1746pub struct MirOpt {
1747    pub compiler: Compiler,
1748    pub target: TargetSelection,
1749}
1750
1751impl Step for MirOpt {
1752    type Output = ();
1753
1754    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1755        run.suite_path("tests/mir-opt")
1756    }
1757
1758    fn is_default_step(_builder: &Builder<'_>) -> bool {
1759        true
1760    }
1761
1762    fn make_run(run: RunConfig<'_>) {
1763        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1764        run.builder.ensure(MirOpt { compiler, target: run.target });
1765    }
1766
1767    fn run(self, builder: &Builder<'_>) {
1768        let run = |target| {
1769            builder.ensure(Compiletest {
1770                test_compiler: self.compiler,
1771                target,
1772                mode: CompiletestMode::MirOpt,
1773                suite: "mir-opt",
1774                path: "tests/mir-opt",
1775                compare_mode: None,
1776            })
1777        };
1778
1779        run(self.target);
1780
1781        // Run more targets with `--bless`. But we always run the host target first, since some
1782        // tests use very specific `only` clauses that are not covered by the target set below.
1783        if builder.config.cmd.bless() {
1784            // All that we really need to do is cover all combinations of 32/64-bit and unwind/abort,
1785            // but while we're at it we might as well flex our cross-compilation support. This
1786            // selection covers all our tier 1 operating systems and architectures using only tier
1787            // 1 targets.
1788
1789            for target in ["aarch64-unknown-linux-gnu", "i686-pc-windows-msvc"] {
1790                run(TargetSelection::from_user(target));
1791            }
1792
1793            for target in ["x86_64-apple-darwin", "i686-unknown-linux-musl"] {
1794                let target = TargetSelection::from_user(target);
1795                let panic_abort_target = builder.ensure(MirOptPanicAbortSyntheticTarget {
1796                    compiler: self.compiler,
1797                    base: target,
1798                });
1799                run(panic_abort_target);
1800            }
1801        }
1802    }
1803}
1804
1805/// Executes the `compiletest` tool to run a suite of tests.
1806///
1807/// Compiles all tests with `test_compiler` for `target` with the specified
1808/// compiletest `mode` and `suite` arguments. For example `mode` can be
1809/// "mir-opt" and `suite` can be something like "debuginfo".
1810#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1811struct Compiletest {
1812    /// The compiler that we're testing.
1813    test_compiler: Compiler,
1814    target: TargetSelection,
1815    mode: CompiletestMode,
1816    suite: &'static str,
1817    path: &'static str,
1818    compare_mode: Option<&'static str>,
1819}
1820
1821impl Step for Compiletest {
1822    type Output = ();
1823
1824    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1825        run.never()
1826    }
1827
1828    fn run(self, builder: &Builder<'_>) {
1829        if builder.doc_tests == DocTests::Only {
1830            return;
1831        }
1832
1833        if builder.top_stage == 0 && !builder.config.compiletest_allow_stage0 {
1834            eprintln!("\
1835ERROR: `--stage 0` runs compiletest on the stage0 (precompiled) compiler, not your local changes, and will almost always cause tests to fail
1836HELP: to test the compiler or standard library, omit the stage or explicitly use `--stage 1` instead
1837NOTE: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `--set build.compiletest-allow-stage0=true`."
1838            );
1839            crate::exit!(1);
1840        }
1841
1842        let mut test_compiler = self.test_compiler;
1843        let target = self.target;
1844        let mode = self.mode;
1845        let suite = self.suite;
1846
1847        // Path for test suite
1848        let suite_path = self.path;
1849
1850        // Skip codegen tests if they aren't enabled in configuration.
1851        if !builder.config.codegen_tests && mode == CompiletestMode::Codegen {
1852            return;
1853        }
1854
1855        // Support stage 1 ui-fulldeps. This is somewhat complicated: ui-fulldeps tests for the most
1856        // part test the *API* of the compiler, not how it compiles a given file. As a result, we
1857        // can run them against the stage 1 sources as long as we build them with the stage 0
1858        // bootstrap compiler.
1859        // NOTE: Only stage 1 is special cased because we need the rustc_private artifacts to match the
1860        // running compiler in stage 2 when plugins run.
1861        let query_compiler;
1862        let (stage, stage_id) = if suite == "ui-fulldeps" && test_compiler.stage == 1 {
1863            // Even when using the stage 0 compiler, we also need to provide the stage 1 compiler
1864            // so that compiletest can query it for target information.
1865            query_compiler = Some(test_compiler);
1866            // At stage 0 (stage - 1) we are using the stage0 compiler. Using `self.target` can lead
1867            // finding an incorrect compiler path on cross-targets, as the stage 0 is always equal to
1868            // `build.build` in the configuration.
1869            let build = builder.build.host_target;
1870            test_compiler = builder.compiler(test_compiler.stage - 1, build);
1871            let test_stage = test_compiler.stage + 1;
1872            (test_stage, format!("stage{test_stage}-{build}"))
1873        } else {
1874            query_compiler = None;
1875            let stage = test_compiler.stage;
1876            (stage, format!("stage{stage}-{target}"))
1877        };
1878
1879        if suite.ends_with("fulldeps") {
1880            builder.ensure(compile::Rustc::new(test_compiler, target));
1881        }
1882
1883        if suite == "debuginfo" {
1884            builder.ensure(dist::DebuggerScripts {
1885                sysroot: builder.sysroot(test_compiler).to_path_buf(),
1886                target,
1887            });
1888        }
1889        if mode == CompiletestMode::RunMake {
1890            builder.tool_exe(Tool::RunMakeSupport);
1891        }
1892
1893        // ensure that `libproc_macro` is available on the host.
1894        if suite == "mir-opt" {
1895            builder.ensure(
1896                compile::Std::new(test_compiler, test_compiler.host).is_for_mir_opt_tests(true),
1897            );
1898        } else {
1899            builder.std(test_compiler, test_compiler.host);
1900        }
1901
1902        let mut cmd = builder.tool_cmd(Tool::Compiletest);
1903
1904        if suite == "mir-opt" {
1905            builder.ensure(compile::Std::new(test_compiler, target).is_for_mir_opt_tests(true));
1906        } else {
1907            builder.std(test_compiler, target);
1908        }
1909
1910        builder.ensure(RemoteCopyLibs { build_compiler: test_compiler, target });
1911
1912        // compiletest currently has... a lot of arguments, so let's just pass all
1913        // of them!
1914
1915        cmd.arg("--stage").arg(stage.to_string());
1916        cmd.arg("--stage-id").arg(stage_id);
1917
1918        cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(test_compiler));
1919        cmd.arg("--run-lib-path").arg(builder.sysroot_target_libdir(test_compiler, target));
1920        cmd.arg("--rustc-path").arg(builder.rustc(test_compiler));
1921        if let Some(query_compiler) = query_compiler {
1922            cmd.arg("--query-rustc-path").arg(builder.rustc(query_compiler));
1923        }
1924
1925        // Minicore auxiliary lib for `no_core` tests that need `core` stubs in cross-compilation
1926        // scenarios.
1927        cmd.arg("--minicore-path")
1928            .arg(builder.src.join("tests").join("auxiliary").join("minicore.rs"));
1929
1930        let is_rustdoc = suite == "rustdoc-ui" || suite == "rustdoc-js";
1931
1932        // There are (potentially) 2 `cargo`s to consider:
1933        //
1934        // - A "bootstrap" cargo, which is the same cargo used to build bootstrap itself, and is
1935        //   used to build the `run-make` test recipes and the `run-make-support` test library. All
1936        //   of these may not use unstable rustc/cargo features.
1937        // - An in-tree cargo, which should be considered as under test. The `run-make-cargo` test
1938        //   suite is intended to support the use case of testing the "toolchain" (that is, at the
1939        //   minimum the interaction between in-tree cargo + rustc) together.
1940        //
1941        // For build time and iteration purposes, we partition `run-make` tests which needs an
1942        // in-tree cargo (a smaller subset) versus `run-make` tests that do not into two test
1943        // suites, `run-make` and `run-make-cargo`. That way, contributors who do not need to run
1944        // the `run-make` tests that need in-tree cargo do not need to spend time building in-tree
1945        // cargo.
1946        if mode == CompiletestMode::RunMake {
1947            // We need to pass the compiler that was used to compile run-make-support,
1948            // because we have to use the same compiler to compile rmake.rs recipes.
1949            let stage0_rustc_path = builder.compiler(0, test_compiler.host);
1950            cmd.arg("--stage0-rustc-path").arg(builder.rustc(stage0_rustc_path));
1951
1952            if suite == "run-make-cargo" {
1953                let cargo_path = if test_compiler.stage == 0 {
1954                    // If we're using `--stage 0`, we should provide the bootstrap cargo.
1955                    builder.initial_cargo.clone()
1956                } else {
1957                    builder
1958                        .ensure(tool::Cargo::from_build_compiler(
1959                            builder.compiler(test_compiler.stage - 1, test_compiler.host),
1960                            test_compiler.host,
1961                        ))
1962                        .tool_path
1963                };
1964
1965                cmd.arg("--cargo-path").arg(cargo_path);
1966            }
1967        }
1968
1969        // Avoid depending on rustdoc when we don't need it.
1970        if matches!(
1971            mode,
1972            CompiletestMode::RunMake
1973                | CompiletestMode::Rustdoc
1974                | CompiletestMode::RustdocJs
1975                | CompiletestMode::RustdocJson
1976        ) || matches!(suite, "rustdoc-ui" | "coverage-run-rustdoc")
1977        {
1978            cmd.arg("--rustdoc-path").arg(builder.rustdoc_for_compiler(test_compiler));
1979        }
1980
1981        if mode == CompiletestMode::RustdocJson {
1982            // Use the stage0 compiler for jsondocck
1983            let json_compiler = builder.compiler(0, builder.host_target);
1984            cmd.arg("--jsondocck-path")
1985                .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }).tool_path);
1986            cmd.arg("--jsondoclint-path").arg(
1987                builder.ensure(tool::JsonDocLint { compiler: json_compiler, target }).tool_path,
1988            );
1989        }
1990
1991        if matches!(mode, CompiletestMode::CoverageMap | CompiletestMode::CoverageRun) {
1992            let coverage_dump = builder.tool_exe(Tool::CoverageDump);
1993            cmd.arg("--coverage-dump-path").arg(coverage_dump);
1994        }
1995
1996        cmd.arg("--src-root").arg(&builder.src);
1997        cmd.arg("--src-test-suite-root").arg(builder.src.join("tests").join(suite));
1998
1999        // N.B. it's important to distinguish between the *root* build directory, the *host* build
2000        // directory immediately under the root build directory, and the test-suite-specific build
2001        // directory.
2002        cmd.arg("--build-root").arg(&builder.out);
2003        cmd.arg("--build-test-suite-root").arg(testdir(builder, test_compiler.host).join(suite));
2004
2005        // When top stage is 0, that means that we're testing an externally provided compiler.
2006        // In that case we need to use its specific sysroot for tests to pass.
2007        // Note: DO NOT check if test_compiler.stage is 0, because the test compiler can be stage 0
2008        // even if the top stage is 1 (when we run the ui-fulldeps suite).
2009        let sysroot = if builder.top_stage == 0 {
2010            builder.initial_sysroot.clone()
2011        } else {
2012            builder.sysroot(test_compiler)
2013        };
2014
2015        cmd.arg("--sysroot-base").arg(sysroot);
2016
2017        cmd.arg("--suite").arg(suite);
2018        cmd.arg("--mode").arg(mode.as_str());
2019        cmd.arg("--target").arg(target.rustc_target_arg());
2020        cmd.arg("--host").arg(&*test_compiler.host.triple);
2021        cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.host_target));
2022
2023        if let Some(codegen_backend) = builder.config.cmd.test_codegen_backend() {
2024            if !builder
2025                .config
2026                .enabled_codegen_backends(test_compiler.host)
2027                .contains(codegen_backend)
2028            {
2029                eprintln!(
2030                    "\
2031ERROR: No configured backend named `{name}`
2032HELP: You can add it into `bootstrap.toml` in `rust.codegen-backends = [{name:?}]`",
2033                    name = codegen_backend.name(),
2034                );
2035                crate::exit!(1);
2036            }
2037
2038            if let CodegenBackendKind::Gcc = codegen_backend
2039                && builder.config.rustc_debug_assertions
2040            {
2041                eprintln!(
2042                    r#"WARNING: Running tests with the GCC codegen backend while rustc debug assertions are enabled. This might lead to test failures.
2043Please disable assertions with `rust.debug-assertions = false`.
2044        "#
2045                );
2046            }
2047
2048            // Tells compiletest that we want to use this codegen in particular and to override
2049            // the default one.
2050            cmd.arg("--override-codegen-backend").arg(codegen_backend.name());
2051            // Tells compiletest which codegen backend to use.
2052            // It is used to e.g. ignore tests that don't support that codegen backend.
2053            cmd.arg("--default-codegen-backend").arg(codegen_backend.name());
2054        } else {
2055            // Tells compiletest which codegen backend to use.
2056            // It is used to e.g. ignore tests that don't support that codegen backend.
2057            cmd.arg("--default-codegen-backend")
2058                .arg(builder.config.default_codegen_backend(test_compiler.host).name());
2059        }
2060        if builder.config.cmd.bypass_ignore_backends() {
2061            cmd.arg("--bypass-ignore-backends");
2062        }
2063
2064        if builder.build.config.llvm_enzyme {
2065            cmd.arg("--has-enzyme");
2066        }
2067
2068        if builder.config.cmd.bless() {
2069            cmd.arg("--bless");
2070        }
2071
2072        if builder.config.cmd.force_rerun() {
2073            cmd.arg("--force-rerun");
2074        }
2075
2076        if builder.config.cmd.no_capture() {
2077            cmd.arg("--no-capture");
2078        }
2079
2080        let compare_mode =
2081            builder.config.cmd.compare_mode().or_else(|| {
2082                if builder.config.test_compare_mode { self.compare_mode } else { None }
2083            });
2084
2085        if let Some(ref pass) = builder.config.cmd.pass() {
2086            cmd.arg("--pass");
2087            cmd.arg(pass);
2088        }
2089
2090        if let Some(ref run) = builder.config.cmd.run() {
2091            cmd.arg("--run");
2092            cmd.arg(run);
2093        }
2094
2095        if let Some(ref nodejs) = builder.config.nodejs {
2096            cmd.arg("--nodejs").arg(nodejs);
2097        } else if mode == CompiletestMode::RustdocJs {
2098            panic!("need nodejs to run rustdoc-js suite");
2099        }
2100        if builder.config.rust_optimize_tests {
2101            cmd.arg("--optimize-tests");
2102        }
2103        if builder.config.rust_randomize_layout {
2104            cmd.arg("--rust-randomized-layout");
2105        }
2106        if builder.config.cmd.only_modified() {
2107            cmd.arg("--only-modified");
2108        }
2109        if let Some(compiletest_diff_tool) = &builder.config.compiletest_diff_tool {
2110            cmd.arg("--compiletest-diff-tool").arg(compiletest_diff_tool);
2111        }
2112
2113        let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
2114        flags.push(format!(
2115            "-Cdebuginfo={}",
2116            if mode == CompiletestMode::Codegen {
2117                // codegen tests typically check LLVM IR and are sensitive to additional debuginfo.
2118                // So do not apply `rust.debuginfo-level-tests` for codegen tests.
2119                if builder.config.rust_debuginfo_level_tests
2120                    != crate::core::config::DebuginfoLevel::None
2121                {
2122                    println!(
2123                        "NOTE: ignoring `rust.debuginfo-level-tests={}` for codegen tests",
2124                        builder.config.rust_debuginfo_level_tests
2125                    );
2126                }
2127                crate::core::config::DebuginfoLevel::None
2128            } else {
2129                builder.config.rust_debuginfo_level_tests
2130            }
2131        ));
2132        flags.extend(builder.config.cmd.compiletest_rustc_args().iter().map(|s| s.to_string()));
2133
2134        if suite != "mir-opt" {
2135            if let Some(linker) = builder.linker(target) {
2136                cmd.arg("--target-linker").arg(linker);
2137            }
2138            if let Some(linker) = builder.linker(test_compiler.host) {
2139                cmd.arg("--host-linker").arg(linker);
2140            }
2141        }
2142
2143        // FIXME(136096): on macOS, we get linker warnings about duplicate `-lm` flags.
2144        if suite == "ui-fulldeps" && target.ends_with("darwin") {
2145            flags.push("-Alinker_messages".into());
2146        }
2147
2148        let mut hostflags = flags.clone();
2149        hostflags.extend(linker_flags(builder, test_compiler.host, LldThreads::No));
2150
2151        let mut targetflags = flags;
2152
2153        // Provide `rust_test_helpers` for both host and target.
2154        if suite == "ui" || suite == "incremental" {
2155            builder.ensure(TestHelpers { target: test_compiler.host });
2156            builder.ensure(TestHelpers { target });
2157            hostflags.push(format!(
2158                "-Lnative={}",
2159                builder.test_helpers_out(test_compiler.host).display()
2160            ));
2161            targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
2162        }
2163
2164        for flag in hostflags {
2165            cmd.arg("--host-rustcflags").arg(flag);
2166        }
2167        for flag in targetflags {
2168            cmd.arg("--target-rustcflags").arg(flag);
2169        }
2170
2171        cmd.arg("--python").arg(
2172            builder.config.python.as_ref().expect("python is required for running rustdoc tests"),
2173        );
2174
2175        // Discover and set some flags related to running tests on Android targets.
2176        let android = android::discover_android(builder, target);
2177        if let Some(android::Android { adb_path, adb_test_dir, android_cross_path }) = &android {
2178            cmd.arg("--adb-path").arg(adb_path);
2179            cmd.arg("--adb-test-dir").arg(adb_test_dir);
2180            cmd.arg("--android-cross-path").arg(android_cross_path);
2181        }
2182
2183        if mode == CompiletestMode::Debuginfo {
2184            if let Some(debuggers::Gdb { gdb }) = debuggers::discover_gdb(builder, android.as_ref())
2185            {
2186                cmd.arg("--gdb").arg(gdb.as_ref());
2187            }
2188
2189            if let Some(debuggers::Lldb { lldb_exe, lldb_version }) =
2190                debuggers::discover_lldb(builder)
2191            {
2192                cmd.arg("--lldb").arg(lldb_exe);
2193                cmd.arg("--lldb-version").arg(lldb_version);
2194            }
2195        }
2196
2197        if helpers::forcing_clang_based_tests() {
2198            let clang_exe = builder.llvm_out(target).join("bin").join("clang");
2199            cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
2200        }
2201
2202        for exclude in &builder.config.skip {
2203            cmd.arg("--skip");
2204            cmd.arg(exclude);
2205        }
2206
2207        // Get paths from cmd args
2208        let mut paths = match &builder.config.cmd {
2209            Subcommand::Test { .. } => &builder.config.paths[..],
2210            _ => &[],
2211        };
2212
2213        // in rustdoc-js mode, allow filters to be rs files or js files.
2214        // use a late-initialized Vec to avoid cloning for other modes.
2215        let mut paths_v;
2216        if mode == CompiletestMode::RustdocJs {
2217            paths_v = paths.to_vec();
2218            for p in &mut paths_v {
2219                if let Some(ext) = p.extension()
2220                    && ext == "js"
2221                {
2222                    p.set_extension("rs");
2223                }
2224            }
2225            paths = &paths_v;
2226        }
2227        // Get test-args by striping suite path
2228        let mut test_args: Vec<&str> = paths
2229            .iter()
2230            .filter_map(|p| helpers::is_valid_test_suite_arg(p, suite_path, builder))
2231            .collect();
2232
2233        test_args.append(&mut builder.config.test_args());
2234
2235        // On Windows, replace forward slashes in test-args by backslashes
2236        // so the correct filters are passed to libtest
2237        if cfg!(windows) {
2238            let test_args_win: Vec<String> =
2239                test_args.iter().map(|s| s.replace('/', "\\")).collect();
2240            cmd.args(&test_args_win);
2241        } else {
2242            cmd.args(&test_args);
2243        }
2244
2245        if builder.is_verbose() {
2246            cmd.arg("--verbose");
2247        }
2248
2249        if builder.config.rustc_debug_assertions {
2250            cmd.arg("--with-rustc-debug-assertions");
2251        }
2252
2253        if builder.config.std_debug_assertions {
2254            cmd.arg("--with-std-debug-assertions");
2255        }
2256
2257        let mut llvm_components_passed = false;
2258        let mut copts_passed = false;
2259        if builder.config.llvm_enabled(test_compiler.host) {
2260            let llvm::LlvmResult { host_llvm_config, .. } =
2261                builder.ensure(llvm::Llvm { target: builder.config.host_target });
2262            if !builder.config.dry_run() {
2263                let llvm_version = get_llvm_version(builder, &host_llvm_config);
2264                let llvm_components = command(&host_llvm_config)
2265                    .cached()
2266                    .arg("--components")
2267                    .run_capture_stdout(builder)
2268                    .stdout();
2269                // Remove trailing newline from llvm-config output.
2270                cmd.arg("--llvm-version")
2271                    .arg(llvm_version.trim())
2272                    .arg("--llvm-components")
2273                    .arg(llvm_components.trim());
2274                llvm_components_passed = true;
2275            }
2276            if !builder.config.is_rust_llvm(target) {
2277                cmd.arg("--system-llvm");
2278            }
2279
2280            // Tests that use compiler libraries may inherit the `-lLLVM` link
2281            // requirement, but the `-L` library path is not propagated across
2282            // separate compilations. We can add LLVM's library path to the
2283            // rustc args as a workaround.
2284            if !builder.config.dry_run() && suite.ends_with("fulldeps") {
2285                let llvm_libdir = command(&host_llvm_config)
2286                    .cached()
2287                    .arg("--libdir")
2288                    .run_capture_stdout(builder)
2289                    .stdout();
2290                let link_llvm = if target.is_msvc() {
2291                    format!("-Clink-arg=-LIBPATH:{llvm_libdir}")
2292                } else {
2293                    format!("-Clink-arg=-L{llvm_libdir}")
2294                };
2295                cmd.arg("--host-rustcflags").arg(link_llvm);
2296            }
2297
2298            if !builder.config.dry_run()
2299                && matches!(mode, CompiletestMode::RunMake | CompiletestMode::CoverageRun)
2300            {
2301                // The llvm/bin directory contains many useful cross-platform
2302                // tools. Pass the path to run-make tests so they can use them.
2303                // (The coverage-run tests also need these tools to process
2304                // coverage reports.)
2305                let llvm_bin_path = host_llvm_config
2306                    .parent()
2307                    .expect("Expected llvm-config to be contained in directory");
2308                assert!(llvm_bin_path.is_dir());
2309                cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
2310            }
2311
2312            if !builder.config.dry_run() && mode == CompiletestMode::RunMake {
2313                // If LLD is available, add it to the PATH
2314                if builder.config.lld_enabled {
2315                    let lld_install_root =
2316                        builder.ensure(llvm::Lld { target: builder.config.host_target });
2317
2318                    let lld_bin_path = lld_install_root.join("bin");
2319
2320                    let old_path = env::var_os("PATH").unwrap_or_default();
2321                    let new_path = env::join_paths(
2322                        std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
2323                    )
2324                    .expect("Could not add LLD bin path to PATH");
2325                    cmd.env("PATH", new_path);
2326                }
2327            }
2328        }
2329
2330        // Only pass correct values for these flags for the `run-make` suite as it
2331        // requires that a C++ compiler was configured which isn't always the case.
2332        if !builder.config.dry_run() && mode == CompiletestMode::RunMake {
2333            let mut cflags = builder.cc_handled_clags(target, CLang::C);
2334            cflags.extend(builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::C));
2335            let mut cxxflags = builder.cc_handled_clags(target, CLang::Cxx);
2336            cxxflags.extend(builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx));
2337            cmd.arg("--cc")
2338                .arg(builder.cc(target))
2339                .arg("--cxx")
2340                .arg(builder.cxx(target).unwrap())
2341                .arg("--cflags")
2342                .arg(cflags.join(" "))
2343                .arg("--cxxflags")
2344                .arg(cxxflags.join(" "));
2345            copts_passed = true;
2346            if let Some(ar) = builder.ar(target) {
2347                cmd.arg("--ar").arg(ar);
2348            }
2349        }
2350
2351        if !llvm_components_passed {
2352            cmd.arg("--llvm-components").arg("");
2353        }
2354        if !copts_passed {
2355            cmd.arg("--cc")
2356                .arg("")
2357                .arg("--cxx")
2358                .arg("")
2359                .arg("--cflags")
2360                .arg("")
2361                .arg("--cxxflags")
2362                .arg("");
2363        }
2364
2365        if builder.remote_tested(target) {
2366            cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
2367        } else if let Some(tool) = builder.runner(target) {
2368            cmd.arg("--runner").arg(tool);
2369        }
2370
2371        if suite != "mir-opt" {
2372            // Running a C compiler on MSVC requires a few env vars to be set, to be
2373            // sure to set them here.
2374            //
2375            // Note that if we encounter `PATH` we make sure to append to our own `PATH`
2376            // rather than stomp over it.
2377            if !builder.config.dry_run() && target.is_msvc() {
2378                for (k, v) in builder.cc[&target].env() {
2379                    if k != "PATH" {
2380                        cmd.env(k, v);
2381                    }
2382                }
2383            }
2384        }
2385
2386        // Special setup to enable running with sanitizers on MSVC.
2387        if !builder.config.dry_run()
2388            && target.contains("msvc")
2389            && builder.config.sanitizers_enabled(target)
2390        {
2391            // Ignore interception failures: not all dlls in the process will have been built with
2392            // address sanitizer enabled (e.g., ntdll.dll).
2393            cmd.env("ASAN_WIN_CONTINUE_ON_INTERCEPTION_FAILURE", "1");
2394            // Add the address sanitizer runtime to the PATH - it is located next to cl.exe.
2395            let asan_runtime_path = builder.cc[&target].path().parent().unwrap().to_path_buf();
2396            let old_path = cmd
2397                .get_envs()
2398                .find_map(|(k, v)| (k == "PATH").then_some(v))
2399                .flatten()
2400                .map_or_else(|| env::var_os("PATH").unwrap_or_default(), |v| v.to_owned());
2401            let new_path = env::join_paths(
2402                env::split_paths(&old_path).chain(std::iter::once(asan_runtime_path)),
2403            )
2404            .expect("Could not add ASAN runtime path to PATH");
2405            cmd.env("PATH", new_path);
2406        }
2407
2408        // Some UI tests trigger behavior in rustc where it reads $CARGO and changes behavior if it exists.
2409        // To make the tests work that rely on it not being set, make sure it is not set.
2410        cmd.env_remove("CARGO");
2411
2412        cmd.env("RUSTC_BOOTSTRAP", "1");
2413        // Override the rustc version used in symbol hashes to reduce the amount of normalization
2414        // needed when diffing test output.
2415        cmd.env("RUSTC_FORCE_RUSTC_VERSION", "compiletest");
2416        cmd.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
2417        builder.add_rust_test_threads(&mut cmd);
2418
2419        if builder.config.sanitizers_enabled(target) {
2420            cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
2421        }
2422
2423        if builder.config.profiler_enabled(target) {
2424            cmd.arg("--profiler-runtime");
2425        }
2426
2427        cmd.env("RUST_TEST_TMPDIR", builder.tempdir());
2428
2429        if builder.config.cmd.rustfix_coverage() {
2430            cmd.arg("--rustfix-coverage");
2431        }
2432
2433        cmd.arg("--channel").arg(&builder.config.channel);
2434
2435        if !builder.config.omit_git_hash {
2436            cmd.arg("--git-hash");
2437        }
2438
2439        let git_config = builder.config.git_config();
2440        cmd.arg("--nightly-branch").arg(git_config.nightly_branch);
2441        cmd.arg("--git-merge-commit-email").arg(git_config.git_merge_commit_email);
2442
2443        #[cfg(feature = "build-metrics")]
2444        builder.metrics.begin_test_suite(
2445            build_helper::metrics::TestSuiteMetadata::Compiletest {
2446                suite: suite.into(),
2447                mode: mode.to_string(),
2448                compare_mode: None,
2449                target: self.target.triple.to_string(),
2450                host: self.test_compiler.host.triple.to_string(),
2451                stage: self.test_compiler.stage,
2452            },
2453            builder,
2454        );
2455
2456        let _group = builder.msg_test(
2457            format!("with compiletest suite={suite} mode={mode}"),
2458            target,
2459            test_compiler.stage,
2460        );
2461        try_run_tests(builder, &mut cmd, false);
2462
2463        if let Some(compare_mode) = compare_mode {
2464            cmd.arg("--compare-mode").arg(compare_mode);
2465
2466            #[cfg(feature = "build-metrics")]
2467            builder.metrics.begin_test_suite(
2468                build_helper::metrics::TestSuiteMetadata::Compiletest {
2469                    suite: suite.into(),
2470                    mode: mode.to_string(),
2471                    compare_mode: Some(compare_mode.into()),
2472                    target: self.target.triple.to_string(),
2473                    host: self.test_compiler.host.triple.to_string(),
2474                    stage: self.test_compiler.stage,
2475                },
2476                builder,
2477            );
2478
2479            builder.info(&format!(
2480                "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
2481                suite, mode, compare_mode, &test_compiler.host, target
2482            ));
2483            let _time = helpers::timeit(builder);
2484            try_run_tests(builder, &mut cmd, false);
2485        }
2486    }
2487
2488    fn metadata(&self) -> Option<StepMetadata> {
2489        Some(
2490            StepMetadata::test(&format!("compiletest-{}", self.suite), self.target)
2491                .stage(self.test_compiler.stage),
2492        )
2493    }
2494}
2495
2496/// Runs the documentation tests for a book in `src/doc` using the `rustdoc` of `test_compiler`.
2497#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2498struct BookTest {
2499    test_compiler: Compiler,
2500    path: PathBuf,
2501    name: &'static str,
2502    is_ext_doc: bool,
2503    dependencies: Vec<&'static str>,
2504}
2505
2506impl Step for BookTest {
2507    type Output = ();
2508    const IS_HOST: bool = true;
2509
2510    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2511        run.never()
2512    }
2513
2514    fn run(self, builder: &Builder<'_>) {
2515        // External docs are different from local because:
2516        // - Some books need pre-processing by mdbook before being tested.
2517        // - They need to save their state to toolstate.
2518        // - They are only tested on the "checktools" builders.
2519        //
2520        // The local docs are tested by default, and we don't want to pay the
2521        // cost of building mdbook, so they use `rustdoc --test` directly.
2522        // Also, the unstable book is special because SUMMARY.md is generated,
2523        // so it is easier to just run `rustdoc` on its files.
2524        if self.is_ext_doc {
2525            self.run_ext_doc(builder);
2526        } else {
2527            self.run_local_doc(builder);
2528        }
2529    }
2530}
2531
2532impl BookTest {
2533    /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
2534    /// which in turn runs `rustdoc --test` on each file in the book.
2535    fn run_ext_doc(self, builder: &Builder<'_>) {
2536        let test_compiler = self.test_compiler;
2537
2538        builder.std(test_compiler, test_compiler.host);
2539
2540        // mdbook just executes a binary named "rustdoc", so we need to update
2541        // PATH so that it points to our rustdoc.
2542        let mut rustdoc_path = builder.rustdoc_for_compiler(test_compiler);
2543        rustdoc_path.pop();
2544        let old_path = env::var_os("PATH").unwrap_or_default();
2545        let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
2546            .expect("could not add rustdoc to PATH");
2547
2548        let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
2549        let path = builder.src.join(&self.path);
2550        // Books often have feature-gated example text.
2551        rustbook_cmd.env("RUSTC_BOOTSTRAP", "1");
2552        rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
2553
2554        // Books may also need to build dependencies. For example, `TheBook` has
2555        // code samples which use the `trpl` crate. For the `rustdoc` invocation
2556        // to find them them successfully, they need to be built first and their
2557        // paths used to generate the
2558        let libs = if !self.dependencies.is_empty() {
2559            let mut lib_paths = vec![];
2560            for dep in self.dependencies {
2561                let mode = Mode::ToolRustcPrivate;
2562                let target = builder.config.host_target;
2563                let cargo = tool::prepare_tool_cargo(
2564                    builder,
2565                    test_compiler,
2566                    mode,
2567                    target,
2568                    Kind::Build,
2569                    dep,
2570                    SourceType::Submodule,
2571                    &[],
2572                );
2573
2574                let stamp = BuildStamp::new(&builder.cargo_out(test_compiler, mode, target))
2575                    .with_prefix(PathBuf::from(dep).file_name().and_then(|v| v.to_str()).unwrap());
2576
2577                let output_paths = run_cargo(builder, cargo, vec![], &stamp, vec![], false, false);
2578                let directories = output_paths
2579                    .into_iter()
2580                    .filter_map(|p| p.parent().map(ToOwned::to_owned))
2581                    .fold(HashSet::new(), |mut set, dir| {
2582                        set.insert(dir);
2583                        set
2584                    });
2585
2586                lib_paths.extend(directories);
2587            }
2588            lib_paths
2589        } else {
2590            vec![]
2591        };
2592
2593        if !libs.is_empty() {
2594            let paths = libs
2595                .into_iter()
2596                .map(|path| path.into_os_string())
2597                .collect::<Vec<OsString>>()
2598                .join(OsStr::new(","));
2599            rustbook_cmd.args([OsString::from("--library-path"), paths]);
2600        }
2601
2602        builder.add_rust_test_threads(&mut rustbook_cmd);
2603        let _guard = builder.msg_test(
2604            format_args!("mdbook {}", self.path.display()),
2605            test_compiler.host,
2606            test_compiler.stage,
2607        );
2608        let _time = helpers::timeit(builder);
2609        let toolstate = if rustbook_cmd.delay_failure().run(builder) {
2610            ToolState::TestPass
2611        } else {
2612            ToolState::TestFail
2613        };
2614        builder.save_toolstate(self.name, toolstate);
2615    }
2616
2617    /// This runs `rustdoc --test` on all `.md` files in the path.
2618    fn run_local_doc(self, builder: &Builder<'_>) {
2619        let test_compiler = self.test_compiler;
2620        let host = self.test_compiler.host;
2621
2622        builder.std(test_compiler, host);
2623
2624        let _guard = builder.msg_test(
2625            format!("book {}", self.name),
2626            test_compiler.host,
2627            test_compiler.stage,
2628        );
2629
2630        // Do a breadth-first traversal of the `src/doc` directory and just run
2631        // tests for all files that end in `*.md`
2632        let mut stack = vec![builder.src.join(self.path)];
2633        let _time = helpers::timeit(builder);
2634        let mut files = Vec::new();
2635        while let Some(p) = stack.pop() {
2636            if p.is_dir() {
2637                stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
2638                continue;
2639            }
2640
2641            if p.extension().and_then(|s| s.to_str()) != Some("md") {
2642                continue;
2643            }
2644
2645            files.push(p);
2646        }
2647
2648        files.sort();
2649
2650        for file in files {
2651            markdown_test(builder, test_compiler, &file);
2652        }
2653    }
2654}
2655
2656macro_rules! test_book {
2657    ($(
2658        $name:ident, $path:expr, $book_name:expr,
2659        default=$default:expr
2660        $(,submodules = $submodules:expr)?
2661        $(,dependencies=$dependencies:expr)?
2662        ;
2663    )+) => {
2664        $(
2665            #[derive(Debug, Clone, PartialEq, Eq, Hash)]
2666            pub struct $name {
2667                test_compiler: Compiler,
2668            }
2669
2670            impl Step for $name {
2671                type Output = ();
2672                const IS_HOST: bool = true;
2673
2674                fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2675                    run.path($path)
2676                }
2677
2678                fn is_default_step(_builder: &Builder<'_>) -> bool {
2679                    const { $default }
2680                }
2681
2682                fn make_run(run: RunConfig<'_>) {
2683                    run.builder.ensure($name {
2684                        test_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2685                    });
2686                }
2687
2688                fn run(self, builder: &Builder<'_>) {
2689                    $(
2690                        for submodule in $submodules {
2691                            builder.require_submodule(submodule, None);
2692                        }
2693                    )*
2694
2695                    let dependencies = vec![];
2696                    $(
2697                        let mut dependencies = dependencies;
2698                        for dep in $dependencies {
2699                            dependencies.push(dep);
2700                        }
2701                    )?
2702
2703                    builder.ensure(BookTest {
2704                        test_compiler: self.test_compiler,
2705                        path: PathBuf::from($path),
2706                        name: $book_name,
2707                        is_ext_doc: !$default,
2708                        dependencies,
2709                    });
2710                }
2711            }
2712        )+
2713    }
2714}
2715
2716test_book!(
2717    Nomicon, "src/doc/nomicon", "nomicon", default=false, submodules=["src/doc/nomicon"];
2718    Reference, "src/doc/reference", "reference", default=false, submodules=["src/doc/reference"];
2719    RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
2720    RustcBook, "src/doc/rustc", "rustc", default=true;
2721    RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false, submodules=["src/doc/rust-by-example"];
2722    EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false, submodules=["src/doc/embedded-book"];
2723    TheBook, "src/doc/book", "book", default=false, submodules=["src/doc/book"], dependencies=["src/doc/book/packages/trpl"];
2724    UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
2725    EditionGuide, "src/doc/edition-guide", "edition-guide", default=false, submodules=["src/doc/edition-guide"];
2726);
2727
2728#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2729pub struct ErrorIndex {
2730    compilers: RustcPrivateCompilers,
2731}
2732
2733impl Step for ErrorIndex {
2734    type Output = ();
2735    const IS_HOST: bool = true;
2736
2737    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2738        // Also add `error-index` here since that is what appears in the error message
2739        // when this fails.
2740        run.path("src/tools/error_index_generator").alias("error-index")
2741    }
2742
2743    fn is_default_step(_builder: &Builder<'_>) -> bool {
2744        true
2745    }
2746
2747    fn make_run(run: RunConfig<'_>) {
2748        // error_index_generator depends on librustdoc. Use the compiler that
2749        // is normally used to build rustdoc for other tests (like compiletest
2750        // tests in tests/rustdoc) so that it shares the same artifacts.
2751        let compilers = RustcPrivateCompilers::new(
2752            run.builder,
2753            run.builder.top_stage,
2754            run.builder.config.host_target,
2755        );
2756        run.builder.ensure(ErrorIndex { compilers });
2757    }
2758
2759    /// Runs the error index generator tool to execute the tests located in the error
2760    /// index.
2761    ///
2762    /// The `error_index_generator` tool lives in `src/tools` and is used to
2763    /// generate a markdown file from the error indexes of the code base which is
2764    /// then passed to `rustdoc --test`.
2765    fn run(self, builder: &Builder<'_>) {
2766        // The compiler that we are testing
2767        let target_compiler = self.compilers.target_compiler();
2768
2769        let dir = testdir(builder, target_compiler.host);
2770        t!(fs::create_dir_all(&dir));
2771        let output = dir.join("error-index.md");
2772
2773        let mut tool = tool::ErrorIndex::command(builder, self.compilers);
2774        tool.arg("markdown").arg(&output);
2775
2776        let guard = builder.msg_test("error-index", target_compiler.host, target_compiler.stage);
2777        let _time = helpers::timeit(builder);
2778        tool.run_capture(builder);
2779        drop(guard);
2780        // The tests themselves need to link to std, so make sure it is
2781        // available.
2782        builder.std(target_compiler, target_compiler.host);
2783        markdown_test(builder, target_compiler, &output);
2784    }
2785}
2786
2787fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
2788    if let Ok(contents) = fs::read_to_string(markdown)
2789        && !contents.contains("```")
2790    {
2791        return true;
2792    }
2793
2794    builder.do_if_verbose(|| println!("doc tests for: {}", markdown.display()));
2795    let mut cmd = builder.rustdoc_cmd(compiler);
2796    builder.add_rust_test_threads(&mut cmd);
2797    // allow for unstable options such as new editions
2798    cmd.arg("-Z");
2799    cmd.arg("unstable-options");
2800    cmd.arg("--test");
2801    cmd.arg(markdown);
2802    cmd.env("RUSTC_BOOTSTRAP", "1");
2803
2804    let test_args = builder.config.test_args().join(" ");
2805    cmd.arg("--test-args").arg(test_args);
2806
2807    cmd = cmd.delay_failure();
2808    if !builder.config.verbose_tests {
2809        cmd.run_capture(builder).is_success()
2810    } else {
2811        cmd.run(builder)
2812    }
2813}
2814
2815/// Runs `cargo test` for the compiler crates in `compiler/`.
2816///
2817/// (This step does not test `rustc_codegen_cranelift` or `rustc_codegen_gcc`,
2818/// which have their own separate test steps.)
2819#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2820pub struct CrateLibrustc {
2821    /// The compiler that will run unit tests and doctests on the in-tree rustc source.
2822    build_compiler: Compiler,
2823    target: TargetSelection,
2824    crates: Vec<String>,
2825}
2826
2827impl Step for CrateLibrustc {
2828    type Output = ();
2829    const IS_HOST: bool = true;
2830
2831    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2832        run.crate_or_deps("rustc-main").path("compiler")
2833    }
2834
2835    fn is_default_step(_builder: &Builder<'_>) -> bool {
2836        true
2837    }
2838
2839    fn make_run(run: RunConfig<'_>) {
2840        let builder = run.builder;
2841        let host = run.build_triple();
2842        let build_compiler = builder.compiler(builder.top_stage - 1, host);
2843        let crates = run.make_run_crates(Alias::Compiler);
2844
2845        builder.ensure(CrateLibrustc { build_compiler, target: run.target, crates });
2846    }
2847
2848    fn run(self, builder: &Builder<'_>) {
2849        builder.std(self.build_compiler, self.target);
2850
2851        // To actually run the tests, delegate to a copy of the `Crate` step.
2852        builder.ensure(Crate {
2853            build_compiler: self.build_compiler,
2854            target: self.target,
2855            mode: Mode::Rustc,
2856            crates: self.crates,
2857        });
2858    }
2859
2860    fn metadata(&self) -> Option<StepMetadata> {
2861        Some(StepMetadata::test("CrateLibrustc", self.target).built_by(self.build_compiler))
2862    }
2863}
2864
2865/// Given a `cargo test` subcommand, add the appropriate flags and run it.
2866///
2867/// Returns whether the test succeeded.
2868fn run_cargo_test<'a>(
2869    cargo: builder::Cargo,
2870    libtest_args: &[&str],
2871    crates: &[String],
2872    description: impl Into<Option<&'a str>>,
2873    target: TargetSelection,
2874    builder: &Builder<'_>,
2875) -> bool {
2876    let compiler = cargo.compiler();
2877    let stage = match cargo.mode() {
2878        Mode::Std => compiler.stage,
2879        _ => compiler.stage + 1,
2880    };
2881
2882    let mut cargo = prepare_cargo_test(cargo, libtest_args, crates, target, builder);
2883    let _time = helpers::timeit(builder);
2884
2885    let _group = description.into().and_then(|what| builder.msg_test(what, target, stage));
2886
2887    #[cfg(feature = "build-metrics")]
2888    builder.metrics.begin_test_suite(
2889        build_helper::metrics::TestSuiteMetadata::CargoPackage {
2890            crates: crates.iter().map(|c| c.to_string()).collect(),
2891            target: target.triple.to_string(),
2892            host: compiler.host.triple.to_string(),
2893            stage: compiler.stage,
2894        },
2895        builder,
2896    );
2897    add_flags_and_try_run_tests(builder, &mut cargo)
2898}
2899
2900/// Given a `cargo test` subcommand, pass it the appropriate test flags given a `builder`.
2901fn prepare_cargo_test(
2902    cargo: builder::Cargo,
2903    libtest_args: &[&str],
2904    crates: &[String],
2905    target: TargetSelection,
2906    builder: &Builder<'_>,
2907) -> BootstrapCommand {
2908    let compiler = cargo.compiler();
2909    let mut cargo: BootstrapCommand = cargo.into();
2910
2911    // Propagate `--bless` if it has not already been set/unset
2912    // Any tools that want to use this should bless if `RUSTC_BLESS` is set to
2913    // anything other than `0`.
2914    if builder.config.cmd.bless() && !cargo.get_envs().any(|v| v.0 == "RUSTC_BLESS") {
2915        cargo.env("RUSTC_BLESS", "Gesundheit");
2916    }
2917
2918    // Pass in some standard flags then iterate over the graph we've discovered
2919    // in `cargo metadata` with the maps above and figure out what `-p`
2920    // arguments need to get passed.
2921    if builder.kind == Kind::Test && !builder.fail_fast {
2922        cargo.arg("--no-fail-fast");
2923    }
2924
2925    if builder.config.json_output {
2926        cargo.arg("--message-format=json");
2927    }
2928
2929    match builder.doc_tests {
2930        DocTests::Only => {
2931            cargo.arg("--doc");
2932        }
2933        DocTests::No => {
2934            cargo.args(["--bins", "--examples", "--tests", "--benches"]);
2935        }
2936        DocTests::Yes => {}
2937    }
2938
2939    for krate in crates {
2940        cargo.arg("-p").arg(krate);
2941    }
2942
2943    cargo.arg("--").args(builder.config.test_args()).args(libtest_args);
2944    if !builder.config.verbose_tests {
2945        cargo.arg("--quiet");
2946    }
2947
2948    // The tests are going to run with the *target* libraries, so we need to
2949    // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
2950    //
2951    // Note that to run the compiler we need to run with the *host* libraries,
2952    // but our wrapper scripts arrange for that to be the case anyway.
2953    //
2954    // We skip everything on Miri as then this overwrites the libdir set up
2955    // by `Cargo::new` and that actually makes things go wrong.
2956    if builder.kind != Kind::Miri {
2957        let mut dylib_paths = builder.rustc_lib_paths(compiler);
2958        dylib_paths.push(builder.sysroot_target_libdir(compiler, target));
2959        helpers::add_dylib_path(dylib_paths, &mut cargo);
2960    }
2961
2962    if builder.remote_tested(target) {
2963        cargo.env(
2964            format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2965            format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
2966        );
2967    } else if let Some(tool) = builder.runner(target) {
2968        cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), tool);
2969    }
2970
2971    cargo
2972}
2973
2974/// Runs `cargo test` for standard library crates.
2975///
2976/// (Also used internally to run `cargo test` for compiler crates.)
2977///
2978/// FIXME(Zalathar): Try to split this into two separate steps: a user-visible
2979/// step for testing standard library crates, and an internal step used for both
2980/// library crates and compiler crates.
2981#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2982pub struct Crate {
2983    /// The compiler that will *build* libstd or rustc in test mode.
2984    build_compiler: Compiler,
2985    target: TargetSelection,
2986    mode: Mode,
2987    crates: Vec<String>,
2988}
2989
2990impl Step for Crate {
2991    type Output = ();
2992
2993    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2994        run.crate_or_deps("sysroot").crate_or_deps("coretests").crate_or_deps("alloctests")
2995    }
2996
2997    fn is_default_step(_builder: &Builder<'_>) -> bool {
2998        true
2999    }
3000
3001    fn make_run(run: RunConfig<'_>) {
3002        let builder = run.builder;
3003        let host = run.build_triple();
3004        let build_compiler = builder.compiler(builder.top_stage, host);
3005        let crates = run
3006            .paths
3007            .iter()
3008            .map(|p| builder.crate_paths[&p.assert_single_path().path].clone())
3009            .collect();
3010
3011        builder.ensure(Crate { build_compiler, target: run.target, mode: Mode::Std, crates });
3012    }
3013
3014    /// Runs all unit tests plus documentation tests for a given crate defined
3015    /// by a `Cargo.toml` (single manifest)
3016    ///
3017    /// This is what runs tests for crates like the standard library, compiler, etc.
3018    /// It essentially is the driver for running `cargo test`.
3019    ///
3020    /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
3021    /// arguments, and those arguments are discovered from `cargo metadata`.
3022    fn run(self, builder: &Builder<'_>) {
3023        let build_compiler = self.build_compiler;
3024        let target = self.target;
3025        let mode = self.mode;
3026
3027        // Prepare sysroot
3028        // See [field@compile::Std::force_recompile].
3029        builder.ensure(Std::new(build_compiler, build_compiler.host).force_recompile(true));
3030
3031        let mut cargo = if builder.kind == Kind::Miri {
3032            if builder.top_stage == 0 {
3033                eprintln!("ERROR: `x.py miri` requires stage 1 or higher");
3034                std::process::exit(1);
3035            }
3036
3037            // Build `cargo miri test` command
3038            // (Implicitly prepares target sysroot)
3039            let mut cargo = builder::Cargo::new(
3040                builder,
3041                build_compiler,
3042                mode,
3043                SourceType::InTree,
3044                target,
3045                Kind::MiriTest,
3046            );
3047            // This hack helps bootstrap run standard library tests in Miri. The issue is as
3048            // follows: when running `cargo miri test` on libcore, cargo builds a local copy of core
3049            // and makes it a dependency of the integration test crate. This copy duplicates all the
3050            // lang items, so the build fails. (Regular testing avoids this because the sysroot is a
3051            // literal copy of what `cargo build` produces, but since Miri builds its own sysroot
3052            // this does not work for us.) So we need to make it so that the locally built libcore
3053            // contains all the items from `core`, but does not re-define them -- we want to replace
3054            // the entire crate but a re-export of the sysroot crate. We do this by swapping out the
3055            // source file: if `MIRI_REPLACE_LIBRS_IF_NOT_TEST` is set and we are building a
3056            // `lib.rs` file, and a `lib.miri.rs` file exists in the same folder, we build that
3057            // instead. But crucially we only do that for the library, not the test builds.
3058            cargo.env("MIRI_REPLACE_LIBRS_IF_NOT_TEST", "1");
3059            // std needs to be built with `-Zforce-unstable-if-unmarked`. For some reason the builder
3060            // does not set this directly, but relies on the rustc wrapper to set it, and we are not using
3061            // the wrapper -- hence we have to set it ourselves.
3062            cargo.rustflag("-Zforce-unstable-if-unmarked");
3063            cargo
3064        } else {
3065            // Also prepare a sysroot for the target.
3066            if !builder.config.is_host_target(target) {
3067                builder.ensure(compile::Std::new(build_compiler, target).force_recompile(true));
3068                builder.ensure(RemoteCopyLibs { build_compiler, target });
3069            }
3070
3071            // Build `cargo test` command
3072            builder::Cargo::new(
3073                builder,
3074                build_compiler,
3075                mode,
3076                SourceType::InTree,
3077                target,
3078                builder.kind,
3079            )
3080        };
3081
3082        match mode {
3083            Mode::Std => {
3084                if builder.kind == Kind::Miri {
3085                    // We can't use `std_cargo` as that uses `optimized-compiler-builtins` which
3086                    // needs host tools for the given target. This is similar to what `compile::Std`
3087                    // does when `is_for_mir_opt_tests` is true. There's probably a chance for
3088                    // de-duplication here... `std_cargo` should support a mode that avoids needing
3089                    // host tools.
3090                    cargo
3091                        .arg("--manifest-path")
3092                        .arg(builder.src.join("library/sysroot/Cargo.toml"));
3093                } else {
3094                    compile::std_cargo(builder, target, &mut cargo, &[]);
3095                }
3096            }
3097            Mode::Rustc => {
3098                compile::rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
3099            }
3100            _ => panic!("can only test libraries"),
3101        };
3102
3103        let mut crates = self.crates.clone();
3104        // The core and alloc crates can't directly be tested. We
3105        // could silently ignore them, but adding their own test
3106        // crates is less confusing for users. We still keep core and
3107        // alloc themself for doctests
3108        if crates.iter().any(|crate_| crate_ == "core") {
3109            crates.push("coretests".to_owned());
3110        }
3111        if crates.iter().any(|crate_| crate_ == "alloc") {
3112            crates.push("alloctests".to_owned());
3113        }
3114
3115        run_cargo_test(cargo, &[], &crates, &*crate_description(&self.crates), target, builder);
3116    }
3117}
3118
3119/// Run cargo tests for the rustdoc crate.
3120/// Rustdoc is special in various ways, which is why this step is different from `Crate`.
3121#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3122pub struct CrateRustdoc {
3123    host: TargetSelection,
3124}
3125
3126impl Step for CrateRustdoc {
3127    type Output = ();
3128    const IS_HOST: bool = true;
3129
3130    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3131        run.paths(&["src/librustdoc", "src/tools/rustdoc"])
3132    }
3133
3134    fn is_default_step(_builder: &Builder<'_>) -> bool {
3135        true
3136    }
3137
3138    fn make_run(run: RunConfig<'_>) {
3139        let builder = run.builder;
3140
3141        builder.ensure(CrateRustdoc { host: run.target });
3142    }
3143
3144    fn run(self, builder: &Builder<'_>) {
3145        let target = self.host;
3146
3147        let compiler = if builder.download_rustc() {
3148            builder.compiler(builder.top_stage, target)
3149        } else {
3150            // Use the previous stage compiler to reuse the artifacts that are
3151            // created when running compiletest for tests/rustdoc. If this used
3152            // `compiler`, then it would cause rustdoc to be built *again*, which
3153            // isn't really necessary.
3154            builder.compiler_for(builder.top_stage, target, target)
3155        };
3156        // NOTE: normally `ensure(Rustc)` automatically runs `ensure(Std)` for us. However, when
3157        // using `download-rustc`, the rustc_private artifacts may be in a *different sysroot* from
3158        // the target rustdoc (`ci-rustc-sysroot` vs `stage2`). In that case, we need to ensure this
3159        // explicitly to make sure it ends up in the stage2 sysroot.
3160        builder.std(compiler, target);
3161        builder.ensure(compile::Rustc::new(compiler, target));
3162
3163        let mut cargo = tool::prepare_tool_cargo(
3164            builder,
3165            compiler,
3166            Mode::ToolRustcPrivate,
3167            target,
3168            builder.kind,
3169            "src/tools/rustdoc",
3170            SourceType::InTree,
3171            &[],
3172        );
3173        if self.host.contains("musl") {
3174            cargo.arg("'-Ctarget-feature=-crt-static'");
3175        }
3176
3177        // This is needed for running doctests on librustdoc. This is a bit of
3178        // an unfortunate interaction with how bootstrap works and how cargo
3179        // sets up the dylib path, and the fact that the doctest (in
3180        // html/markdown.rs) links to rustc-private libs. For stage1, the
3181        // compiler host dylibs (in stage1/lib) are not the same as the target
3182        // dylibs (in stage1/lib/rustlib/...). This is different from a normal
3183        // rust distribution where they are the same.
3184        //
3185        // On the cargo side, normal tests use `target_process` which handles
3186        // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
3187        // case). However, for doctests it uses `rustdoc_process` which only
3188        // sets up the dylib path for the *host* (stage1/lib), which is the
3189        // wrong directory.
3190        //
3191        // Recall that we special-cased `compiler_for(top_stage)` above, so we always use stage1.
3192        //
3193        // It should be considered to just stop running doctests on
3194        // librustdoc. There is only one test, and it doesn't look too
3195        // important. There might be other ways to avoid this, but it seems
3196        // pretty convoluted.
3197        //
3198        // See also https://github.com/rust-lang/rust/issues/13983 where the
3199        // host vs target dylibs for rustdoc are consistently tricky to deal
3200        // with.
3201        //
3202        // Note that this set the host libdir for `download_rustc`, which uses a normal rust distribution.
3203        let libdir = if builder.download_rustc() {
3204            builder.rustc_libdir(compiler)
3205        } else {
3206            builder.sysroot_target_libdir(compiler, target).to_path_buf()
3207        };
3208        let mut dylib_path = dylib_path();
3209        dylib_path.insert(0, PathBuf::from(&*libdir));
3210        cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
3211
3212        run_cargo_test(cargo, &[], &["rustdoc:0.0.0".to_string()], "rustdoc", target, builder);
3213    }
3214}
3215
3216#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3217pub struct CrateRustdocJsonTypes {
3218    build_compiler: Compiler,
3219    target: TargetSelection,
3220}
3221
3222impl Step for CrateRustdocJsonTypes {
3223    type Output = ();
3224    const IS_HOST: bool = true;
3225
3226    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3227        run.path("src/rustdoc-json-types")
3228    }
3229
3230    fn is_default_step(_builder: &Builder<'_>) -> bool {
3231        true
3232    }
3233
3234    fn make_run(run: RunConfig<'_>) {
3235        let builder = run.builder;
3236
3237        builder.ensure(CrateRustdocJsonTypes {
3238            build_compiler: get_tool_target_compiler(
3239                builder,
3240                ToolTargetBuildMode::Build(run.target),
3241            ),
3242            target: run.target,
3243        });
3244    }
3245
3246    fn run(self, builder: &Builder<'_>) {
3247        let target = self.target;
3248
3249        let cargo = tool::prepare_tool_cargo(
3250            builder,
3251            self.build_compiler,
3252            Mode::ToolTarget,
3253            target,
3254            builder.kind,
3255            "src/rustdoc-json-types",
3256            SourceType::InTree,
3257            &[],
3258        );
3259
3260        // FIXME: this looks very wrong, libtest doesn't accept `-C` arguments and the quotes are fishy.
3261        let libtest_args = if target.contains("musl") {
3262            ["'-Ctarget-feature=-crt-static'"].as_slice()
3263        } else {
3264            &[]
3265        };
3266
3267        run_cargo_test(
3268            cargo,
3269            libtest_args,
3270            &["rustdoc-json-types".to_string()],
3271            "rustdoc-json-types",
3272            target,
3273            builder,
3274        );
3275    }
3276}
3277
3278/// Some test suites are run inside emulators or on remote devices, and most
3279/// of our test binaries are linked dynamically which means we need to ship
3280/// the standard library and such to the emulator ahead of time. This step
3281/// represents this and is a dependency of all test suites.
3282///
3283/// Most of the time this is a no-op. For some steps such as shipping data to
3284/// QEMU we have to build our own tools so we've got conditional dependencies
3285/// on those programs as well. Note that the remote test client is built for
3286/// the build target (us) and the server is built for the target.
3287#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3288pub struct RemoteCopyLibs {
3289    build_compiler: Compiler,
3290    target: TargetSelection,
3291}
3292
3293impl Step for RemoteCopyLibs {
3294    type Output = ();
3295
3296    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3297        run.never()
3298    }
3299
3300    fn run(self, builder: &Builder<'_>) {
3301        let build_compiler = self.build_compiler;
3302        let target = self.target;
3303        if !builder.remote_tested(target) {
3304            return;
3305        }
3306
3307        builder.std(build_compiler, target);
3308
3309        builder.info(&format!("REMOTE copy libs to emulator ({target})"));
3310
3311        let remote_test_server = builder.ensure(tool::RemoteTestServer { build_compiler, target });
3312
3313        // Spawn the emulator and wait for it to come online
3314        let tool = builder.tool_exe(Tool::RemoteTestClient);
3315        let mut cmd = command(&tool);
3316        cmd.arg("spawn-emulator")
3317            .arg(target.triple)
3318            .arg(&remote_test_server.tool_path)
3319            .arg(builder.tempdir());
3320        if let Some(rootfs) = builder.qemu_rootfs(target) {
3321            cmd.arg(rootfs);
3322        }
3323        cmd.run(builder);
3324
3325        // Push all our dylibs to the emulator
3326        for f in t!(builder.sysroot_target_libdir(build_compiler, target).read_dir()) {
3327            let f = t!(f);
3328            if helpers::is_dylib(&f.path()) {
3329                command(&tool).arg("push").arg(f.path()).run(builder);
3330            }
3331        }
3332    }
3333}
3334
3335#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3336pub struct Distcheck;
3337
3338impl Step for Distcheck {
3339    type Output = ();
3340
3341    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3342        run.alias("distcheck")
3343    }
3344
3345    fn make_run(run: RunConfig<'_>) {
3346        run.builder.ensure(Distcheck);
3347    }
3348
3349    /// Runs `distcheck`, which is a collection of smoke tests:
3350    ///
3351    /// - Run `make check` from an unpacked dist tarball to make sure we can at the minimum run
3352    ///   check steps from those sources.
3353    /// - Check that selected dist components (`rust-src` only at the moment) at least have expected
3354    ///   directory shape and crate manifests that cargo can generate a lockfile from.
3355    /// - Check that we can run `cargo metadata` on the workspace in the `rustc-dev` component
3356    ///
3357    /// FIXME(#136822): dist components are under-tested.
3358    fn run(self, builder: &Builder<'_>) {
3359        // Use a temporary directory completely outside the current checkout, to avoid reusing any
3360        // local source code, built artifacts or configuration by accident
3361        let root_dir = std::env::temp_dir().join("distcheck");
3362
3363        distcheck_plain_source_tarball(builder, &root_dir.join("distcheck-rustc-src"));
3364        distcheck_rust_src(builder, &root_dir.join("distcheck-rust-src"));
3365        distcheck_rustc_dev(builder, &root_dir.join("distcheck-rustc-dev"));
3366    }
3367}
3368
3369/// Check that we can build some basic things from the plain source tarball
3370fn distcheck_plain_source_tarball(builder: &Builder<'_>, plain_src_dir: &Path) {
3371    builder.info("Distcheck plain source tarball");
3372    let plain_src_tarball = builder.ensure(dist::PlainSourceTarball);
3373    builder.clear_dir(plain_src_dir);
3374
3375    let configure_args: Vec<String> = std::env::var("DISTCHECK_CONFIGURE_ARGS")
3376        .map(|args| args.split(" ").map(|s| s.to_string()).collect::<Vec<String>>())
3377        .unwrap_or_default();
3378
3379    command("tar")
3380        .arg("-xf")
3381        .arg(plain_src_tarball.tarball())
3382        .arg("--strip-components=1")
3383        .current_dir(plain_src_dir)
3384        .run(builder);
3385    command("./configure")
3386        .arg("--set")
3387        .arg("rust.omit-git-hash=false")
3388        .args(&configure_args)
3389        .arg("--enable-vendor")
3390        .current_dir(plain_src_dir)
3391        .run(builder);
3392    command(helpers::make(&builder.config.host_target.triple))
3393        .arg("check")
3394        // Do not run the build as if we were in CI, otherwise git would be assumed to be
3395        // present, but we build from a tarball here
3396        .env("GITHUB_ACTIONS", "0")
3397        .current_dir(plain_src_dir)
3398        .run(builder);
3399    // Mitigate pressure on small-capacity disks.
3400    builder.remove_dir(plain_src_dir);
3401}
3402
3403/// Check that rust-src has all of libstd's dependencies
3404fn distcheck_rust_src(builder: &Builder<'_>, src_dir: &Path) {
3405    builder.info("Distcheck rust-src");
3406    let src_tarball = builder.ensure(dist::Src);
3407    builder.clear_dir(src_dir);
3408
3409    command("tar")
3410        .arg("-xf")
3411        .arg(src_tarball.tarball())
3412        .arg("--strip-components=1")
3413        .current_dir(src_dir)
3414        .run(builder);
3415
3416    let toml = src_dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
3417    command(&builder.initial_cargo)
3418        // Will read the libstd Cargo.toml
3419        // which uses the unstable `public-dependency` feature.
3420        .env("RUSTC_BOOTSTRAP", "1")
3421        .arg("generate-lockfile")
3422        .arg("--manifest-path")
3423        .arg(&toml)
3424        .current_dir(src_dir)
3425        .run(builder);
3426    // Mitigate pressure on small-capacity disks.
3427    builder.remove_dir(src_dir);
3428}
3429
3430/// Check that rustc-dev's compiler crate source code can be loaded with `cargo metadata`
3431fn distcheck_rustc_dev(builder: &Builder<'_>, dir: &Path) {
3432    builder.info("Distcheck rustc-dev");
3433    let tarball = builder.ensure(dist::RustcDev::new(builder, builder.host_target)).unwrap();
3434    builder.clear_dir(dir);
3435
3436    command("tar")
3437        .arg("-xf")
3438        .arg(tarball.tarball())
3439        .arg("--strip-components=1")
3440        .current_dir(dir)
3441        .run(builder);
3442
3443    command(&builder.initial_cargo)
3444        .arg("metadata")
3445        .arg("--manifest-path")
3446        .arg("rustc-dev/lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml")
3447        .env("RUSTC_BOOTSTRAP", "1")
3448        // We might not have a globally available `rustc` binary on CI
3449        .env("RUSTC", &builder.initial_rustc)
3450        .current_dir(dir)
3451        .run(builder);
3452    // Mitigate pressure on small-capacity disks.
3453    builder.remove_dir(dir);
3454}
3455
3456/// Runs unit tests in `bootstrap_test.py`, which test the Python parts of bootstrap.
3457#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3458pub(crate) struct BootstrapPy;
3459
3460impl Step for BootstrapPy {
3461    type Output = ();
3462    const IS_HOST: bool = true;
3463
3464    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3465        run.alias("bootstrap-py")
3466    }
3467
3468    fn is_default_step(builder: &Builder<'_>) -> bool {
3469        // Bootstrap tests might not be perfectly self-contained and can depend
3470        // on the environment, so only run them by default in CI, not locally.
3471        // See `test::Bootstrap::should_run`.
3472        builder.config.is_running_on_ci
3473    }
3474
3475    fn make_run(run: RunConfig<'_>) {
3476        run.builder.ensure(BootstrapPy)
3477    }
3478
3479    fn run(self, builder: &Builder<'_>) -> Self::Output {
3480        let mut check_bootstrap = command(
3481            builder.config.python.as_ref().expect("python is required for running bootstrap tests"),
3482        );
3483        check_bootstrap
3484            .args(["-m", "unittest", "bootstrap_test.py"])
3485            // Forward command-line args after `--` to unittest, for filtering etc.
3486            .args(builder.config.test_args())
3487            .env("BUILD_DIR", &builder.out)
3488            .env("BUILD_PLATFORM", builder.build.host_target.triple)
3489            .env("BOOTSTRAP_TEST_RUSTC_BIN", &builder.initial_rustc)
3490            .env("BOOTSTRAP_TEST_CARGO_BIN", &builder.initial_cargo)
3491            .current_dir(builder.src.join("src/bootstrap/"));
3492        check_bootstrap.delay_failure().run(builder);
3493    }
3494}
3495
3496#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3497pub struct Bootstrap;
3498
3499impl Step for Bootstrap {
3500    type Output = ();
3501    const IS_HOST: bool = true;
3502
3503    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3504        run.path("src/bootstrap")
3505    }
3506
3507    fn is_default_step(builder: &Builder<'_>) -> bool {
3508        // Bootstrap tests might not be perfectly self-contained and can depend on the external
3509        // environment, submodules that are checked out, etc.
3510        // Therefore we only run them by default on CI.
3511        builder.config.is_running_on_ci
3512    }
3513
3514    /// Tests the build system itself.
3515    fn run(self, builder: &Builder<'_>) {
3516        let host = builder.config.host_target;
3517        let build_compiler = builder.compiler(0, host);
3518
3519        // Some tests require cargo submodule to be present.
3520        builder.build.require_submodule("src/tools/cargo", None);
3521
3522        let mut cargo = tool::prepare_tool_cargo(
3523            builder,
3524            build_compiler,
3525            Mode::ToolBootstrap,
3526            host,
3527            Kind::Test,
3528            "src/bootstrap",
3529            SourceType::InTree,
3530            &[],
3531        );
3532
3533        cargo.release_build(false);
3534
3535        cargo
3536            .rustflag("-Cdebuginfo=2")
3537            .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
3538            // Needed for insta to correctly write pending snapshots to the right directories.
3539            .env("INSTA_WORKSPACE_ROOT", &builder.src)
3540            .env("RUSTC_BOOTSTRAP", "1");
3541
3542        if builder.config.cmd.bless() {
3543            // Tell `insta` to automatically bless any failing `.snap` files.
3544            // Unlike compiletest blessing, the tests might still report failure.
3545            // Does not bless inline snapshots.
3546            cargo.env("INSTA_UPDATE", "always");
3547        }
3548
3549        run_cargo_test(cargo, &[], &[], None, host, builder);
3550    }
3551
3552    fn make_run(run: RunConfig<'_>) {
3553        run.builder.ensure(Bootstrap);
3554    }
3555}
3556
3557fn get_compiler_to_test(builder: &Builder<'_>, target: TargetSelection) -> Compiler {
3558    builder.compiler(builder.top_stage, target)
3559}
3560
3561/// Tests the Platform Support page in the rustc book.
3562/// `test_compiler` is used to query the actual targets that are checked.
3563#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3564pub struct TierCheck {
3565    test_compiler: Compiler,
3566}
3567
3568impl Step for TierCheck {
3569    type Output = ();
3570    const IS_HOST: bool = true;
3571
3572    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3573        run.path("src/tools/tier-check")
3574    }
3575
3576    fn is_default_step(_builder: &Builder<'_>) -> bool {
3577        true
3578    }
3579
3580    fn make_run(run: RunConfig<'_>) {
3581        run.builder
3582            .ensure(TierCheck { test_compiler: get_compiler_to_test(run.builder, run.target) });
3583    }
3584
3585    fn run(self, builder: &Builder<'_>) {
3586        let tool_build_compiler = builder.compiler(0, builder.host_target);
3587
3588        let mut cargo = tool::prepare_tool_cargo(
3589            builder,
3590            tool_build_compiler,
3591            Mode::ToolBootstrap,
3592            tool_build_compiler.host,
3593            Kind::Run,
3594            "src/tools/tier-check",
3595            SourceType::InTree,
3596            &[],
3597        );
3598        cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
3599        cargo.arg(builder.rustc(self.test_compiler));
3600
3601        let _guard = builder.msg_test(
3602            "platform support check",
3603            self.test_compiler.host,
3604            self.test_compiler.stage,
3605        );
3606        BootstrapCommand::from(cargo).delay_failure().run(builder);
3607    }
3608
3609    fn metadata(&self) -> Option<StepMetadata> {
3610        Some(StepMetadata::test("tier-check", self.test_compiler.host))
3611    }
3612}
3613
3614#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3615pub struct LintDocs {
3616    build_compiler: Compiler,
3617    target: TargetSelection,
3618}
3619
3620impl Step for LintDocs {
3621    type Output = ();
3622    const IS_HOST: bool = true;
3623
3624    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3625        run.path("src/tools/lint-docs")
3626    }
3627
3628    fn is_default_step(builder: &Builder<'_>) -> bool {
3629        // Lint docs tests might not work with stage 1, so do not run this test by default in
3630        // `x test` below stage 2.
3631        builder.top_stage >= 2
3632    }
3633
3634    fn make_run(run: RunConfig<'_>) {
3635        if run.builder.top_stage < 2 {
3636            eprintln!("WARNING: lint-docs tests might not work below stage 2");
3637        }
3638
3639        run.builder.ensure(LintDocs {
3640            build_compiler: prepare_doc_compiler(
3641                run.builder,
3642                run.builder.config.host_target,
3643                run.builder.top_stage,
3644            ),
3645            target: run.target,
3646        });
3647    }
3648
3649    /// Tests that the lint examples in the rustc book generate the correct
3650    /// lints and have the expected format.
3651    fn run(self, builder: &Builder<'_>) {
3652        builder.ensure(crate::core::build_steps::doc::RustcBook::validate(
3653            self.build_compiler,
3654            self.target,
3655        ));
3656    }
3657
3658    fn metadata(&self) -> Option<StepMetadata> {
3659        Some(StepMetadata::test("lint-docs", self.target).built_by(self.build_compiler))
3660    }
3661}
3662
3663#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3664pub struct RustInstaller;
3665
3666impl Step for RustInstaller {
3667    type Output = ();
3668    const IS_HOST: bool = true;
3669
3670    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3671        run.path("src/tools/rust-installer")
3672    }
3673
3674    fn is_default_step(_builder: &Builder<'_>) -> bool {
3675        true
3676    }
3677
3678    fn make_run(run: RunConfig<'_>) {
3679        run.builder.ensure(Self);
3680    }
3681
3682    /// Ensure the version placeholder replacement tool builds
3683    fn run(self, builder: &Builder<'_>) {
3684        let bootstrap_host = builder.config.host_target;
3685        let build_compiler = builder.compiler(0, bootstrap_host);
3686        let cargo = tool::prepare_tool_cargo(
3687            builder,
3688            build_compiler,
3689            Mode::ToolBootstrap,
3690            bootstrap_host,
3691            Kind::Test,
3692            "src/tools/rust-installer",
3693            SourceType::InTree,
3694            &[],
3695        );
3696
3697        let _guard = builder.msg_test("rust-installer", bootstrap_host, 1);
3698        run_cargo_test(cargo, &[], &[], None, bootstrap_host, builder);
3699
3700        // We currently don't support running the test.sh script outside linux(?) environments.
3701        // Eventually this should likely migrate to #[test]s in rust-installer proper rather than a
3702        // set of scripts, which will likely allow dropping this if.
3703        if bootstrap_host != "x86_64-unknown-linux-gnu" {
3704            return;
3705        }
3706
3707        let mut cmd = command(builder.src.join("src/tools/rust-installer/test.sh"));
3708        let tmpdir = testdir(builder, build_compiler.host).join("rust-installer");
3709        let _ = std::fs::remove_dir_all(&tmpdir);
3710        let _ = std::fs::create_dir_all(&tmpdir);
3711        cmd.current_dir(&tmpdir);
3712        cmd.env("CARGO_TARGET_DIR", tmpdir.join("cargo-target"));
3713        cmd.env("CARGO", &builder.initial_cargo);
3714        cmd.env("RUSTC", &builder.initial_rustc);
3715        cmd.env("TMP_DIR", &tmpdir);
3716        cmd.delay_failure().run(builder);
3717    }
3718}
3719
3720#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3721pub struct TestHelpers {
3722    pub target: TargetSelection,
3723}
3724
3725impl Step for TestHelpers {
3726    type Output = ();
3727
3728    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3729        run.path("tests/auxiliary/rust_test_helpers.c")
3730    }
3731
3732    fn make_run(run: RunConfig<'_>) {
3733        run.builder.ensure(TestHelpers { target: run.target })
3734    }
3735
3736    /// Compiles the `rust_test_helpers.c` library which we used in various
3737    /// `run-pass` tests for ABI testing.
3738    fn run(self, builder: &Builder<'_>) {
3739        if builder.config.dry_run() {
3740            return;
3741        }
3742        // The x86_64-fortanix-unknown-sgx target doesn't have a working C
3743        // toolchain. However, some x86_64 ELF objects can be linked
3744        // without issues. Use this hack to compile the test helpers.
3745        let target = if self.target == "x86_64-fortanix-unknown-sgx" {
3746            TargetSelection::from_user("x86_64-unknown-linux-gnu")
3747        } else {
3748            self.target
3749        };
3750        let dst = builder.test_helpers_out(target);
3751        let src = builder.src.join("tests/auxiliary/rust_test_helpers.c");
3752        if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
3753            return;
3754        }
3755
3756        let _guard = builder.msg_unstaged(Kind::Build, "test helpers", target);
3757        t!(fs::create_dir_all(&dst));
3758        let mut cfg = cc::Build::new();
3759
3760        // We may have found various cross-compilers a little differently due to our
3761        // extra configuration, so inform cc of these compilers. Note, though, that
3762        // on MSVC we still need cc's detection of env vars (ugh).
3763        if !target.is_msvc() {
3764            if let Some(ar) = builder.ar(target) {
3765                cfg.archiver(ar);
3766            }
3767            cfg.compiler(builder.cc(target));
3768        }
3769        cfg.cargo_metadata(false)
3770            .out_dir(&dst)
3771            .target(&target.triple)
3772            .host(&builder.config.host_target.triple)
3773            .opt_level(0)
3774            .warnings(false)
3775            .debug(false)
3776            .file(builder.src.join("tests/auxiliary/rust_test_helpers.c"))
3777            .compile("rust_test_helpers");
3778    }
3779}
3780
3781#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3782pub struct CodegenCranelift {
3783    compilers: RustcPrivateCompilers,
3784    target: TargetSelection,
3785}
3786
3787impl Step for CodegenCranelift {
3788    type Output = ();
3789    const IS_HOST: bool = true;
3790
3791    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3792        run.paths(&["compiler/rustc_codegen_cranelift"])
3793    }
3794
3795    fn is_default_step(_builder: &Builder<'_>) -> bool {
3796        true
3797    }
3798
3799    fn make_run(run: RunConfig<'_>) {
3800        let builder = run.builder;
3801        let host = run.build_triple();
3802        let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, host);
3803
3804        if builder.doc_tests == DocTests::Only {
3805            return;
3806        }
3807
3808        if builder.download_rustc() {
3809            builder.info("CI rustc uses the default codegen backend. skipping");
3810            return;
3811        }
3812
3813        if !target_supports_cranelift_backend(run.target) {
3814            builder.info("target not supported by rustc_codegen_cranelift. skipping");
3815            return;
3816        }
3817
3818        if builder.remote_tested(run.target) {
3819            builder.info("remote testing is not supported by rustc_codegen_cranelift. skipping");
3820            return;
3821        }
3822
3823        if !builder
3824            .config
3825            .enabled_codegen_backends(run.target)
3826            .contains(&CodegenBackendKind::Cranelift)
3827        {
3828            builder.info("cranelift not in rust.codegen-backends. skipping");
3829            return;
3830        }
3831
3832        builder.ensure(CodegenCranelift { compilers, target: run.target });
3833    }
3834
3835    fn run(self, builder: &Builder<'_>) {
3836        let compilers = self.compilers;
3837        let build_compiler = compilers.build_compiler();
3838
3839        // We need to run the cranelift tests with the compiler against cranelift links to, not with
3840        // the build compiler.
3841        let target_compiler = compilers.target_compiler();
3842        let target = self.target;
3843
3844        builder.std(target_compiler, target);
3845
3846        let mut cargo = builder::Cargo::new(
3847            builder,
3848            target_compiler,
3849            Mode::Codegen, // Must be codegen to ensure dlopen on compiled dylibs works
3850            SourceType::InTree,
3851            target,
3852            Kind::Run,
3853        );
3854
3855        cargo.current_dir(&builder.src.join("compiler/rustc_codegen_cranelift"));
3856        cargo
3857            .arg("--manifest-path")
3858            .arg(builder.src.join("compiler/rustc_codegen_cranelift/build_system/Cargo.toml"));
3859        compile::rustc_cargo_env(builder, &mut cargo, target);
3860
3861        // Avoid incremental cache issues when changing rustc
3862        cargo.env("CARGO_BUILD_INCREMENTAL", "false");
3863
3864        let _guard = builder.msg_test(
3865            "rustc_codegen_cranelift",
3866            target_compiler.host,
3867            target_compiler.stage,
3868        );
3869
3870        // FIXME handle vendoring for source tarballs before removing the --skip-test below
3871        let download_dir = builder.out.join("cg_clif_download");
3872
3873        cargo
3874            .arg("--")
3875            .arg("test")
3876            .arg("--download-dir")
3877            .arg(&download_dir)
3878            .arg("--out-dir")
3879            .arg(builder.stage_out(build_compiler, Mode::Codegen).join("cg_clif"))
3880            .arg("--no-unstable-features")
3881            .arg("--use-backend")
3882            .arg("cranelift")
3883            // Avoid having to vendor the standard library dependencies
3884            .arg("--sysroot")
3885            .arg("llvm")
3886            // These tests depend on crates that are not yet vendored
3887            // FIXME remove once vendoring is handled
3888            .arg("--skip-test")
3889            .arg("testsuite.extended_sysroot");
3890
3891        cargo.into_cmd().run(builder);
3892    }
3893
3894    fn metadata(&self) -> Option<StepMetadata> {
3895        Some(
3896            StepMetadata::test("rustc_codegen_cranelift", self.target)
3897                .built_by(self.compilers.build_compiler()),
3898        )
3899    }
3900}
3901
3902#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3903pub struct CodegenGCC {
3904    compilers: RustcPrivateCompilers,
3905    target: TargetSelection,
3906}
3907
3908impl Step for CodegenGCC {
3909    type Output = ();
3910    const IS_HOST: bool = true;
3911
3912    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3913        run.paths(&["compiler/rustc_codegen_gcc"])
3914    }
3915
3916    fn is_default_step(_builder: &Builder<'_>) -> bool {
3917        true
3918    }
3919
3920    fn make_run(run: RunConfig<'_>) {
3921        let builder = run.builder;
3922        let host = run.build_triple();
3923        let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, host);
3924
3925        if builder.doc_tests == DocTests::Only {
3926            return;
3927        }
3928
3929        if builder.download_rustc() {
3930            builder.info("CI rustc uses the default codegen backend. skipping");
3931            return;
3932        }
3933
3934        let triple = run.target.triple;
3935        let target_supported =
3936            if triple.contains("linux") { triple.contains("x86_64") } else { false };
3937        if !target_supported {
3938            builder.info("target not supported by rustc_codegen_gcc. skipping");
3939            return;
3940        }
3941
3942        if builder.remote_tested(run.target) {
3943            builder.info("remote testing is not supported by rustc_codegen_gcc. skipping");
3944            return;
3945        }
3946
3947        if !builder.config.enabled_codegen_backends(run.target).contains(&CodegenBackendKind::Gcc) {
3948            builder.info("gcc not in rust.codegen-backends. skipping");
3949            return;
3950        }
3951
3952        builder.ensure(CodegenGCC { compilers, target: run.target });
3953    }
3954
3955    fn run(self, builder: &Builder<'_>) {
3956        let compilers = self.compilers;
3957        let target = self.target;
3958
3959        let gcc = builder.ensure(Gcc { target });
3960
3961        builder.ensure(
3962            compile::Std::new(compilers.build_compiler(), target)
3963                .extra_rust_args(&["-Csymbol-mangling-version=v0", "-Cpanic=abort"]),
3964        );
3965
3966        let _guard = builder.msg_test(
3967            "rustc_codegen_gcc",
3968            compilers.target(),
3969            compilers.target_compiler().stage,
3970        );
3971
3972        let mut cargo = builder::Cargo::new(
3973            builder,
3974            compilers.build_compiler(),
3975            Mode::Codegen, // Must be codegen to ensure dlopen on compiled dylibs works
3976            SourceType::InTree,
3977            target,
3978            Kind::Run,
3979        );
3980
3981        cargo.current_dir(&builder.src.join("compiler/rustc_codegen_gcc"));
3982        cargo
3983            .arg("--manifest-path")
3984            .arg(builder.src.join("compiler/rustc_codegen_gcc/build_system/Cargo.toml"));
3985        compile::rustc_cargo_env(builder, &mut cargo, target);
3986        add_cg_gcc_cargo_flags(&mut cargo, &gcc);
3987
3988        // Avoid incremental cache issues when changing rustc
3989        cargo.env("CARGO_BUILD_INCREMENTAL", "false");
3990        cargo.rustflag("-Cpanic=abort");
3991
3992        cargo
3993            // cg_gcc's build system ignores RUSTFLAGS. pass some flags through CG_RUSTFLAGS instead.
3994            .env("CG_RUSTFLAGS", "-Alinker-messages")
3995            .arg("--")
3996            .arg("test")
3997            .arg("--use-backend")
3998            .arg("gcc")
3999            .arg("--gcc-path")
4000            .arg(gcc.libgccjit.parent().unwrap())
4001            .arg("--out-dir")
4002            .arg(builder.stage_out(compilers.build_compiler(), Mode::Codegen).join("cg_gcc"))
4003            .arg("--release")
4004            .arg("--mini-tests")
4005            .arg("--std-tests");
4006        cargo.args(builder.config.test_args());
4007
4008        cargo.into_cmd().run(builder);
4009    }
4010
4011    fn metadata(&self) -> Option<StepMetadata> {
4012        Some(
4013            StepMetadata::test("rustc_codegen_gcc", self.target)
4014                .built_by(self.compilers.build_compiler()),
4015        )
4016    }
4017}
4018
4019/// Test step that does two things:
4020/// - Runs `cargo test` for the `src/tools/test-float-parse` tool.
4021/// - Invokes the `test-float-parse` tool to test the standard library's
4022///   float parsing routines.
4023#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4024pub struct TestFloatParse {
4025    /// The build compiler which will build and run unit tests of `test-float-parse`, and which will
4026    /// build the `test-float-parse` tool itself.
4027    ///
4028    /// Note that the staging is a bit funny here, because this step essentially tests std, but it
4029    /// also needs to build the tool. So if we test stage1 std, we build:
4030    /// 1) stage1 rustc
4031    /// 2) Use that to build stage1 libstd
4032    /// 3) Use that to build and run *stage2* test-float-parse
4033    build_compiler: Compiler,
4034    /// Target for which we build std and test that std.
4035    target: TargetSelection,
4036}
4037
4038impl Step for TestFloatParse {
4039    type Output = ();
4040    const IS_HOST: bool = true;
4041
4042    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
4043        run.path("src/tools/test-float-parse")
4044    }
4045
4046    fn is_default_step(_builder: &Builder<'_>) -> bool {
4047        true
4048    }
4049
4050    fn make_run(run: RunConfig<'_>) {
4051        run.builder.ensure(Self {
4052            build_compiler: get_compiler_to_test(run.builder, run.target),
4053            target: run.target,
4054        });
4055    }
4056
4057    fn run(self, builder: &Builder<'_>) {
4058        let build_compiler = self.build_compiler;
4059        let target = self.target;
4060
4061        // Build the standard library that will be tested, and a stdlib for host code
4062        builder.std(build_compiler, target);
4063        builder.std(build_compiler, builder.host_target);
4064
4065        // Run any unit tests in the crate
4066        let mut cargo_test = tool::prepare_tool_cargo(
4067            builder,
4068            build_compiler,
4069            Mode::ToolStd,
4070            target,
4071            Kind::Test,
4072            "src/tools/test-float-parse",
4073            SourceType::InTree,
4074            &[],
4075        );
4076        cargo_test.allow_features(TEST_FLOAT_PARSE_ALLOW_FEATURES);
4077
4078        run_cargo_test(cargo_test, &[], &[], "test-float-parse", target, builder);
4079
4080        // Run the actual parse tests.
4081        let mut cargo_run = tool::prepare_tool_cargo(
4082            builder,
4083            build_compiler,
4084            Mode::ToolStd,
4085            target,
4086            Kind::Run,
4087            "src/tools/test-float-parse",
4088            SourceType::InTree,
4089            &[],
4090        );
4091        cargo_run.allow_features(TEST_FLOAT_PARSE_ALLOW_FEATURES);
4092
4093        if !matches!(env::var("FLOAT_PARSE_TESTS_NO_SKIP_HUGE").as_deref(), Ok("1") | Ok("true")) {
4094            cargo_run.args(["--", "--skip-huge"]);
4095        }
4096
4097        cargo_run.into_cmd().run(builder);
4098    }
4099}
4100
4101/// Runs the tool `src/tools/collect-license-metadata` in `ONLY_CHECK=1` mode,
4102/// which verifies that `license-metadata.json` is up-to-date and therefore
4103/// running the tool normally would not update anything.
4104#[derive(Debug, Clone, Hash, PartialEq, Eq)]
4105pub struct CollectLicenseMetadata;
4106
4107impl Step for CollectLicenseMetadata {
4108    type Output = PathBuf;
4109    const IS_HOST: bool = true;
4110
4111    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
4112        run.path("src/tools/collect-license-metadata")
4113    }
4114
4115    fn make_run(run: RunConfig<'_>) {
4116        run.builder.ensure(CollectLicenseMetadata);
4117    }
4118
4119    fn run(self, builder: &Builder<'_>) -> Self::Output {
4120        let Some(reuse) = &builder.config.reuse else {
4121            panic!("REUSE is required to collect the license metadata");
4122        };
4123
4124        let dest = builder.src.join("license-metadata.json");
4125
4126        let mut cmd = builder.tool_cmd(Tool::CollectLicenseMetadata);
4127        cmd.env("REUSE_EXE", reuse);
4128        cmd.env("DEST", &dest);
4129        cmd.env("ONLY_CHECK", "1");
4130        cmd.run(builder);
4131
4132        dest
4133    }
4134}
4135
4136#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4137pub struct RemoteTestClientTests {
4138    host: TargetSelection,
4139}
4140
4141impl Step for RemoteTestClientTests {
4142    type Output = ();
4143    const IS_HOST: bool = true;
4144
4145    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
4146        run.path("src/tools/remote-test-client")
4147    }
4148
4149    fn is_default_step(_builder: &Builder<'_>) -> bool {
4150        true
4151    }
4152
4153    fn make_run(run: RunConfig<'_>) {
4154        run.builder.ensure(Self { host: run.target });
4155    }
4156
4157    fn run(self, builder: &Builder<'_>) {
4158        let bootstrap_host = builder.config.host_target;
4159        let compiler = builder.compiler(0, bootstrap_host);
4160
4161        let cargo = tool::prepare_tool_cargo(
4162            builder,
4163            compiler,
4164            Mode::ToolBootstrap,
4165            bootstrap_host,
4166            Kind::Test,
4167            "src/tools/remote-test-client",
4168            SourceType::InTree,
4169            &[],
4170        );
4171
4172        run_cargo_test(cargo, &[], &[], "remote-test-client", bootstrap_host, builder);
4173    }
4174}