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