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