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