compiletest/common.rs
1use std::borrow::Cow;
2use std::collections::{BTreeSet, HashMap, HashSet};
3use std::iter;
4use std::process::Command;
5use std::str::FromStr;
6use std::sync::OnceLock;
7
8use build_helper::git::GitConfig;
9use camino::{Utf8Path, Utf8PathBuf};
10use semver::Version;
11
12use crate::debuggers::LldbVersion;
13use crate::edition::Edition;
14use crate::executor::TestVariant;
15use crate::fatal;
16use crate::util::{Utf8PathBufExt, add_dylib_path, string_enum};
17
18string_enum! {
19 #[derive(Clone, Copy, PartialEq, Debug)]
20 pub(crate) enum TestMode {
21 Pretty => "pretty",
22 DebugInfo => "debuginfo",
23 Codegen => "codegen",
24 RustdocHtml => "rustdoc-html",
25 RustdocJson => "rustdoc-json",
26 CodegenUnits => "codegen-units",
27 Incremental => "incremental",
28 RunMake => "run-make",
29 Ui => "ui",
30 RustdocJs => "rustdoc-js",
31 MirOpt => "mir-opt",
32 Assembly => "assembly",
33 CoverageMap => "coverage-map",
34 CoverageRun => "coverage-run",
35 Crashes => "crashes",
36 }
37}
38
39impl TestMode {
40 pub(crate) fn aux_dir_disambiguator(self) -> &'static str {
41 // Pretty-printing tests could run concurrently, and if they do,
42 // they need to keep their output segregated.
43 match self {
44 TestMode::Pretty => ".pretty",
45 _ => "",
46 }
47 }
48
49 pub(crate) fn output_dir_disambiguator(self) -> &'static str {
50 // Coverage tests use the same test files for multiple test modes,
51 // so each mode should have a separate output directory.
52 match self {
53 TestMode::CoverageMap | TestMode::CoverageRun => self.to_str(),
54 _ => "",
55 }
56 }
57}
58
59// Note that coverage tests use the same test files for multiple test modes.
60string_enum! {
61 #[derive(Clone, Copy, PartialEq, Debug)]
62 pub(crate) enum TestSuite {
63 AssemblyGcc => "assembly-gcc",
64 AssemblyLlvm => "assembly-llvm",
65 CodegenLlvm => "codegen-llvm",
66 CodegenUnits => "codegen-units",
67 Coverage => "coverage",
68 CoverageRunRustdoc => "coverage-run-rustdoc",
69 Crashes => "crashes",
70 Debuginfo => "debuginfo",
71 Incremental => "incremental",
72 MirOpt => "mir-opt",
73 Pretty => "pretty",
74 RunMake => "run-make",
75 RunMakeCargo => "run-make-cargo",
76 RustdocHtml => "rustdoc-html",
77 RustdocGui => "rustdoc-gui",
78 RustdocJs => "rustdoc-js",
79 RustdocJsStd=> "rustdoc-js-std",
80 RustdocJson => "rustdoc-json",
81 RustdocUi => "rustdoc-ui",
82 Ui => "ui",
83 UiFullDeps => "ui-fulldeps",
84 BuildStd => "build-std",
85 }
86}
87
88string_enum! {
89 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
90 pub(crate) enum PassFailMode {
91 CheckFail => "check-fail",
92 CheckPass => "check-pass",
93 BuildFail => "build-fail",
94 BuildPass => "build-pass",
95 /// Running the program must make it exit with a regular failure exit code
96 /// in the range `1..=127`. If the program is terminated by e.g. a signal
97 /// the test will fail.
98 RunFail => "run-fail",
99 /// Running the program must result in a crash, e.g. by `SIGABRT` or
100 /// `SIGSEGV` on Unix or on Windows by having an appropriate NTSTATUS high
101 /// bit in the exit code.
102 RunCrash => "run-crash",
103 /// Running the program must either fail or crash. Useful for e.g. sanitizer
104 /// tests since some sanitizer implementations exit the process with code 1
105 /// to in the face of memory errors while others abort (crash) the process
106 /// in the face of memory errors.
107 RunFailOrCrash => "run-fail-or-crash",
108 RunPass => "run-pass",
109 }
110}
111
112impl PassFailMode {
113 pub(crate) fn is_pass(&self) -> bool {
114 match self {
115 PassFailMode::CheckPass | PassFailMode::BuildPass | PassFailMode::RunPass => true,
116
117 PassFailMode::CheckFail
118 | PassFailMode::BuildFail
119 | PassFailMode::RunFail
120 | PassFailMode::RunCrash
121 | PassFailMode::RunFailOrCrash => false,
122 }
123 }
124
125 pub(crate) fn is_check(&self) -> bool {
126 match self {
127 PassFailMode::CheckFail | PassFailMode::CheckPass => true,
128
129 PassFailMode::BuildFail
130 | PassFailMode::BuildPass
131 | PassFailMode::RunFail
132 | PassFailMode::RunCrash
133 | PassFailMode::RunFailOrCrash
134 | PassFailMode::RunPass => false,
135 }
136 }
137
138 pub(crate) fn is_run(&self) -> bool {
139 match self {
140 PassFailMode::CheckFail
141 | PassFailMode::CheckPass
142 | PassFailMode::BuildFail
143 | PassFailMode::BuildPass => false,
144
145 PassFailMode::RunFail
146 | PassFailMode::RunCrash
147 | PassFailMode::RunFailOrCrash
148 | PassFailMode::RunPass => true,
149 }
150 }
151}
152
153string_enum! {
154 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
155 pub(crate) enum ForcePassMode {
156 Check => "check",
157 Build => "build",
158 Run => "run",
159 }
160}
161
162string_enum! {
163 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
164 pub(crate) enum RunResult {
165 Pass => "run-pass",
166 Fail => "run-fail",
167 Crash => "run-crash",
168 }
169}
170
171string_enum! {
172 #[derive(Clone, Debug, PartialEq)]
173 pub(crate) enum CompareMode {
174 Polonius => "polonius",
175 NextSolver => "next-solver",
176 NextSolverCoherence => "next-solver-coherence",
177 SplitDwarf => "split-dwarf",
178 SplitDwarfSingle => "split-dwarf-single",
179 }
180}
181
182string_enum! {
183 #[derive(Clone, Copy, Debug, PartialEq)]
184 pub(crate) enum Debugger {
185 Cdb => "cdb",
186 Gdb => "gdb",
187 Lldb => "lldb",
188 }
189}
190
191#[derive(Clone, Copy, Debug, PartialEq, Default, serde::Deserialize)]
192#[serde(rename_all = "kebab-case")]
193pub(crate) enum PanicStrategy {
194 #[default]
195 Unwind,
196 Abort,
197}
198
199impl PanicStrategy {
200 pub(crate) fn for_miropt_test_tools(&self) -> miropt_test_tools::PanicStrategy {
201 match self {
202 PanicStrategy::Unwind => miropt_test_tools::PanicStrategy::Unwind,
203 PanicStrategy::Abort => miropt_test_tools::PanicStrategy::Abort,
204 }
205 }
206}
207
208#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
209#[serde(rename_all = "kebab-case")]
210pub(crate) enum Sanitizer {
211 Address,
212 Cfi,
213 Dataflow,
214 Kcfi,
215 KernelAddress,
216 KernelHwaddress,
217 Leak,
218 Memory,
219 Memtag,
220 Safestack,
221 ShadowCallStack,
222 Thread,
223 Hwaddress,
224 Realtime,
225}
226
227#[derive(Clone, Copy, Debug, PartialEq)]
228pub(crate) enum CodegenBackend {
229 Cranelift,
230 Gcc,
231 Llvm,
232}
233
234impl FromStr for CodegenBackend {
235 type Err = &'static str;
236
237 fn from_str(value: &str) -> Result<Self, Self::Err> {
238 match value.to_lowercase().as_str() {
239 "cranelift" => Ok(Self::Cranelift),
240 "gcc" => Ok(Self::Gcc),
241 "llvm" => Ok(Self::Llvm),
242 _ => Err("unknown codegen backend"),
243 }
244 }
245}
246
247impl CodegenBackend {
248 pub(crate) fn as_str(self) -> &'static str {
249 match self {
250 Self::Cranelift => "cranelift",
251 Self::Gcc => "gcc",
252 Self::Llvm => "llvm",
253 }
254 }
255
256 pub(crate) fn is_llvm(self) -> bool {
257 matches!(self, Self::Llvm)
258 }
259}
260
261/// Configuration for `compiletest` *per invocation*.
262///
263/// In terms of `bootstrap`, this means that `./x test tests/ui tests/run-make` actually correspond
264/// to *two* separate invocations of `compiletest`.
265///
266/// FIXME: this `Config` struct should be broken up into smaller logically contained sub-config
267/// structs, it's too much of a "soup" of everything at the moment.
268///
269/// # Configuration sources
270///
271/// Configuration values for `compiletest` comes from several sources:
272///
273/// - CLI args passed from `bootstrap` while running the `compiletest` binary.
274/// - Env vars.
275/// - Discovery (e.g. trying to identify a suitable debugger based on filesystem discovery).
276/// - Cached output of running the `rustc` under test (e.g. output of `rustc` print requests).
277///
278/// FIXME: make sure we *clearly* account for sources of *all* config options.
279///
280/// FIXME: audit these options to make sure we are not hashing less than necessary for build stamp
281/// (for changed test detection).
282#[derive(Debug, Clone)]
283pub(crate) struct Config {
284 /// Some [`TestMode`]s support [snapshot testing], where a *reference snapshot* of outputs (of
285 /// `stdout`, `stderr`, or other form of artifacts) can be compared to the *actual output*.
286 ///
287 /// This option can be set to `true` to update the *reference snapshots* in-place, otherwise
288 /// `compiletest` will only try to compare.
289 ///
290 /// [snapshot testing]: https://jestjs.io/docs/snapshot-testing
291 pub(crate) bless: bool,
292
293 /// Attempt to stop as soon as possible after any test fails. We may still run a few more tests
294 /// before stopping when multiple test threads are used.
295 pub(crate) fail_fast: bool,
296
297 /// Path to libraries needed to run the *staged* `rustc`-under-test on the **host** platform.
298 ///
299 /// For example:
300 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1/bin/lib`
301 pub(crate) host_compile_lib_path: Utf8PathBuf,
302
303 /// Path to libraries needed to run the compiled executable for the **target** platform. This
304 /// corresponds to the **target** sysroot libraries, including the **target** standard library.
305 ///
306 /// For example:
307 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/i686-unknown-linux-gnu/lib`
308 ///
309 /// FIXME: this is very under-documented in conjunction with the `remote-test-client` scheme and
310 /// `RUNNER` scheme to actually run the target executable under the target platform environment,
311 /// cf. [`Self::remote_test_client`] and [`Self::runner`].
312 pub(crate) target_run_lib_path: Utf8PathBuf,
313
314 /// Path to the `rustc`-under-test.
315 ///
316 /// For `ui-fulldeps` test suite specifically:
317 ///
318 /// - This is the **stage 0** compiler when testing `ui-fulldeps` under `--stage=1`.
319 /// - This is the **stage 2** compiler when testing `ui-fulldeps` under `--stage=2`.
320 ///
321 /// See [`Self::query_rustc_path`] for the `--stage=1` `ui-fulldeps` scenario where a separate
322 /// in-tree `rustc` is used for querying target information.
323 ///
324 /// For example:
325 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1/bin/rustc`
326 ///
327 /// # Note on forced stage0
328 ///
329 /// It is possible for this `rustc` to be a stage 0 `rustc` if explicitly configured with the
330 /// bootstrap option `build.compiletest-allow-stage0=true` and specifying `--stage=0`.
331 pub(crate) rustc_path: Utf8PathBuf,
332
333 /// Path to a *staged* **host** platform cargo executable (unless stage 0 is forced). This
334 /// staged `cargo` is only used within `run-make` test recipes during recipe run time (and is
335 /// *not* used to compile the test recipes), and so must be staged as there may be differences
336 /// between e.g. beta `cargo` vs in-tree `cargo`.
337 ///
338 /// For example:
339 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1-tools-bin/cargo`
340 ///
341 /// FIXME: maybe rename this to reflect that this is a *staged* host cargo.
342 pub(crate) cargo_path: Option<Utf8PathBuf>,
343
344 /// Path to the stage 0 `rustc` used to build `run-make` recipes. This must not be confused with
345 /// [`Self::rustc_path`].
346 ///
347 /// For example:
348 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage0/bin/rustc`
349 pub(crate) stage0_rustc_path: Option<Utf8PathBuf>,
350
351 /// Path to the run-make-support .rlib file, used to build `run-make` recipes.
352 pub(crate) run_make_support_rlib: Option<Utf8PathBuf>,
353
354 /// Path to the run-make-support .rmeta file, used to build `run-make` recipes.
355 pub(crate) run_make_support_rmeta: Option<Utf8PathBuf>,
356
357 /// Path to the stage 1 or higher `rustc` used to obtain target information via
358 /// `--print=all-target-specs-json` and similar queries.
359 ///
360 /// Normally this is unset, because [`Self::rustc_path`] can be used instead.
361 /// But when running "stage 1" ui-fulldeps tests, `rustc_path` is a stage 0
362 /// compiler, whereas target specs must be obtained from a stage 1+ compiler
363 /// (in case the JSON format has changed since the last bootstrap bump).
364 pub(crate) query_rustc_path: Option<Utf8PathBuf>,
365
366 /// Path to the libraries needed to run the compiler at [`Self::query_rustc_path`].
367 ///
368 /// If unset, [`Self::host_compile_lib_path`] will be used instead.
369 pub(crate) query_rustc_lib_path: Option<Utf8PathBuf>,
370
371 /// Path to the `rustdoc`-under-test. Like [`Self::rustc_path`], this `rustdoc` is *staged*.
372 pub(crate) rustdoc_path: Option<Utf8PathBuf>,
373
374 /// Path to the `src/tools/coverage-dump/` bootstrap tool executable.
375 pub(crate) coverage_dump_path: Option<Utf8PathBuf>,
376
377 /// Path to the Python 3 executable to use for htmldocck and some run-make tests.
378 pub(crate) python: String,
379
380 /// Path to the `src/tools/jsondocck/` bootstrap tool executable.
381 pub(crate) jsondocck_path: Option<Utf8PathBuf>,
382
383 /// Path to the `src/tools/jsondoclint/` bootstrap tool executable.
384 pub(crate) jsondoclint_path: Option<Utf8PathBuf>,
385
386 /// Path to a host LLVM `FileCheck` executable.
387 pub(crate) llvm_filecheck: Option<Utf8PathBuf>,
388
389 /// Path to a host LLVM bintools directory.
390 ///
391 /// For example:
392 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/llvm/bin`
393 pub(crate) llvm_bin_dir: Option<Utf8PathBuf>,
394
395 /// The path to the **target** `clang` executable to run `clang`-based tests with. If `None`,
396 /// then these tests will be ignored.
397 pub(crate) run_clang_based_tests_with: Option<Utf8PathBuf>,
398
399 /// Path to the directory containing the sources. This corresponds to the root folder of a
400 /// `rust-lang/rust` checkout.
401 ///
402 /// For example:
403 /// - `/home/ferris/rust`
404 ///
405 /// FIXME: this name is confusing, because this is actually `$checkout_root`, **not** the
406 /// `$checkout_root/src/` folder.
407 pub(crate) src_root: Utf8PathBuf,
408
409 /// Absolute path to the test suite directory.
410 ///
411 /// For example:
412 /// - `/home/ferris/rust/tests/ui`
413 /// - `/home/ferris/rust/tests/coverage`
414 pub(crate) src_test_suite_root: Utf8PathBuf,
415
416 /// Path to the top-level build directory used by bootstrap.
417 ///
418 /// For example:
419 /// - `/home/ferris/rust/build`
420 pub(crate) build_root: Utf8PathBuf,
421
422 /// Path to the build directory used by the current test suite.
423 ///
424 /// For example:
425 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/test/ui`
426 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/test/coverage`
427 pub(crate) build_test_suite_root: Utf8PathBuf,
428
429 /// Path to the directory containing the sysroot of the `rustc`-under-test.
430 ///
431 /// For example:
432 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1`
433 /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage2`
434 ///
435 /// When stage 0 is forced, this will correspond to the sysroot *of* that specified stage 0
436 /// `rustc`.
437 ///
438 /// FIXME: this name is confusing, because it doesn't specify *which* compiler this sysroot
439 /// corresponds to. It's actually the `rustc`-under-test, and not the bootstrap `rustc`, unless
440 /// stage 0 is forced and no custom stage 0 `rustc` was otherwise specified (so that it
441 /// *happens* to run against the bootstrap `rustc`, but this non-custom bootstrap `rustc` case
442 /// is not really supported).
443 pub(crate) sysroot_base: Utf8PathBuf,
444
445 /// The number of the stage under test.
446 pub(crate) stage: u32,
447
448 /// The id of the stage under test (stage1-xxx, etc).
449 ///
450 /// FIXME: reconsider this string; this is hashed for test build stamp.
451 pub(crate) stage_id: String,
452
453 /// The [`TestMode`]. E.g. [`TestMode::Ui`]. Each test mode can correspond to one or more test
454 /// suites.
455 ///
456 /// FIXME: stop using stringly-typed test suites!
457 pub(crate) mode: TestMode,
458
459 /// The test suite.
460 ///
461 /// Example: `tests/ui/` is [`TestSuite::Ui`] test *suite*, which happens to also be of the
462 /// [`TestMode::Ui`] test *mode*.
463 ///
464 /// Note that the same test suite (e.g. `tests/coverage/`) may correspond to multiple test
465 /// modes, e.g. `tests/coverage/` can be run under both [`TestMode::CoverageRun`] and
466 /// [`TestMode::CoverageMap`].
467 pub(crate) suite: TestSuite,
468
469 /// Run ignored tests *unconditionally*, overriding their ignore reason.
470 ///
471 /// FIXME: this is wired up through the test execution logic, but **not** accessible from
472 /// `bootstrap` directly; `compiletest` exposes this as `--ignored`. I.e. you'd have to use `./x
473 /// test $test_suite -- --ignored=true`.
474 pub(crate) run_ignored: bool,
475
476 /// Whether *staged* `rustc`-under-test was built with debug assertions.
477 ///
478 /// FIXME: make it clearer that this refers to the staged `rustc`-under-test, not stage 0
479 /// `rustc`.
480 pub(crate) with_rustc_debug_assertions: bool,
481
482 /// Whether *staged* `std` was built with debug assertions.
483 ///
484 /// FIXME: make it clearer that this refers to the staged `std`, not stage 0 `std`.
485 pub(crate) with_std_debug_assertions: bool,
486
487 /// Whether *staged* `std` was built with remapping of debuginfo.
488 ///
489 /// FIXME: make it clearer that this refers to the staged `std`, not stage 0 `std`.
490 pub(crate) with_std_remap_debuginfo: bool,
491
492 /// Only run tests that match these filters (using `libtest` "test name contains" filter logic).
493 ///
494 /// FIXME(#139660): the current hand-rolled test executor intentionally mimics the `libtest`
495 /// "test name contains" filter matching logic to preserve previous `libtest` executor behavior,
496 /// but this is often not intuitive. We should consider changing that behavior with an MCP to do
497 /// test path *prefix* matching which better corresponds to how `compiletest` `tests/` are
498 /// organized, and how users would intuitively expect the filtering logic to work like.
499 pub(crate) filters: Vec<String>,
500
501 /// Skip tests matching these substrings. The matching logic exactly corresponds to
502 /// [`Self::filters`] but inverted.
503 ///
504 /// FIXME(#139660): ditto on test matching behavior.
505 pub(crate) skip: Vec<String>,
506
507 /// Exactly match the filter, rather than a substring.
508 ///
509 /// FIXME(#139660): ditto on test matching behavior.
510 pub(crate) filter_exact: bool,
511
512 /// Force the pass mode of a check/build/run test to instead use this mode instead.
513 ///
514 /// FIXME: make it even more obvious (especially in PR CI where `--pass=check` is used) when a
515 /// pass mode is forced when the test fails, because it can be very non-obvious when e.g. an
516 /// error is emitted only when `//@ build-pass` but not `//@ check-pass`.
517 pub(crate) force_pass_mode: Option<ForcePassMode>,
518
519 /// Explicitly enable or disable running of the target test binary.
520 ///
521 /// FIXME: this scheme is a bit confusing, and at times questionable. Re-evaluate this run
522 /// scheme.
523 ///
524 /// FIXME: Currently `--run` is a tri-state, it can be `--run={auto,always,never}`, and when
525 /// `--run=auto` is specified, it's run if the platform doesn't end with `-fuchsia`. See
526 /// [`Config::run_enabled`].
527 pub(crate) run: Option<bool>,
528
529 /// A command line to prefix target program execution with, for running under valgrind for
530 /// example, i.e. `$runner target.exe [args..]`. Similar to `CARGO_*_RUNNER` configuration.
531 ///
532 /// Note: this is not to be confused with [`Self::remote_test_client`], which is a different
533 /// scheme.
534 ///
535 /// FIXME: the runner scheme is very under-documented.
536 pub(crate) runner: Option<String>,
537
538 /// Compiler flags to pass to the *staged* `rustc`-under-test when building for the **host**
539 /// platform.
540 pub(crate) host_rustcflags: Vec<String>,
541
542 /// Compiler flags to pass to the *staged* `rustc`-under-test when building for the **target**
543 /// platform.
544 pub(crate) target_rustcflags: Vec<String>,
545
546 /// Whether the *staged* `rustc`-under-test and the associated *staged* `std` has been built
547 /// with randomized struct layouts.
548 pub(crate) rust_randomized_layout: bool,
549
550 /// Whether tests should be optimized by default (`-O`). Individual test suites and test files
551 /// may override this setting.
552 ///
553 /// FIXME: this flag / config option is somewhat misleading. For instance, in ui tests, it's
554 /// *only* applied to the [`PassFailMode::RunPass`] test crate and not its auxiliaries.
555 pub(crate) optimize_tests: bool,
556
557 /// Whether rustdoc should disable CSS/JS minification when generating docs for tests.
558 ///
559 /// Forwarded from bootstrap's `build.docs-minification = false`.
560 pub(crate) disable_minification: bool,
561
562 /// Target platform tuple.
563 pub(crate) target: String,
564
565 /// Host platform tuple.
566 pub(crate) host: String,
567
568 /// Path to / name of the Microsoft Console Debugger (CDB) executable.
569 ///
570 /// FIXME: this is an *opt-in* "override" option. When this isn't provided, we try to conjure a
571 /// cdb by looking at the user's program files on Windows... See `debuggers::find_cdb`.
572 pub(crate) cdb: Option<Utf8PathBuf>,
573
574 /// Version of CDB.
575 ///
576 /// FIXME: `cdb_version` is *derived* from cdb, but it's *not* technically a config!
577 ///
578 /// FIXME: audit cdb version gating.
579 pub(crate) cdb_version: Option<[u16; 4]>,
580
581 /// Path to / name of the GDB executable.
582 ///
583 /// FIXME: the fallback path when `gdb` isn't provided tries to find *a* `gdb` or `gdb.exe` from
584 /// `PATH`, which is... arguably questionable.
585 ///
586 /// FIXME: we are propagating a python from `PYTHONPATH`, not from an explicit config for gdb
587 /// debugger script.
588 pub(crate) gdb: Option<Utf8PathBuf>,
589
590 /// Version of GDB, encoded as ((major * 1000) + minor) * 1000 + patch
591 ///
592 /// FIXME: this gdb version gating scheme is possibly questionable -- gdb does not use semver,
593 /// only its major version is likely materially meaningful, cf.
594 /// <https://sourceware.org/gdb/wiki/Internals%20Versions>. Even the major version I'm not sure
595 /// is super meaningful. Maybe min gdb `major.minor` version gating is sufficient for the
596 /// purposes of debuginfo tests?
597 ///
598 /// FIXME: `gdb_version` is *derived* from gdb, but it's *not* technically a config!
599 pub(crate) gdb_version: Option<u32>,
600
601 /// Path to or name of the LLDB executable to use for debuginfo tests.
602 pub(crate) lldb: Option<Utf8PathBuf>,
603
604 /// Version of LLDB.
605 ///
606 /// FIXME: `lldb_version` is *derived* from lldb, but it's *not* technically a config!
607 pub(crate) lldb_version: Option<LldbVersion>,
608
609 /// Version of LLVM.
610 ///
611 /// FIXME: Audit the fallback derivation of
612 /// [`crate::directives::extract_llvm_version_from_binary`], that seems very questionable?
613 pub(crate) llvm_version: Option<Version>,
614
615 /// Is LLVM a system LLVM.
616 pub(crate) system_llvm: bool,
617
618 /// Path to the android tools.
619 ///
620 /// Note: this is only used for android gdb debugger script in the debuginfo test suite.
621 ///
622 /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
623 /// `arm-linux-androideabi` target.
624 pub(crate) android_cross_path: Option<Utf8PathBuf>,
625
626 /// Extra parameter to run adb on `arm-linux-androideabi`.
627 ///
628 /// FIXME: is this *only* `arm-linux-androideabi`, or is it also for other Tier 2/3 android
629 /// targets?
630 ///
631 /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
632 /// `arm-linux-androideabi` target.
633 pub(crate) adb_path: Option<Utf8PathBuf>,
634
635 /// Extra parameter to run test suite on `arm-linux-androideabi`.
636 ///
637 /// FIXME: is this *only* `arm-linux-androideabi`, or is it also for other Tier 2/3 android
638 /// targets?
639 ///
640 /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
641 /// `arm-linux-androideabi` target.
642 pub(crate) adb_test_dir: Option<Utf8PathBuf>,
643
644 /// Status whether android device available or not. When unavailable, this will cause tests to
645 /// panic when the test binary is attempted to be run.
646 ///
647 /// FIXME: take a look at this; this also influences adb in gdb code paths in a strange way.
648 pub(crate) adb_device_status: bool,
649
650 /// Verbose dump a lot of info.
651 ///
652 /// FIXME: this is *way* too coarse; the user can't select *which* info to verbosely dump.
653 pub(crate) verbose: bool,
654
655 /// Whether to enable verbose subprocess output for run-make tests.
656 /// Set to false to suppress output for passing tests (e.g. for cg_clif with --no-capture).
657 pub verbose_run_make_subprocess_output: bool,
658
659 /// Where to find the remote test client process, if we're using it.
660 ///
661 /// Note: this is *only* used for target platform executables created by `run-make` test
662 /// recipes.
663 ///
664 /// Note: this is not to be confused with [`Self::runner`], which is a different scheme.
665 ///
666 /// FIXME: the `remote_test_client` scheme is very under-documented.
667 pub(crate) remote_test_client: Option<Utf8PathBuf>,
668
669 /// [`CompareMode`] describing what file the actual ui output will be compared to.
670 ///
671 /// FIXME: currently, [`CompareMode`] is a mishmash of lot of things (different borrow-checker
672 /// model, different trait solver, different debugger, etc.).
673 pub(crate) compare_mode: Option<CompareMode>,
674
675 /// If true, this will generate a coverage file with UI test files that run `MachineApplicable`
676 /// diagnostics but are missing `run-rustfix` annotations. The generated coverage file is
677 /// created in `$test_suite_build_root/rustfix_missing_coverage.txt`
678 pub(crate) rustfix_coverage: bool,
679
680 /// Whether to run `enzyme` autodiff tests.
681 pub(crate) has_enzyme: bool,
682
683 /// Whether to run `offload` autodiff tests.
684 pub(crate) has_offload: bool,
685
686 /// The current Rust channel info.
687 ///
688 /// FIXME: treat this more carefully; "stable", "beta" and "nightly" are definitely valid, but
689 /// channel might also be "dev" or such, which should be treated as "nightly".
690 pub(crate) channel: String,
691
692 /// Whether adding git commit information such as the commit hash has been enabled for building.
693 ///
694 /// FIXME: `compiletest` cannot trust `bootstrap` for this information, because `bootstrap` can
695 /// have bugs and had bugs on that logic. We need to figure out how to obtain this e.g. directly
696 /// from CI or via git locally.
697 pub(crate) git_hash: bool,
698
699 /// The default Rust edition.
700 pub(crate) edition: Option<Edition>,
701
702 // Configuration for various run-make tests frobbing things like C compilers or querying about
703 // various LLVM component information.
704 //
705 // FIXME: this really should be better packaged together.
706 // FIXME: these need better docs, e.g. for *host*, or for *target*?
707 pub(crate) cc: String,
708 pub(crate) cxx: String,
709 pub(crate) cflags: String,
710 pub(crate) cxxflags: String,
711 pub(crate) ar: String,
712 pub(crate) target_linker: Option<String>,
713 pub(crate) host_linker: Option<String>,
714 pub(crate) llvm_components: String,
715
716 /// Path to a NodeJS executable. Used for JS doctests, emscripten and WASM tests.
717 pub(crate) nodejs: Option<Utf8PathBuf>,
718
719 /// Whether to rerun tests even if the inputs are unchanged.
720 pub(crate) force_rerun: bool,
721
722 /// Only rerun the tests that result has been modified according to `git status`.
723 ///
724 /// FIXME: this is undocumented.
725 ///
726 /// FIXME: how does this interact with [`Self::force_rerun`]?
727 pub(crate) only_modified: bool,
728
729 // FIXME: these are really not "config"s, but rather are information derived from
730 // `rustc`-under-test. This poses an interesting conundrum: if we're testing the
731 // `rustc`-under-test, can we trust its print request outputs and target cfgs? In theory, this
732 // itself can break or be unreliable -- ideally, we'd be sharing these kind of information not
733 // through `rustc`-under-test's execution output. In practice, however, print requests are very
734 // unlikely to completely break (we also have snapshot ui tests for them). Furthermore, even if
735 // we share them via some kind of static config, that static config can still be wrong! Who
736 // tests the tester? Therefore, we make a pragmatic compromise here, and use information derived
737 // from print requests produced by the `rustc`-under-test.
738 //
739 // FIXME: move them out from `Config`, because they are *not* configs.
740 pub(crate) target_cfgs: OnceLock<TargetCfgs>,
741 pub(crate) builtin_cfg_names: OnceLock<HashSet<String>>,
742 pub(crate) supported_crate_types: OnceLock<HashSet<String>>,
743
744 /// Should we capture console output that would be printed by test runners via their `stdout`
745 /// and `stderr` trait objects, or via the custom panic hook.
746 ///
747 /// The default is `true`. This can be disabled via the compiletest cli flag `--no-capture`
748 /// (which mirrors the libtest `--no-capture` flag).
749 pub(crate) capture: bool,
750
751 /// Needed both to construct [`build_helper::git::GitConfig`].
752 pub(crate) nightly_branch: String,
753 pub(crate) git_merge_commit_email: String,
754
755 /// True if the profiler runtime is enabled for this target. Used by the
756 /// `needs-profiler-runtime` directive in test files.
757 pub(crate) profiler_runtime: bool,
758
759 /// Command for visual diff display, e.g. `diff-tool --color=always`.
760 pub(crate) diff_command: Option<String>,
761
762 /// Path to minicore aux library (`tests/auxiliary/minicore.rs`), used for `no_core` tests that
763 /// need `core` stubs in cross-compilation scenarios that do not otherwise want/need to
764 /// `-Zbuild-std`. Used in e.g. ABI tests.
765 pub(crate) minicore_path: Utf8PathBuf,
766
767 /// Current codegen backend used.
768 pub(crate) default_codegen_backend: CodegenBackend,
769 /// Name/path of the backend to use instead of `default_codegen_backend`.
770 pub(crate) override_codegen_backend: Option<String>,
771 /// Whether to ignore `//@ ignore-backends`.
772 pub(crate) bypass_ignore_backends: bool,
773
774 /// Number of parallel jobs configured for the build.
775 ///
776 /// This is forwarded from bootstrap's `jobs` configuration.
777 pub(crate) jobs: u32,
778
779 /// Number of parallel threads to use for the frontend when building test artifacts.
780 pub(crate) parallel_frontend_threads: u32,
781 /// Number of times to execute each test.
782 pub(crate) iteration_count: u32,
783
784 pub(crate) wasm_proc_macros: bool,
785}
786
787impl Config {
788 pub(crate) const DEFAULT_PARALLEL_FRONTEND_THREADS: u32 = 1;
789 pub(crate) const DEFAULT_ITERATION_COUNT: u32 = 1;
790
791 /// FIXME: this run scheme is... confusing.
792 pub(crate) fn run_enabled(&self) -> bool {
793 self.run.unwrap_or_else(|| {
794 // Auto-detect whether to run based on the platform.
795 !self.target.ends_with("-fuchsia")
796 })
797 }
798
799 pub(crate) fn target_cfgs(&self) -> &TargetCfgs {
800 self.target_cfgs.get_or_init(|| TargetCfgs::new(self))
801 }
802
803 pub(crate) fn target_cfg(&self) -> &TargetCfg {
804 &self.target_cfgs().current
805 }
806
807 pub(crate) fn matches_arch(&self, arch: &str) -> bool {
808 self.target_cfg().arch == arch
809 || {
810 // Matching all the thumb variants as one can be convenient.
811 // (thumbv6m, thumbv7em, thumbv7m, etc.)
812 arch == "thumb" && self.target.starts_with("thumb")
813 }
814 || (arch == "i586" && self.target.starts_with("i586-"))
815 }
816
817 pub(crate) fn matches_os(&self, os: &str) -> bool {
818 self.target_cfg().os == os
819 }
820
821 pub(crate) fn matches_env(&self, env: &str) -> bool {
822 self.target_cfg().env == env
823 }
824
825 pub(crate) fn matches_abi(&self, abi: &str) -> bool {
826 self.target_cfg().abi == abi
827 }
828
829 #[cfg_attr(not(test), expect(dead_code, reason = "only used by tests for `ignore-{family}`"))]
830 pub(crate) fn matches_family(&self, family: &str) -> bool {
831 self.target_cfg().families.iter().any(|f| f == family)
832 }
833
834 pub(crate) fn is_big_endian(&self) -> bool {
835 self.target_cfg().endian == Endian::Big
836 }
837
838 pub(crate) fn get_pointer_width(&self) -> u32 {
839 *&self.target_cfg().pointer_width
840 }
841
842 pub(crate) fn can_unwind(&self) -> bool {
843 self.target_cfg().panic == PanicStrategy::Unwind
844 }
845
846 /// Get the list of builtin, 'well known' cfg names
847 pub(crate) fn builtin_cfg_names(&self) -> &HashSet<String> {
848 self.builtin_cfg_names.get_or_init(|| builtin_cfg_names(self))
849 }
850
851 /// Get the list of crate types that the target platform supports.
852 pub(crate) fn supported_crate_types(&self) -> &HashSet<String> {
853 self.supported_crate_types.get_or_init(|| supported_crate_types(self))
854 }
855
856 pub(crate) fn has_threads(&self) -> bool {
857 // Wasm targets don't have threads unless `-threads` is in the target
858 // name, such as `wasm32-wasip1-threads`.
859 if self.target.starts_with("wasm") {
860 return self.target.contains("threads");
861 }
862 true
863 }
864
865 pub(crate) fn has_asm_support(&self) -> bool {
866 // This should match the stable list in `LoweringContext::lower_inline_asm`.
867 static ASM_SUPPORTED_ARCHS: &[&str] = &[
868 "x86",
869 "x86_64",
870 "arm",
871 "aarch64",
872 "arm64ec",
873 "riscv32",
874 "riscv64",
875 "loongarch32",
876 "loongarch64",
877 "s390x",
878 // These targets require an additional asm_experimental_arch feature.
879 // "nvptx64", "hexagon", "mips", "mips64", "spirv", "wasm32",
880 ];
881 ASM_SUPPORTED_ARCHS.contains(&self.target_cfg().arch.as_str())
882 }
883
884 pub(crate) fn git_config(&self) -> GitConfig<'_> {
885 GitConfig {
886 nightly_branch: &self.nightly_branch,
887 git_merge_commit_email: &self.git_merge_commit_email,
888 }
889 }
890
891 pub(crate) fn has_subprocess_support(&self) -> bool {
892 // FIXME(#135928): compiletest is always a **host** tool. Building and running an
893 // capability detection executable against the **target** is not trivial. The short term
894 // solution here is to hard-code some targets to allow/deny, unfortunately.
895
896 let unsupported_target = self.target_cfg().env == "sgx"
897 || matches!(self.target_cfg().arch.as_str(), "wasm32" | "wasm64")
898 || self.target_cfg().os == "emscripten";
899 !unsupported_target
900 }
901
902 /// Whether the parallel frontend is enabled,
903 /// which is the case when `parallel_frontend_threads` is not set to `1`.
904 ///
905 /// - `0` means auto-detect: use the number of available hardware threads on the host.
906 /// But we treat it as the parallel frontend being enabled in this case.
907 /// - `1` means single-threaded (parallel frontend disabled).
908 /// - `>1` means an explicitly configured thread count.
909 pub(crate) fn parallel_frontend_enabled(&self) -> bool {
910 self.parallel_frontend_threads != 1
911 }
912}
913
914/// Known widths of `target_has_atomic`.
915pub(crate) const KNOWN_TARGET_HAS_ATOMIC_WIDTHS: &[&str] = &["8", "16", "32", "64", "128", "ptr"];
916
917#[derive(Debug, Clone)]
918pub(crate) struct TargetCfgs {
919 pub(crate) current: TargetCfg,
920 pub(crate) all_targets: HashSet<String>,
921 pub(crate) all_archs: HashSet<String>,
922 pub(crate) all_oses: HashSet<String>,
923 pub(crate) all_oses_and_envs: HashSet<String>,
924 pub(crate) all_envs: HashSet<String>,
925 pub(crate) all_abis: HashSet<String>,
926 pub(crate) all_families: HashSet<String>,
927 pub(crate) all_pointer_widths: HashSet<String>,
928 pub(crate) all_rustc_abis: HashSet<String>,
929}
930
931impl TargetCfgs {
932 fn new(config: &Config) -> TargetCfgs {
933 let mut targets: HashMap<String, TargetCfg> = serde_json::from_str(&query_rustc_output(
934 config,
935 &["--print=all-target-specs-json", "-Zunstable-options"],
936 Default::default(),
937 ))
938 .unwrap();
939
940 let mut all_targets = HashSet::new();
941 let mut all_archs = HashSet::new();
942 let mut all_oses = HashSet::new();
943 let mut all_oses_and_envs = HashSet::new();
944 let mut all_envs = HashSet::new();
945 let mut all_abis = HashSet::new();
946 let mut all_families = HashSet::new();
947 let mut all_pointer_widths = HashSet::new();
948 // NOTE: for distinction between `abi` and `rustc_abi`, see comment on
949 // `TargetCfg::rustc_abi`.
950 let mut all_rustc_abis = HashSet::new();
951
952 // If current target is not included in the `--print=all-target-specs-json` output,
953 // we check whether it is a custom target from the user or a synthetic target from bootstrap.
954 if !targets.contains_key(&config.target) {
955 let mut envs: HashMap<String, String> = HashMap::new();
956
957 if let Ok(t) = std::env::var("RUST_TARGET_PATH") {
958 envs.insert("RUST_TARGET_PATH".into(), t);
959 }
960
961 // This returns false only when the target is neither a synthetic target
962 // nor a custom target from the user, indicating it is most likely invalid.
963 if config.target.ends_with(".json") || !envs.is_empty() {
964 targets.insert(
965 config.target.clone(),
966 serde_json::from_str(&query_rustc_output(
967 config,
968 &[
969 "--print=target-spec-json",
970 "-Zunstable-options",
971 "--target",
972 &config.target,
973 ],
974 envs,
975 ))
976 .unwrap(),
977 );
978 }
979 }
980
981 for (target, cfg) in targets.iter() {
982 all_archs.insert(cfg.arch.clone());
983 all_oses.insert(cfg.os.clone());
984 all_oses_and_envs.insert(cfg.os_and_env());
985 all_envs.insert(cfg.env.clone());
986 all_abis.insert(cfg.abi.clone());
987 for family in &cfg.families {
988 all_families.insert(family.clone());
989 }
990 all_pointer_widths.insert(format!("{}bit", cfg.pointer_width));
991 if let Some(rustc_abi) = &cfg.rustc_abi {
992 all_rustc_abis.insert(rustc_abi.clone());
993 }
994 all_targets.insert(target.clone());
995 }
996
997 Self {
998 current: Self::get_current_target_config(config, &targets),
999 all_targets,
1000 all_archs,
1001 all_oses,
1002 all_oses_and_envs,
1003 all_envs,
1004 all_abis,
1005 all_families,
1006 all_pointer_widths,
1007 all_rustc_abis,
1008 }
1009 }
1010
1011 fn get_current_target_config(
1012 config: &Config,
1013 targets: &HashMap<String, TargetCfg>,
1014 ) -> TargetCfg {
1015 let mut cfg = targets[&config.target].clone();
1016
1017 // To get the target information for the current target, we take the target spec obtained
1018 // from `--print=all-target-specs-json`, and then we enrich it with the information
1019 // gathered from `--print=cfg --target=$target`.
1020 //
1021 // This is done because some parts of the target spec can be overridden with `-C` flags,
1022 // which are respected for `--print=cfg` but not for `--print=all-target-specs-json`. The
1023 // code below extracts them from `--print=cfg`: make sure to only override fields that can
1024 // actually be changed with `-C` flags.
1025 for config in query_rustc_output(
1026 config,
1027 // `-Zunstable-options` is necessary when compiletest is running with custom targets
1028 // (such as synthetic targets used to bless mir-opt tests).
1029 &["-Zunstable-options", "--print=cfg", "--target", &config.target],
1030 Default::default(),
1031 )
1032 .trim()
1033 .lines()
1034 {
1035 let (name, value) = config
1036 .split_once("=\"")
1037 .map(|(name, value)| {
1038 (
1039 name,
1040 Some(
1041 value
1042 .strip_suffix('\"')
1043 .expect("key-value pair should be properly quoted"),
1044 ),
1045 )
1046 })
1047 .unwrap_or_else(|| (config, None));
1048
1049 match (name, value) {
1050 // Can be overridden with `-C panic=$strategy`.
1051 ("panic", Some("abort")) => cfg.panic = PanicStrategy::Abort,
1052 ("panic", Some("unwind")) => cfg.panic = PanicStrategy::Unwind,
1053 ("panic", other) => panic!("unexpected value for panic cfg: {other:?}"),
1054
1055 ("target_has_atomic", Some(width))
1056 if KNOWN_TARGET_HAS_ATOMIC_WIDTHS.contains(&width) =>
1057 {
1058 cfg.target_has_atomic.insert(width.to_string());
1059 }
1060 ("target_has_atomic", Some(other)) => {
1061 panic!("unexpected value for `target_has_atomic` cfg: {other:?}")
1062 }
1063 // Nightly-only std-internal impl detail.
1064 ("target_has_atomic", None) => {}
1065 _ => {}
1066 }
1067 }
1068
1069 cfg
1070 }
1071}
1072
1073#[derive(Clone, Debug, serde::Deserialize)]
1074#[serde(rename_all = "kebab-case")]
1075pub(crate) struct TargetCfg {
1076 pub(crate) arch: String,
1077 #[serde(default = "default_os")]
1078 pub(crate) os: String,
1079 #[serde(default)]
1080 pub(crate) env: String,
1081 #[serde(default)]
1082 pub(crate) abi: String,
1083 #[serde(rename = "target-family", default)]
1084 pub(crate) families: Vec<String>,
1085 #[serde(rename = "target-pointer-width")]
1086 pub(crate) pointer_width: u32,
1087 #[serde(rename = "target-endian", default)]
1088 endian: Endian,
1089 #[serde(rename = "panic-strategy", default)]
1090 pub(crate) panic: PanicStrategy,
1091 #[serde(default)]
1092 pub(crate) dynamic_linking: bool,
1093 #[serde(rename = "supported-sanitizers", default)]
1094 pub(crate) sanitizers: Vec<Sanitizer>,
1095 #[serde(rename = "supports-xray", default)]
1096 pub(crate) xray: bool,
1097 #[serde(default = "default_reloc_model")]
1098 pub(crate) relocation_model: String,
1099 // NOTE: `rustc_abi` should not be confused with `abi`. `rustc_abi` was introduced in #137037 to
1100 // make SSE2 *required* by the ABI (kind of a hack to make a target feature *required* via the
1101 // target spec).
1102 pub(crate) rustc_abi: Option<String>,
1103
1104 /// ELF is the "default" binary format, so the compiler typically doesn't
1105 /// emit a `"binary-format"` field for ELF targets.
1106 ///
1107 /// See `impl ToJson for Target` in `compiler/rustc_target/src/spec/json.rs`.
1108 #[serde(default = "default_binary_format_elf")]
1109 pub(crate) binary_format: Cow<'static, str>,
1110
1111 // Not present in target cfg json output, additional derived information.
1112 #[serde(skip)]
1113 /// Supported target atomic widths: e.g. `8` to `128` or `ptr`. This is derived from the builtin
1114 /// `target_has_atomic` `cfg`s e.g. `target_has_atomic="8"`.
1115 pub(crate) target_has_atomic: BTreeSet<String>,
1116}
1117
1118impl TargetCfg {
1119 pub(crate) fn os_and_env(&self) -> String {
1120 format!("{}-{}", self.os, self.env)
1121 }
1122}
1123
1124fn default_os() -> String {
1125 "none".into()
1126}
1127
1128fn default_reloc_model() -> String {
1129 "pic".into()
1130}
1131
1132fn default_binary_format_elf() -> Cow<'static, str> {
1133 Cow::Borrowed("elf")
1134}
1135
1136#[derive(Eq, PartialEq, Clone, Debug, Default, serde::Deserialize)]
1137#[serde(rename_all = "kebab-case")]
1138pub(crate) enum Endian {
1139 #[default]
1140 Little,
1141 Big,
1142}
1143
1144fn builtin_cfg_names(config: &Config) -> HashSet<String> {
1145 query_rustc_output(
1146 config,
1147 &["--print=check-cfg", "-Zunstable-options", "--check-cfg=cfg()"],
1148 Default::default(),
1149 )
1150 .lines()
1151 .map(|l| extract_cfg_name(&l).unwrap().to_string())
1152 .chain(std::iter::once(String::from("test")))
1153 .collect()
1154}
1155
1156/// Extract the cfg name from `cfg(name, values(...))` lines
1157fn extract_cfg_name(check_cfg_line: &str) -> Result<&str, &'static str> {
1158 let trimmed = check_cfg_line.trim();
1159
1160 #[rustfmt::skip]
1161 let inner = trimmed
1162 .strip_prefix("cfg(")
1163 .ok_or("missing cfg(")?
1164 .strip_suffix(")")
1165 .ok_or("missing )")?;
1166
1167 let first_comma = inner.find(',').ok_or("no comma found")?;
1168
1169 Ok(inner[..first_comma].trim())
1170}
1171
1172pub(crate) const KNOWN_CRATE_TYPES: &[&str] =
1173 &["bin", "cdylib", "dylib", "lib", "proc-macro", "rlib", "staticlib"];
1174
1175fn supported_crate_types(config: &Config) -> HashSet<String> {
1176 let crate_types: HashSet<_> = query_rustc_output(
1177 config,
1178 &["--target", &config.target, "--print=supported-crate-types", "-Zunstable-options"],
1179 Default::default(),
1180 )
1181 .lines()
1182 .map(|l| l.to_string())
1183 .collect();
1184
1185 for crate_type in crate_types.iter() {
1186 assert!(
1187 KNOWN_CRATE_TYPES.contains(&crate_type.as_str()),
1188 "unexpected crate type `{}`: known crate types are {:?}",
1189 crate_type,
1190 KNOWN_CRATE_TYPES
1191 );
1192 }
1193
1194 crate_types
1195}
1196
1197pub(crate) fn query_rustc_output(
1198 config: &Config,
1199 args: &[&str],
1200 envs: HashMap<String, String>,
1201) -> String {
1202 let query_rustc_path = config.query_rustc_path.as_deref().unwrap_or(&config.rustc_path);
1203
1204 let mut command = Command::new(query_rustc_path);
1205 add_dylib_path(
1206 &mut command,
1207 iter::once(config.query_rustc_lib_path.as_deref().unwrap_or(&config.host_compile_lib_path)),
1208 );
1209 command.args(&config.target_rustcflags).args(args);
1210 command.env("RUSTC_BOOTSTRAP", "1");
1211 command.envs(envs);
1212
1213 let output = match command.output() {
1214 Ok(output) => output,
1215 Err(e) => {
1216 fatal!("failed to run {command:?}: {e}");
1217 }
1218 };
1219 if !output.status.success() {
1220 fatal!(
1221 "failed to run {command:?}\n--- stdout\n{}\n--- stderr\n{}",
1222 String::from_utf8(output.stdout).unwrap(),
1223 String::from_utf8(output.stderr).unwrap(),
1224 );
1225 }
1226 String::from_utf8(output.stdout).unwrap()
1227}
1228
1229/// Path information for a single test file.
1230#[derive(Debug, Clone)]
1231pub(crate) struct TestPaths {
1232 /// Full path to the test file.
1233 ///
1234 /// For example:
1235 /// - `/home/ferris/rust/tests/ui/warnings/hello-world.rs`
1236 ///
1237 /// ---
1238 ///
1239 /// For `run-make` tests, this path is the _directory_ that contains
1240 /// `rmake.rs`.
1241 ///
1242 /// For example:
1243 /// - `/home/ferris/rust/tests/run-make/emit`
1244 pub(crate) file: Utf8PathBuf,
1245
1246 /// Subset of the full path that excludes the suite directory and the
1247 /// test filename. For tests in the root of their test suite directory,
1248 /// this is blank.
1249 ///
1250 /// For example:
1251 /// - `file`: `/home/ferris/rust/tests/ui/warnings/hello-world.rs`
1252 /// - `relative_dir`: `warnings`
1253 pub(crate) relative_dir: Utf8PathBuf,
1254}
1255
1256/// Used by `ui` tests to generate things like `foo.stderr` from `foo.rs`.
1257pub(crate) fn expected_output_path(
1258 testpaths: &TestPaths,
1259 revision: Option<&str>,
1260 compare_mode: &Option<CompareMode>,
1261 kind: &str,
1262) -> Utf8PathBuf {
1263 assert!(UI_EXTENSIONS.contains(&kind));
1264 let mut parts = Vec::new();
1265
1266 if let Some(x) = revision {
1267 parts.push(x);
1268 }
1269 if let Some(ref x) = *compare_mode {
1270 parts.push(x.to_str());
1271 }
1272 parts.push(kind);
1273
1274 let extension = parts.join(".");
1275 testpaths.file.with_extension(extension)
1276}
1277
1278pub(crate) const UI_EXTENSIONS: &[&str] = &[
1279 UI_STDERR,
1280 UI_SVG,
1281 UI_WINDOWS_SVG,
1282 UI_STDOUT,
1283 UI_FIXED,
1284 UI_RUN_STDERR,
1285 UI_RUN_STDOUT,
1286 UI_STDERR_64,
1287 UI_STDERR_32,
1288 UI_STDERR_16,
1289 UI_COVERAGE,
1290 UI_COVERAGE_MAP,
1291];
1292pub(crate) const UI_STDERR: &str = "stderr";
1293pub(crate) const UI_SVG: &str = "svg";
1294pub(crate) const UI_WINDOWS_SVG: &str = "windows.svg";
1295pub(crate) const UI_STDOUT: &str = "stdout";
1296pub(crate) const UI_FIXED: &str = "fixed";
1297pub(crate) const UI_RUN_STDERR: &str = "run.stderr";
1298pub(crate) const UI_RUN_STDOUT: &str = "run.stdout";
1299pub(crate) const UI_STDERR_64: &str = "64bit.stderr";
1300pub(crate) const UI_STDERR_32: &str = "32bit.stderr";
1301pub(crate) const UI_STDERR_16: &str = "16bit.stderr";
1302pub(crate) const UI_COVERAGE: &str = "coverage";
1303pub(crate) const UI_COVERAGE_MAP: &str = "cov-map";
1304
1305/// Absolute path to the directory where all output for all tests in the given `relative_dir` group
1306/// should reside. Example:
1307///
1308/// ```text
1309/// /path/to/build/host-tuple/test/ui/relative/
1310/// ```
1311///
1312/// This is created early when tests are collected to avoid race conditions.
1313pub(crate) fn output_relative_path(config: &Config, relative_dir: &Utf8Path) -> Utf8PathBuf {
1314 config.build_test_suite_root.join(relative_dir)
1315}
1316
1317/// Generates a unique name for the test, such as `testname.revision.mode`.
1318pub(crate) fn output_testname_unique(
1319 config: &Config,
1320 testpaths: &TestPaths,
1321 variant: &TestVariant,
1322) -> Utf8PathBuf {
1323 let mode = config.compare_mode.as_ref().map_or("", |m| m.to_str());
1324 let debugger = variant.debugger.as_ref().map_or("", |m| m.to_str());
1325 Utf8PathBuf::from(&testpaths.file.file_stem().unwrap())
1326 .with_extra_extension(config.mode.output_dir_disambiguator())
1327 .with_extra_extension(variant.revision().unwrap_or(""))
1328 .with_extra_extension(mode)
1329 .with_extra_extension(debugger)
1330}
1331
1332/// Absolute path to the directory where all output for the given
1333/// test/revision should reside. Example:
1334/// /path/to/build/host-tuple/test/ui/relative/testname.revision.mode/
1335pub(crate) fn output_base_dir(
1336 config: &Config,
1337 testpaths: &TestPaths,
1338 variant: &TestVariant,
1339) -> Utf8PathBuf {
1340 output_relative_path(config, &testpaths.relative_dir)
1341 .join(output_testname_unique(config, testpaths, variant))
1342}
1343
1344/// Absolute path to the base filename used as output for the given
1345/// test/revision. Example:
1346/// /path/to/build/host-tuple/test/ui/relative/testname.revision.mode/testname
1347pub(crate) fn output_base_name(
1348 config: &Config,
1349 testpaths: &TestPaths,
1350 variant: &TestVariant,
1351) -> Utf8PathBuf {
1352 output_base_dir(config, testpaths, variant).join(testpaths.file.file_stem().unwrap())
1353}
1354
1355/// Absolute path to the directory to use for incremental compilation. Example:
1356/// /path/to/build/host-tuple/test/ui/relative/testname.mode/testname.inc
1357pub(crate) fn incremental_dir(
1358 config: &Config,
1359 testpaths: &TestPaths,
1360 variant: &TestVariant,
1361) -> Utf8PathBuf {
1362 output_base_name(config, testpaths, variant).with_extension("inc")
1363}