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