Skip to main content

compiletest/
runtest.rs

1use std::borrow::Cow;
2use std::collections::{HashMap, HashSet};
3use std::ffi::OsString;
4use std::fs::{self, create_dir_all};
5use std::hash::{DefaultHasher, Hash, Hasher};
6use std::io::prelude::*;
7use std::process::{Child, Command, ExitStatus, Output, Stdio};
8use std::{env, fmt, io, iter, str};
9
10use build_helper::fs::remove_and_create_dir_all;
11use camino::{Utf8Path, Utf8PathBuf};
12use colored::{Color, Colorize};
13use regex::{Captures, Regex};
14use tracing::*;
15
16use crate::common::{
17    CompareMode, Config, Debugger, ForcePassMode, PassFailMode, RunResult, TestMode, TestPaths,
18    TestSuite, UI_EXTENSIONS, UI_FIXED, UI_RUN_STDERR, UI_RUN_STDOUT, UI_STDERR, UI_STDOUT, UI_SVG,
19    expected_output_path, incremental_dir, output_base_dir, output_base_name,
20};
21use crate::directives::{AuxCrate, TestProps};
22use crate::edition::Edition;
23use crate::errors::{Error, ErrorKind, load_errors};
24use crate::executor::TestVariant;
25use crate::output_capture::ConsoleOut;
26use crate::read2::{Truncated, read2_abbreviated};
27use crate::runtest::compute_diff::{DiffLine, diff_by_lines, make_diff, write_diff};
28use crate::util::{ArgFileCommand, Utf8PathBufExt, add_dylib_path, static_regex};
29use crate::{discovery, json};
30
31// Helper modules that implement test running logic for each test suite.
32// tidy-alphabetical-start
33mod assembly;
34mod codegen;
35mod codegen_units;
36mod coverage;
37mod crashes;
38mod debuginfo;
39mod incremental;
40mod js_doc;
41mod mir_opt;
42mod pretty;
43mod run_make;
44mod rustdoc;
45mod rustdoc_json;
46mod ui;
47// tidy-alphabetical-end
48
49mod compute_diff;
50mod debugger;
51#[cfg(test)]
52mod tests;
53
54const FAKE_SRC_BASE: &str = "fake-test-src-base";
55
56#[cfg(windows)]
57fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
58    use std::sync::Mutex;
59
60    use windows::Win32::System::Diagnostics::Debug::{
61        SEM_FAILCRITICALERRORS, SEM_NOGPFAULTERRORBOX, SetErrorMode,
62    };
63
64    static LOCK: Mutex<()> = Mutex::new(());
65
66    // Error mode is a global variable, so lock it so only one thread will change it
67    let _lock = LOCK.lock().unwrap();
68
69    // Tell Windows to not show any UI on errors (such as terminating abnormally). This is important
70    // for running tests, since some of them use abnormal termination by design. This mode is
71    // inherited by all child processes.
72    //
73    // Note that `run-make` tests require `SEM_FAILCRITICALERRORS` in addition to suppress Windows
74    // Error Reporting (WER) error dialogues that come from "critical failures" such as missing
75    // DLLs.
76    //
77    // See <https://github.com/rust-lang/rust/issues/132092> and
78    // <https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-seterrormode?redirectedfrom=MSDN>.
79    unsafe {
80        // read inherited flags
81        let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
82        SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
83        let r = f();
84        SetErrorMode(old_mode);
85        r
86    }
87}
88
89#[cfg(not(windows))]
90fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
91    f()
92}
93
94/// The platform-specific library name
95fn get_lib_name(name: &str, aux_type: AuxType, wasm_proc_macros: bool) -> Option<String> {
96    match aux_type {
97        AuxType::Bin => None,
98        // In some cases (e.g. MUSL), we build a static
99        // library, rather than a dynamic library.
100        // In this case, the only path we can pass
101        // with '--extern-meta' is the '.rlib' file
102        AuxType::Lib => Some(format!("lib{name}.rlib")),
103        // FIXME maybe use `rustc --print file-names` instead?
104        AuxType::ProcMacro if wasm_proc_macros => Some(format!("{name}.wasm")),
105        AuxType::Dylib | AuxType::ProcMacro | AuxType::Lint => Some(dylib_name(name)),
106    }
107}
108
109fn dylib_name(name: &str) -> String {
110    format!("{}{name}.{}", std::env::consts::DLL_PREFIX, std::env::consts::DLL_EXTENSION)
111}
112
113pub(crate) fn run(
114    config: &Config,
115    stdout: &dyn ConsoleOut,
116    stderr: &dyn ConsoleOut,
117    testpaths: &TestPaths,
118    variant: &TestVariant,
119) {
120    match &*config.target {
121        "arm-linux-androideabi"
122        | "armv7-linux-androideabi"
123        | "thumbv7neon-linux-androideabi"
124        | "aarch64-linux-android" => {
125            if !config.adb_device_status {
126                panic!("android device not available");
127            }
128        }
129        _ => {}
130    }
131
132    if config.verbose {
133        // We're going to be dumping a lot of info. Start on a new line.
134        write!(stdout, "\n\n");
135    }
136    debug!("running {}", testpaths.file);
137    let mut props = TestProps::from_file(&testpaths.file, variant.revision(), &config);
138
139    // For non-incremental (i.e. regular UI) tests, the incremental directory
140    // takes into account the revision name, since the revisions are independent
141    // of each other and can race.
142    if props.incremental {
143        props.incremental_dir = Some(incremental_dir(&config, testpaths, variant));
144    }
145
146    let cx = TestCx { config: &config, stdout, stderr, props: &props, testpaths, variant };
147
148    if let Err(e) = create_dir_all(&cx.output_base_dir()) {
149        panic!("failed to create output base directory {}: {e}", cx.output_base_dir());
150    }
151
152    if props.incremental {
153        cx.init_incremental_test();
154    }
155
156    if config.mode == TestMode::Incremental {
157        // Incremental tests are special because they cannot be run in
158        // parallel.
159        assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
160        for revision in &props.revisions {
161            let mut revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
162            revision_props.incremental_dir = props.incremental_dir.clone();
163            let rev_cx = TestCx {
164                config: &config,
165                stdout,
166                stderr,
167                props: &revision_props,
168                testpaths,
169                variant: &TestVariant {
170                    revision: Some(revision.clone()),
171                    debugger: variant.debugger,
172                },
173            };
174            rev_cx.run_revision();
175        }
176    } else {
177        cx.run_revision();
178    }
179
180    cx.create_stamp();
181}
182
183pub(crate) fn compute_stamp_hash(config: &Config, variant: &TestVariant) -> String {
184    let mut hash = DefaultHasher::new();
185    config.stage_id.hash(&mut hash);
186    config.run.hash(&mut hash);
187    config.edition.hash(&mut hash);
188
189    match variant.debugger {
190        Some(Debugger::Cdb) => {
191            config.cdb.hash(&mut hash);
192        }
193
194        Some(Debugger::Gdb) => {
195            config.gdb.hash(&mut hash);
196            env::var_os("PATH").hash(&mut hash);
197            env::var_os("PYTHONPATH").hash(&mut hash);
198        }
199
200        Some(Debugger::Lldb) => {
201            // LLDB debuginfo tests now use LLDB's embedded Python, with an
202            // explicit PYTHONPATH, so they don't depend on `--python` or
203            // the ambient PYTHONPATH.
204            config.lldb.hash(&mut hash);
205            env::var_os("PATH").hash(&mut hash);
206        }
207
208        None => {}
209    }
210
211    if config.mode == TestMode::Ui {
212        config.force_pass_mode.hash(&mut hash);
213    }
214
215    format!("{:x}", hash.finish())
216}
217
218#[derive(Copy, Clone, Debug)]
219struct TestCx<'test> {
220    config: &'test Config,
221    stdout: &'test dyn ConsoleOut,
222    stderr: &'test dyn ConsoleOut,
223    props: &'test TestProps,
224    testpaths: &'test TestPaths,
225    variant: &'test TestVariant,
226}
227
228impl TestCx<'_> {
229    fn edition(self) -> Edition {
230        // We're always explicitly defaulting to rustc's default to suppress the
231        // warning that rustc emits when no edition gets specified.
232        self.props.edition.or(self.config.edition).unwrap_or(Edition::RUSTC_DEFAULT)
233    }
234}
235
236enum ReadFrom {
237    Path,
238    Stdin(String),
239}
240
241enum TestOutput {
242    Compile,
243    Run,
244}
245
246/// Will this test be executed? Should we use `make_exe_name`?
247#[derive(Copy, Clone, PartialEq)]
248enum WillExecute {
249    Yes,
250    No,
251    Disabled,
252}
253
254/// What value should be passed to `--emit`?
255#[derive(Copy, Clone)]
256enum Emit {
257    None,
258    Metadata,
259    LlvmIr,
260    Mir,
261    Asm,
262    LinkArgsAsm,
263}
264
265/// Indicates whether we are using `rustc`, `rustdoc` or `compiletest-lint-driver`` to compile an input file.
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267enum CompilerKind {
268    Rustc,
269    Rustdoc,
270    LintDriver,
271}
272
273/// Unstable compiler flags that compiletest passes to UI tests on its own, i.e. without specific
274/// tests opting into them explicitly.
275/// This should include both flags that are always passed unconditionally (e.g. `-Zui-testing`) and
276/// flags that are enabled across the whole test suite when compiletest is configured in a
277/// certain way (e.g. a specific `-Zcodegen-backend` being used for all tests).
278///
279/// Note: try to keep this up-to-date with [`TestCx::make_compile_args`].
280pub(crate) const COMPILETEST_UI_SUITE_UNSTABLE_FLAGS: &[&str] = &[
281    "simulate-remapped-rust-src-base",
282    "translate-remapped-path-to-local-path",
283    "ignore-directory-in-diagnostics-source-blocks",
284    "deduplicate-diagnostics",
285    "write-long-types-to-disk",
286    "codegen-backend",
287    "next-solver",
288    "polonius",
289    "wasm-proc-macros",
290    "threads",
291    "ui-testing",
292    "unstable-options",
293];
294
295impl<'test> TestCx<'test> {
296    /// Code executed for each revision in turn (or, if there are no
297    /// revisions, exactly once, with revision == None).
298    fn run_revision(&self) {
299        // Run the test multiple times if requested.
300        // This is useful for catching flaky tests under the parallel frontend.
301        for _ in 0..self.config.iteration_count {
302            match self.config.mode {
303                TestMode::Pretty => self.run_pretty_test(),
304                TestMode::DebugInfo => self.run_debuginfo_test(),
305                TestMode::Codegen => self.run_codegen_test(),
306                TestMode::RustdocHtml => self.run_rustdoc_html_test(),
307                TestMode::RustdocJson => self.run_rustdoc_json_test(),
308                TestMode::CodegenUnits => self.run_codegen_units_test(),
309                TestMode::Incremental => self.run_incremental_test(),
310                TestMode::RunMake => self.run_rmake_test(),
311                TestMode::Ui => self.run_ui_test(),
312                TestMode::MirOpt => self.run_mir_opt_test(),
313                TestMode::Assembly => self.run_assembly_test(),
314                TestMode::RustdocJs => self.run_rustdoc_js_test(),
315                TestMode::CoverageMap => self.run_coverage_map_test(), // see self::coverage
316                TestMode::CoverageRun => self.run_coverage_run_test(), // see self::coverage
317                TestMode::Crashes => self.run_crash_test(),
318            }
319        }
320    }
321
322    /// Returns the pass/fail expectation of this UI test
323    /// (e.g. `//@ check-pass` or `//@ build-fail`),
324    /// possibly modified by an explicit `--pass=check` on the command-line.
325    fn effective_pass_fail_mode(&self) -> Option<PassFailMode> {
326        assert_eq!(self.config.mode, TestMode::Ui);
327        // UI tests always have a pass/fail mode, but their auxiliary crates never have one.
328        let declared = self.props.pass_fail_mode?;
329
330        // Specifying `--pass` only overrides `//@ pass-*` modes, and only if
331        // the test doesn't opt out with `//@ no-pass-override`.
332        if let Some(force_pass_mode) = self.config.force_pass_mode
333            && !self.props.no_pass_override
334            && declared.is_pass()
335        {
336            match force_pass_mode {
337                ForcePassMode::Check => Some(PassFailMode::CheckPass),
338                ForcePassMode::Build => Some(PassFailMode::BuildPass),
339                ForcePassMode::Run => Some(PassFailMode::RunPass),
340            }
341        } else {
342            Some(declared)
343        }
344    }
345
346    fn run_if_enabled(&self) -> WillExecute {
347        if self.config.run_enabled() { WillExecute::Yes } else { WillExecute::Disabled }
348    }
349
350    fn check_if_test_should_compile(&self, pass_fail: PassFailMode, proc_res: &ProcRes) {
351        assert_eq!(self.config.mode, TestMode::Ui);
352
353        let should_compile_successfully = match pass_fail {
354            PassFailMode::CheckFail | PassFailMode::BuildFail => false,
355
356            PassFailMode::CheckPass
357            | PassFailMode::BuildPass
358            | PassFailMode::RunFail
359            | PassFailMode::RunCrash
360            | PassFailMode::RunFailOrCrash
361            | PassFailMode::RunPass => true,
362        };
363
364        if should_compile_successfully {
365            if !proc_res.status.success() {
366                if pass_fail == PassFailMode::CheckPass
367                    && self.effective_pass_fail_mode() == Some(PassFailMode::BuildFail)
368                {
369                    // A `build-fail` test needs to `check-pass`.
370                    self.fatal_proc_rec(
371                        "`build-fail` test is required to pass check build, but check build failed",
372                        proc_res,
373                    );
374                } else {
375                    self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res);
376                }
377            }
378        } else {
379            if proc_res.status.success() {
380                let err = &format!("{} test did not emit an error", self.config.mode);
381                let extra_note = Some(
382                    "note: by default, ui tests are expected not to compile.\nhint: use check-pass, build-pass, or run-pass directive to change this behavior.",
383                );
384                self.fatal_proc_rec_general(err, extra_note, proc_res, || ());
385            }
386
387            if !self.props.dont_check_failure_status {
388                self.check_correct_failure_status(proc_res);
389            }
390        }
391    }
392
393    fn get_output(&self, proc_res: &ProcRes) -> String {
394        if self.props.check_stdout {
395            format!("{}{}", proc_res.stdout, proc_res.stderr)
396        } else {
397            proc_res.stderr.clone()
398        }
399    }
400
401    fn check_correct_failure_status(&self, proc_res: &ProcRes) {
402        let expected_status = Some(self.props.failure_status.unwrap_or(1));
403        let received_status = proc_res.status.code();
404
405        if expected_status != received_status {
406            self.fatal_proc_rec(
407                &format!(
408                    "Error: expected failure status ({:?}) but received status {:?}.",
409                    expected_status, received_status
410                ),
411                proc_res,
412            );
413        }
414    }
415
416    /// Runs a [`ArgFileCommand`] and waits for it to finish, then converts its exit
417    /// status and output streams into a [`ProcRes`].
418    ///
419    /// The command might have succeeded or failed; it is the caller's
420    /// responsibility to check the exit status and take appropriate action.
421    ///
422    /// # Panics
423    /// Panics if the command couldn't be executed at all
424    /// (e.g. because the executable could not be found).
425    #[must_use = "caller should check whether the command succeeded"]
426    fn run_command_to_procres(&self, cmd: ArgFileCommand) -> ProcRes {
427        let (mut cmd, _arg_file) = cmd.build().unwrap();
428        let output = cmd
429            .output()
430            .unwrap_or_else(|e| self.fatal(&format!("failed to exec `{cmd:?}` because: {e}")));
431
432        let proc_res = ProcRes {
433            status: output.status,
434            stdout: String::from_utf8(output.stdout).unwrap(),
435            stderr: String::from_utf8(output.stderr).unwrap(),
436            truncated: Truncated::No,
437            cmdline: format!("{cmd:?}"),
438        };
439        self.dump_output(
440            self.config.verbose || !proc_res.status.success(),
441            &cmd.get_program().to_string_lossy(),
442            &proc_res.stdout,
443            &proc_res.stderr,
444        );
445
446        proc_res
447    }
448
449    fn print_source(&self, read_from: ReadFrom, pretty_type: &str) -> ProcRes {
450        let aux_dir = self.aux_output_dir_name();
451        let input: &str = match read_from {
452            ReadFrom::Stdin(_) => "-",
453            ReadFrom::Path => self.testpaths.file.as_str(),
454        };
455
456        let mut rustc = Command::new(&self.config.rustc_path);
457
458        self.build_all_auxiliary(&self.aux_output_dir(), &mut rustc);
459
460        rustc
461            .arg(input)
462            .args(&["-Z", &format!("unpretty={}", pretty_type)])
463            .arg("-Zunstable-options")
464            .args(&["--target", &self.config.target])
465            .arg("-L")
466            .arg(&aux_dir)
467            .arg("-A")
468            .arg("internal_features")
469            .arg(self.edition().to_flag())
470            .args(&self.props.compile_flags)
471            .envs(self.props.rustc_env.clone());
472        self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
473
474        let src = match read_from {
475            ReadFrom::Stdin(src) => Some(src),
476            ReadFrom::Path => None,
477        };
478
479        self.compose_and_run(
480            rustc,
481            self.config.host_compile_lib_path.as_path(),
482            Some(aux_dir.as_path()),
483            src,
484        )
485    }
486
487    fn compare_source(&self, expected: &str, actual: &str) {
488        if expected != actual {
489            self.fatal(&format!(
490                "pretty-printed source does not match expected source\n\
491                 expected:\n\
492                 ------------------------------------------\n\
493                 {}\n\
494                 ------------------------------------------\n\
495                 actual:\n\
496                 ------------------------------------------\n\
497                 {}\n\
498                 ------------------------------------------\n\
499                 diff:\n\
500                 ------------------------------------------\n\
501                 {}\n",
502                expected,
503                actual,
504                write_diff(expected, actual, 3),
505            ));
506        }
507    }
508
509    fn set_revision_flags(&self, cmd: &mut Command) {
510        // Normalize revisions to be lowercase and replace `-`s with `_`s.
511        // Otherwise the `--cfg` flag is not valid.
512        let normalize_revision = |revision: &str| revision.to_lowercase().replace("-", "_");
513
514        if let Some(revision) = self.variant.revision() {
515            let normalized_revision = normalize_revision(revision);
516            let cfg_arg = ["--cfg", &normalized_revision];
517            let arg = format!("--cfg={normalized_revision}");
518            // Handle if compile_flags is length 1
519            let contains_arg =
520                self.props.compile_flags.iter().any(|considered_arg| *considered_arg == arg);
521            let contains_cfg_arg = self.props.compile_flags.windows(2).any(|args| args == cfg_arg);
522            if contains_arg || contains_cfg_arg {
523                error!(
524                    "redundant cfg argument `{normalized_revision}` is already created by the \
525                    revision"
526                );
527                panic!("redundant cfg argument");
528            }
529            if self.config.builtin_cfg_names().contains(&normalized_revision) {
530                error!("revision `{normalized_revision}` collides with a built-in cfg");
531                panic!("revision collides with built-in cfg");
532            }
533            cmd.args(cfg_arg);
534        }
535
536        if !self.props.no_auto_check_cfg {
537            let mut check_cfg = String::with_capacity(25);
538
539            // Generate `cfg(FALSE, REV1, ..., REVN)` (for all possible revisions)
540            //
541            // For compatibility reason we consider the `FALSE` cfg to be expected
542            // since it is extensively used in the testsuite, as well as the `test`
543            // cfg since we have tests that uses it.
544            check_cfg.push_str("cfg(test,FALSE");
545            for revision in &self.props.revisions {
546                check_cfg.push(',');
547                check_cfg.push_str(&normalize_revision(revision));
548            }
549            check_cfg.push(')');
550
551            cmd.args(&["--check-cfg", &check_cfg]);
552        }
553    }
554
555    fn typecheck_source(&self, src: String) -> ProcRes {
556        let mut rustc = Command::new(&self.config.rustc_path);
557
558        let out_dir = self.output_base_name().with_extension("pretty-out");
559        remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| {
560            panic!("failed to remove and recreate output directory `{out_dir}`: {e}")
561        });
562
563        let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
564
565        let aux_dir = self.aux_output_dir_name();
566
567        rustc
568            .arg("-")
569            .arg("-Zno-codegen")
570            .arg("-Zunstable-options")
571            .arg("--out-dir")
572            .arg(&out_dir)
573            .arg(&format!("--target={}", target))
574            .arg("-L")
575            // FIXME(jieyouxu): this search path seems questionable. Is this intended for
576            // `rust_test_helpers` in ui tests?
577            .arg(&self.config.build_test_suite_root)
578            .arg("-L")
579            .arg(aux_dir)
580            .arg("-A")
581            .arg("internal_features");
582        self.set_revision_flags(&mut rustc);
583        self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
584        rustc.arg(self.edition().to_flag());
585        rustc.args(&self.props.compile_flags);
586
587        self.compose_and_run_compiler(rustc, Some(src))
588    }
589
590    fn maybe_add_external_args(&self, cmd: &mut Command, args: &Vec<String>) {
591        // Filter out the arguments that should not be added by runtest here.
592        //
593        // Notable use-cases are: do not add our optimisation flag if
594        // `compile-flags: -Copt-level=x` and similar for debug-info level as well.
595        const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", /*-C<space>*/ "opt-level="];
596        const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", /*-C<space>*/ "debuginfo="];
597
598        // FIXME: ideally we would "just" check the `cmd` itself, but it does not allow inspecting
599        // its arguments. They need to be collected separately. For now I cannot be bothered to
600        // implement this the "right" way.
601        let have_opt_flag =
602            self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
603        let have_debug_flag = self
604            .props
605            .compile_flags
606            .iter()
607            .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
608
609        for arg in args {
610            if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
611                continue;
612            }
613            if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
614                continue;
615            }
616            cmd.arg(arg);
617        }
618    }
619
620    /// Check `error-pattern` and `regex-error-pattern` directives.
621    fn check_all_error_patterns(&self, output_to_check: &str, proc_res: &ProcRes) {
622        let mut missing_patterns: Vec<String> = Vec::new();
623        self.check_error_patterns(output_to_check, &mut missing_patterns);
624        self.check_regex_error_patterns(output_to_check, proc_res, &mut missing_patterns);
625
626        if missing_patterns.is_empty() {
627            return;
628        }
629
630        if missing_patterns.len() == 1 {
631            self.fatal_proc_rec(
632                &format!("error pattern '{}' not found!", missing_patterns[0]),
633                proc_res,
634            );
635        } else {
636            for pattern in missing_patterns {
637                writeln!(
638                    self.stdout,
639                    "\n{prefix}: error pattern '{pattern}' not found!",
640                    prefix = self.error_prefix()
641                );
642            }
643            self.fatal_proc_rec("multiple error patterns not found", proc_res);
644        }
645    }
646
647    fn check_error_patterns(&self, output_to_check: &str, missing_patterns: &mut Vec<String>) {
648        debug!("check_error_patterns");
649        for pattern in &self.props.error_patterns {
650            if output_to_check.contains(pattern.trim()) {
651                debug!("found error pattern {}", pattern);
652            } else {
653                missing_patterns.push(pattern.to_string());
654            }
655        }
656    }
657
658    fn check_regex_error_patterns(
659        &self,
660        output_to_check: &str,
661        proc_res: &ProcRes,
662        missing_patterns: &mut Vec<String>,
663    ) {
664        debug!("check_regex_error_patterns");
665
666        for pattern in &self.props.regex_error_patterns {
667            let pattern = pattern.trim();
668            let re = match Regex::new(pattern) {
669                Ok(re) => re,
670                Err(err) => {
671                    self.fatal_proc_rec(
672                        &format!("invalid regex error pattern '{}': {:?}", pattern, err),
673                        proc_res,
674                    );
675                }
676            };
677            if re.is_match(output_to_check) {
678                debug!("found regex error pattern {}", pattern);
679            } else {
680                missing_patterns.push(pattern.to_string());
681            }
682        }
683    }
684
685    fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
686        for pat in &self.props.forbid_output {
687            if output_to_check.contains(pat) {
688                self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
689            }
690        }
691    }
692
693    /// Check `//~ KIND message` annotations.
694    fn check_expected_errors(&self, proc_res: &ProcRes) {
695        let expected_errors = load_errors(&self.testpaths.file, self.variant.revision());
696        debug!(
697            "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
698            expected_errors, proc_res.status
699        );
700        if proc_res.status.success() && expected_errors.iter().any(|x| x.kind == ErrorKind::Error) {
701            self.fatal_proc_rec("process did not return an error status", proc_res);
702        }
703
704        if self.props.known_bug {
705            if !expected_errors.is_empty() {
706                self.fatal_proc_rec(
707                    "`known_bug` tests should not have an expected error",
708                    proc_res,
709                );
710            }
711            return;
712        }
713
714        // On Windows, keep all '\' path separators to match the paths reported in the JSON output
715        // from the compiler
716        let diagnostic_file_name = if self.props.remap_src_base {
717            let mut p = Utf8PathBuf::from(FAKE_SRC_BASE);
718            p.push(&self.testpaths.relative_dir);
719            p.push(self.testpaths.file.file_name().unwrap());
720            p.to_string()
721        } else {
722            self.testpaths.file.to_string()
723        };
724
725        // Errors and warnings are always expected, other diagnostics are only expected
726        // if one of them actually occurs in the test.
727        let expected_kinds: HashSet<_> = [ErrorKind::Error, ErrorKind::Warning]
728            .into_iter()
729            .chain(expected_errors.iter().map(|e| e.kind))
730            .collect();
731
732        // Parse the JSON output from the compiler and extract out the messages.
733        let actual_errors = json::parse_output(&diagnostic_file_name, &self.get_output(proc_res))
734            .into_iter()
735            .map(|e| Error { msg: self.normalize_output(&e.msg, &[]), ..e });
736
737        let mut unexpected = Vec::new();
738        let mut unimportant = Vec::new();
739        let mut found = vec![false; expected_errors.len()];
740        for actual_error in actual_errors {
741            for pattern in &self.props.error_patterns {
742                let pattern = pattern.trim();
743                if actual_error.msg.contains(pattern) {
744                    let q = if actual_error.line_num.is_none() { "?" } else { "" };
745                    self.fatal(&format!(
746                        "error pattern '{pattern}' is found in structured \
747                         diagnostics, use `//~{q} {} {pattern}` instead",
748                        actual_error.kind,
749                    ));
750                }
751            }
752
753            let opt_index =
754                expected_errors.iter().enumerate().position(|(index, expected_error)| {
755                    !found[index]
756                        && actual_error.line_num == expected_error.line_num
757                        && actual_error.kind == expected_error.kind
758                        && actual_error.msg.contains(&expected_error.msg)
759                });
760
761            match opt_index {
762                Some(index) => {
763                    // found a match, everybody is happy
764                    assert!(!found[index]);
765                    found[index] = true;
766                }
767
768                None => {
769                    if actual_error.require_annotation
770                        && expected_kinds.contains(&actual_error.kind)
771                        && !self.props.dont_require_annotations.contains(&actual_error.kind)
772                    {
773                        unexpected.push(actual_error);
774                    } else {
775                        unimportant.push(actual_error);
776                    }
777                }
778            }
779        }
780
781        unexpected.sort_by_key(|e| (e.line_num, e.column_num));
782        unimportant.sort_by_key(|e| (e.line_num, e.column_num));
783
784        // `not_found` are sorted because `expected_errors` are sorted as they are read from file
785        // line by line.
786        let mut not_found = Vec::new();
787        // anything not yet found is a problem
788        for (index, expected_error) in expected_errors.iter().enumerate() {
789            if !found[index] {
790                not_found.push(expected_error);
791            }
792        }
793
794        if !unexpected.is_empty() || !not_found.is_empty() {
795            // Emit locations in a format that is short (relative paths) but "clickable" in editors.
796            // Also normalize path separators to `/`.
797            let file_name = self
798                .testpaths
799                .file
800                .strip_prefix(self.config.src_root.as_str())
801                .unwrap_or(&self.testpaths.file)
802                .to_string()
803                .replace(r"\", "/");
804            let line_str = |e: &Error| {
805                let line_num = e.line_num.map_or("?".to_string(), |line_num| line_num.to_string());
806                // `file:?:NUM` may be confusing to editors and unclickable.
807                let opt_col_num = match e.column_num {
808                    Some(col_num) if line_num != "?" => format!(":{col_num}"),
809                    _ => "".to_string(),
810                };
811                format!("{file_name}:{line_num}{opt_col_num}")
812            };
813            let print_error =
814                |e| writeln!(self.stdout, "{}: {}: {}", line_str(e), e.kind, e.msg.cyan());
815            let push_suggestion =
816                |suggestions: &mut Vec<_>, e: &Error, kind, line, msg, color, rank| {
817                    let mut ret = String::new();
818                    if kind {
819                        ret += &format!("{} {}", "with different kind:".color(color), e.kind);
820                    }
821                    if line {
822                        if !ret.is_empty() {
823                            ret.push(' ');
824                        }
825                        ret += &format!("{} {}", "on different line:".color(color), line_str(e));
826                    }
827                    if msg {
828                        if !ret.is_empty() {
829                            ret.push(' ');
830                        }
831                        ret +=
832                            &format!("{} {}", "with different message:".color(color), e.msg.cyan());
833                    }
834                    suggestions.push((ret, rank));
835                };
836            let show_suggestions = |mut suggestions: Vec<_>, prefix: &str, color| {
837                // Only show suggestions with the highest rank.
838                suggestions.sort_by_key(|(_, rank)| *rank);
839                if let Some(&(_, top_rank)) = suggestions.first() {
840                    for (suggestion, rank) in suggestions {
841                        if rank == top_rank {
842                            writeln!(self.stdout, "  {} {suggestion}", prefix.color(color));
843                        }
844                    }
845                }
846            };
847
848            // Fuzzy matching quality:
849            // - message and line / message and kind - great, suggested
850            // - only message - good, suggested
851            // - known line and kind - ok, suggested
852            // - only known line - meh, but suggested
853            // - others are not worth suggesting
854            if !unexpected.is_empty() {
855                writeln!(
856                    self.stdout,
857                    "\n{prefix}: {n} diagnostics reported in rustc output but not expected in test file",
858                    prefix = self.error_prefix(),
859                    n = unexpected.len(),
860                );
861                for error in &unexpected {
862                    print_error(error);
863                    let mut suggestions = Vec::new();
864                    for candidate in &not_found {
865                        let kind_mismatch = candidate.kind != error.kind;
866                        let mut push_red_suggestion = |line, msg, rank| {
867                            push_suggestion(
868                                &mut suggestions,
869                                candidate,
870                                kind_mismatch,
871                                line,
872                                msg,
873                                Color::Red,
874                                rank,
875                            )
876                        };
877                        if error.msg.contains(&candidate.msg) {
878                            push_red_suggestion(candidate.line_num != error.line_num, false, 0);
879                        } else if candidate.line_num.is_some()
880                            && candidate.line_num == error.line_num
881                        {
882                            push_red_suggestion(false, true, if kind_mismatch { 2 } else { 1 });
883                        }
884                    }
885
886                    show_suggestions(suggestions, "expected", Color::Red);
887                }
888            }
889            if !not_found.is_empty() {
890                writeln!(
891                    self.stdout,
892                    "\n{prefix}: {n} diagnostics expected in test file but not reported in rustc output",
893                    prefix = self.error_prefix(),
894                    n = not_found.len(),
895                );
896
897                // FIXME: Ideally, we should check this at the place where we actually parse error annotations.
898                // it's better to use (negated) heuristic inside normalize_output if possible
899                if let Some(human_format) = self.props.compile_flags.iter().find(|flag| {
900                    // `human`, `human-unicode`, `short` will not generate JSON output
901                    flag.contains("error-format")
902                        && (flag.contains("short") || flag.contains("human"))
903                }) {
904                    let msg = format!(
905                        "tests with compile flag `{}` should not have error annotations such as `//~ ERROR`",
906                        human_format
907                    ).color(Color::Red);
908                    writeln!(self.stdout, "{}", msg);
909                }
910
911                for error in &not_found {
912                    print_error(error);
913                    let mut suggestions = Vec::new();
914                    for candidate in unexpected.iter().chain(&unimportant) {
915                        let kind_mismatch = candidate.kind != error.kind;
916                        let mut push_green_suggestion = |line, msg, rank| {
917                            push_suggestion(
918                                &mut suggestions,
919                                candidate,
920                                kind_mismatch,
921                                line,
922                                msg,
923                                Color::Green,
924                                rank,
925                            )
926                        };
927                        if candidate.msg.contains(&error.msg) {
928                            push_green_suggestion(candidate.line_num != error.line_num, false, 0);
929                        } else if candidate.line_num.is_some()
930                            && candidate.line_num == error.line_num
931                        {
932                            push_green_suggestion(false, true, if kind_mismatch { 2 } else { 1 });
933                        }
934                    }
935
936                    show_suggestions(suggestions, "reported", Color::Green);
937                }
938            }
939            panic!(
940                "errors differ from expected\nstatus: {}\ncommand: {}\n",
941                proc_res.status, proc_res.cmdline
942            );
943        }
944    }
945
946    fn compile_test(&self, will_execute: WillExecute, emit: Emit) -> ProcRes {
947        self.compile_test_general(will_execute, emit, Vec::new())
948    }
949
950    fn compile_test_general(
951        &self,
952        will_execute: WillExecute,
953        emit: Emit,
954        passes: Vec<String>,
955    ) -> ProcRes {
956        let compiler_kind = self.compiler_kind_for_non_aux();
957
958        // Only use `make_exe_name` when the test ends up being executed.
959        let output_file = match will_execute {
960            WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
961            WillExecute::No | WillExecute::Disabled => {
962                TargetLocation::ThisDirectory(self.output_base_dir())
963            }
964        };
965
966        let allow_unused = match self.config.mode {
967            TestMode::Ui => {
968                // UI tests tend to have tons of unused code as
969                // it's just testing various pieces of the compile, but we don't
970                // want to actually assert warnings about all this code. Instead
971                // let's just ignore unused code warnings by defaults and tests
972                // can turn it back on if needed.
973                if compiler_kind == CompilerKind::Rustc
974                    // Note that we use the declared pass mode here as we don't want
975                    // to set unused to allow if we've overridden the pass mode
976                    // via command line flags.
977                    // FIXME(Zalathar): We should probably also warn in run-fail/crash
978                    // tests, but that requires changes to some existing tests.
979                    && self.props.pass_fail_mode != Some(PassFailMode::RunPass)
980                {
981                    AllowUnused::Yes
982                } else {
983                    AllowUnused::No
984                }
985            }
986            TestMode::Incremental => AllowUnused::Yes,
987            _ => AllowUnused::No,
988        };
989
990        let rustc = self.make_compile_args(
991            compiler_kind,
992            &self.testpaths.file,
993            output_file,
994            emit,
995            allow_unused,
996            LinkToAux::Yes,
997            self.edition(),
998            passes,
999        );
1000
1001        self.compose_and_run_compiler(rustc, None)
1002    }
1003
1004    /// `root_out_dir` and `root_testpaths` refer to the parameters of the actual test being run.
1005    /// Auxiliaries, no matter how deep, have the same root_out_dir and root_testpaths.
1006    fn document(&self, root_out_dir: &Utf8Path, kind: DocKind) -> ProcRes {
1007        self.document_inner(&self.testpaths.file, root_out_dir, kind)
1008    }
1009
1010    /// Like `document`, but takes an explicit `file_to_doc` argument so that
1011    /// it can also be used for documenting auxiliaries, in addition to
1012    /// documenting the main test file.
1013    fn document_inner(
1014        &self,
1015        file_to_doc: &Utf8Path,
1016        root_out_dir: &Utf8Path,
1017        kind: DocKind,
1018    ) -> ProcRes {
1019        if self.props.build_aux_docs {
1020            assert_eq!(kind, DocKind::Html, "build-aux-docs only make sense for html output");
1021
1022            for rel_ab in &self.props.aux.builds {
1023                let aux_path = self.resolve_aux_path(rel_ab);
1024                let props_for_aux =
1025                    self.props.from_aux_file(&aux_path, self.variant.revision(), self.config);
1026                let aux_cx = TestCx {
1027                    config: self.config,
1028                    stdout: self.stdout,
1029                    stderr: self.stderr,
1030                    props: &props_for_aux,
1031                    testpaths: self.testpaths,
1032                    variant: self.variant,
1033                };
1034                // Create the directory for the stdout/stderr files.
1035                create_dir_all(aux_cx.output_base_dir()).unwrap();
1036                let auxres = aux_cx.document_inner(&aux_path, &root_out_dir, kind);
1037                if !auxres.status.success() {
1038                    return auxres;
1039                }
1040            }
1041        }
1042
1043        let aux_dir = self.aux_output_dir_name();
1044
1045        let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path not passed");
1046
1047        // actual --out-dir given to the auxiliary or test, as opposed to the root out dir for the entire
1048        // test
1049        let out_dir: Cow<'_, Utf8Path> = if self.props.unique_doc_out_dir {
1050            let file_name = file_to_doc.file_stem().expect("file name should not be empty");
1051            let out_dir = Utf8PathBuf::from_iter([
1052                root_out_dir,
1053                Utf8Path::new("docs"),
1054                Utf8Path::new(file_name),
1055                Utf8Path::new("doc"),
1056            ]);
1057            create_dir_all(&out_dir).unwrap();
1058            Cow::Owned(out_dir)
1059        } else {
1060            Cow::Borrowed(root_out_dir)
1061        };
1062
1063        let mut rustdoc = Command::new(rustdoc_path);
1064        let current_dir = self.output_base_dir();
1065        rustdoc.current_dir(current_dir);
1066        rustdoc
1067            .arg("-L")
1068            .arg(self.config.target_run_lib_path.as_path())
1069            .arg("-L")
1070            .arg(aux_dir)
1071            .arg("-o")
1072            .arg(out_dir.as_ref())
1073            .arg("--deny")
1074            .arg("warnings")
1075            .arg(file_to_doc)
1076            .arg("-A")
1077            .arg("internal_features")
1078            // FIXME(#160895): While the new solver is enabled by default on nightly,
1079            // we don't want to use it in our tests for now.
1080            .arg("-Znext-solver=coherence")
1081            .arg(self.edition().to_flag())
1082            .args(&self.props.compile_flags)
1083            .args(&self.props.doc_flags);
1084
1085        match kind {
1086            DocKind::Html => {
1087                if self.props.use_rustdoc_cci_doc_meta_merge {
1088                    rustdoc.arg("--write-doc-meta-dir").arg(out_dir.as_ref().join("doc.meta"));
1089                }
1090            }
1091            DocKind::Json => {
1092                rustdoc.arg("--output-format").arg("json");
1093            }
1094        }
1095
1096        // Both JSON output and `--disable-minification` are unstable rustdoc options.
1097        if matches!(kind, DocKind::Json)
1098            || self.config.disable_minification
1099            || self.props.use_rustdoc_cci_doc_meta_merge
1100        {
1101            rustdoc.arg("-Zunstable-options");
1102        }
1103        if self.config.disable_minification {
1104            rustdoc.arg("--disable-minification");
1105        }
1106
1107        if let Some(ref linker) = self.config.target_linker {
1108            rustdoc.arg(format!("-Clinker={}", linker));
1109        }
1110
1111        let docres = self.compose_and_run_compiler(rustdoc, None);
1112        if !docres.status.success() {
1113            return docres;
1114        }
1115        if kind == DocKind::Html && self.props.use_rustdoc_cci_doc_meta_merge {
1116            let mut rustdoc_merge = Command::new(rustdoc_path);
1117            let current_dir = self.output_base_dir();
1118            rustdoc_merge.current_dir(current_dir);
1119            rustdoc_merge
1120                .arg("-o")
1121                .arg(out_dir.as_ref())
1122                .arg(self.edition().to_flag())
1123                .args(&self.props.compile_flags)
1124                .args(&self.props.doc_flags)
1125                .arg("--read-doc-meta-dir")
1126                .arg(out_dir.as_ref().join("doc.meta"))
1127                .arg("-Zunstable-options");
1128            if self.config.disable_minification {
1129                rustdoc_merge.arg("--disable-minification");
1130            }
1131            let docmerge = self.compose_and_run_compiler(rustdoc_merge, None);
1132            if !docmerge.status.success() {
1133                return docmerge;
1134            }
1135        }
1136        docres
1137    }
1138
1139    fn exec_compiled_test(&self) -> ProcRes {
1140        self.exec_compiled_test_general(&[], true)
1141    }
1142
1143    fn exec_compiled_test_general(
1144        &self,
1145        env_extra: &[(&str, &str)],
1146        delete_after_success: bool,
1147    ) -> ProcRes {
1148        let prepare_env = |cmd: &mut Command| {
1149            for (key, val) in &self.props.exec_env {
1150                cmd.env(key, val);
1151            }
1152            for (key, val) in env_extra {
1153                cmd.env(key, val);
1154            }
1155
1156            for key in &self.props.unset_exec_env {
1157                cmd.env_remove(key);
1158            }
1159        };
1160
1161        let proc_res = match &*self.config.target {
1162            // This is pretty similar to below, we're transforming:
1163            //
1164            // ```text
1165            // program arg1 arg2
1166            // ```
1167            //
1168            // into
1169            //
1170            // ```text
1171            // remote-test-client run program 2 support-lib.so support-lib2.so arg1 arg2
1172            // ```
1173            //
1174            // The test-client program will upload `program` to the emulator along with all other
1175            // support libraries listed (in this case `support-lib.so` and `support-lib2.so`. It
1176            // will then execute the program on the emulator with the arguments specified (in the
1177            // environment we give the process) and then report back the same result.
1178            _ if self.config.remote_test_client.is_some() => {
1179                let aux_dir = self.aux_output_dir_name();
1180                let ProcArgs { prog, args } = self.make_run_args();
1181                let mut support_libs = Vec::new();
1182                if let Ok(entries) = aux_dir.read_dir() {
1183                    for entry in entries {
1184                        let entry = entry.unwrap();
1185                        if !entry.path().is_file() {
1186                            continue;
1187                        }
1188                        support_libs.push(entry.path());
1189                    }
1190                }
1191                let mut test_client =
1192                    Command::new(self.config.remote_test_client.as_ref().unwrap());
1193                test_client
1194                    .args(&["run", &support_libs.len().to_string()])
1195                    .arg(&prog)
1196                    .args(support_libs)
1197                    .args(args);
1198
1199                prepare_env(&mut test_client);
1200
1201                self.compose_and_run(
1202                    test_client,
1203                    self.config.target_run_lib_path.as_path(),
1204                    Some(aux_dir.as_path()),
1205                    None,
1206                )
1207            }
1208            _ if self.config.target.contains("vxworks") => {
1209                let aux_dir = self.aux_output_dir_name();
1210                let ProcArgs { prog, args } = self.make_run_args();
1211                let mut wr_run = Command::new("wr-run");
1212                wr_run.args(&[&prog]).args(args);
1213
1214                prepare_env(&mut wr_run);
1215
1216                self.compose_and_run(
1217                    wr_run,
1218                    self.config.target_run_lib_path.as_path(),
1219                    Some(aux_dir.as_path()),
1220                    None,
1221                )
1222            }
1223            _ => {
1224                let aux_dir = self.aux_output_dir_name();
1225                let ProcArgs { prog, args } = self.make_run_args();
1226                let mut program = Command::new(&prog);
1227                program.args(args).current_dir(&self.output_base_dir());
1228
1229                prepare_env(&mut program);
1230
1231                self.compose_and_run(
1232                    program,
1233                    self.config.target_run_lib_path.as_path(),
1234                    Some(aux_dir.as_path()),
1235                    None,
1236                )
1237            }
1238        };
1239
1240        if delete_after_success && proc_res.status.success() {
1241            // delete the executable after running it to save space.
1242            // it is ok if the deletion failed.
1243            let _ = fs::remove_file(self.make_exe_name());
1244        }
1245
1246        proc_res
1247    }
1248
1249    /// For each `aux-build: foo/bar` annotation, we check to find the file in an `auxiliary`
1250    /// directory relative to the test itself (not any intermediate auxiliaries).
1251    fn resolve_aux_path(&self, relative_aux_path: &str) -> Utf8PathBuf {
1252        let aux_path = self
1253            .testpaths
1254            .file
1255            .parent()
1256            .expect("test file path has no parent")
1257            .join("auxiliary")
1258            .join(relative_aux_path);
1259        if !aux_path.exists() {
1260            self.fatal(&format!(
1261                "auxiliary source file `{relative_aux_path}` not found at `{aux_path}`"
1262            ));
1263        }
1264
1265        aux_path
1266    }
1267
1268    fn is_vxworks_pure_static(&self) -> bool {
1269        if self.config.target.contains("vxworks") {
1270            match env::var("RUST_VXWORKS_TEST_DYLINK") {
1271                Ok(s) => s != "1",
1272                _ => true,
1273            }
1274        } else {
1275            false
1276        }
1277    }
1278
1279    fn is_vxworks_pure_dynamic(&self) -> bool {
1280        self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1281    }
1282
1283    fn has_aux_dir(&self) -> bool {
1284        !self.props.aux.builds.is_empty()
1285            || !self.props.aux.crates.is_empty()
1286            || !self.props.aux.proc_macros.is_empty()
1287            || !self.props.aux.lints.is_empty()
1288    }
1289
1290    fn aux_output_dir(&self) -> Utf8PathBuf {
1291        let aux_dir = self.aux_output_dir_name();
1292
1293        if !self.props.aux.builds.is_empty() {
1294            remove_and_create_dir_all(&aux_dir).unwrap_or_else(|e| {
1295                panic!("failed to remove and recreate output directory `{aux_dir}`: {e}")
1296            });
1297        }
1298
1299        if !self.props.aux.bins.is_empty() {
1300            let aux_bin_dir = self.aux_bin_output_dir_name();
1301            remove_and_create_dir_all(&aux_dir).unwrap_or_else(|e| {
1302                panic!("failed to remove and recreate output directory `{aux_dir}`: {e}")
1303            });
1304            remove_and_create_dir_all(&aux_bin_dir).unwrap_or_else(|e| {
1305                panic!("failed to remove and recreate output directory `{aux_bin_dir}`: {e}")
1306            });
1307        }
1308
1309        aux_dir
1310    }
1311
1312    fn build_all_auxiliary(&self, aux_dir: &Utf8Path, rustc: &mut Command) {
1313        for rel_ab in &self.props.aux.builds {
1314            self.build_auxiliary(rel_ab, &aux_dir, None);
1315        }
1316
1317        for rel_ab in &self.props.aux.bins {
1318            self.build_auxiliary(rel_ab, &aux_dir, Some(AuxType::Bin));
1319        }
1320
1321        for lint in &self.props.aux.lints {
1322            self.build_auxiliary(lint, &aux_dir, Some(AuxType::Lint));
1323        }
1324
1325        let path_to_crate_name = |path: &str| -> String {
1326            path.rsplit_once('/')
1327                .map_or(path, |(_, tail)| tail)
1328                .trim_end_matches(".rs")
1329                .replace('-', "_")
1330        };
1331
1332        let lint_lib_paths = self
1333            .props
1334            .aux
1335            .lints
1336            .iter()
1337            .filter_map(|p| {
1338                if let Some(lib_name) = get_lib_name(
1339                    &path_to_crate_name(p),
1340                    AuxType::Lint,
1341                    self.config.wasm_proc_macros,
1342                ) {
1343                    Some(aux_dir.join(lib_name).to_string())
1344                } else {
1345                    None
1346                }
1347            })
1348            .collect::<Vec<_>>();
1349        if !lint_lib_paths.is_empty() {
1350            rustc.env(
1351                "COMPILETEST_LINT_DRIVER_PATHS",
1352                std::env::join_paths(lint_lib_paths).unwrap(),
1353            );
1354        }
1355
1356        let add_extern = |rustc: &mut Command,
1357                          extern_modifiers: Option<&str>,
1358                          aux_name: &str,
1359                          aux_path: &str,
1360                          aux_type: AuxType| {
1361            let lib_name =
1362                get_lib_name(&path_to_crate_name(aux_path), aux_type, self.config.wasm_proc_macros);
1363            if let Some(lib_name) = lib_name {
1364                let modifiers_and_name = match extern_modifiers {
1365                    Some(modifiers) => format!("{modifiers}:{aux_name}"),
1366                    None => aux_name.to_string(),
1367                };
1368                rustc.arg("--extern").arg(format!("{modifiers_and_name}={aux_dir}/{lib_name}"));
1369            }
1370        };
1371
1372        for AuxCrate { extern_modifiers, name, path } in &self.props.aux.crates {
1373            let aux_type = self.build_auxiliary(&path, &aux_dir, None);
1374            add_extern(rustc, extern_modifiers.as_deref(), name, path, aux_type);
1375        }
1376
1377        for proc_macro in &self.props.aux.proc_macros {
1378            self.build_auxiliary(&proc_macro.path, &aux_dir, Some(AuxType::ProcMacro));
1379            let crate_name = path_to_crate_name(&proc_macro.path);
1380            add_extern(
1381                rustc,
1382                proc_macro.extern_modifiers.as_deref(),
1383                &crate_name,
1384                &proc_macro.path,
1385                AuxType::ProcMacro,
1386            );
1387        }
1388
1389        // Build any `//@ aux-codegen-backend`, and pass the resulting library
1390        // to `-Zcodegen-backend` when compiling the test file.
1391        if let Some(aux_file) = &self.props.aux.codegen_backend {
1392            let aux_type = self.build_auxiliary(aux_file, aux_dir, None);
1393            if let Some(lib_name) = get_lib_name(
1394                aux_file.trim_end_matches(".rs"),
1395                aux_type,
1396                self.config.wasm_proc_macros,
1397            ) {
1398                let lib_path = aux_dir.join(&lib_name);
1399                rustc.arg(format!("-Zcodegen-backend={}", lib_path));
1400            }
1401        }
1402    }
1403
1404    /// `root_testpaths` refers to the path of the original test. the auxiliary and the test with an
1405    /// aux-build have the same `root_testpaths`.
1406    fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1407        if self.props.add_minicore {
1408            let minicore_path = self.build_minicore();
1409            rustc.arg("--extern");
1410            rustc.arg(&format!("minicore={}", minicore_path));
1411        }
1412
1413        let aux_dir = self.aux_output_dir();
1414        self.build_all_auxiliary(&aux_dir, &mut rustc);
1415
1416        rustc.envs(self.props.rustc_env.clone());
1417        self.props.unset_rustc_env.iter().fold(&mut rustc, Command::env_remove);
1418        self.compose_and_run(
1419            rustc,
1420            self.config.host_compile_lib_path.as_path(),
1421            Some(aux_dir.as_path()),
1422            input,
1423        )
1424    }
1425
1426    /// Builds `minicore`. Returns the path to the minicore rlib within the base test output
1427    /// directory.
1428    fn build_minicore(&self) -> Utf8PathBuf {
1429        let output_file_path = self.output_base_dir().join("libminicore.rlib");
1430
1431        // We want to inherit *all* `TestProps` from the test that added minicore *except*
1432        // for the edition which we want to keep fixed to the latest stable one.
1433        let mut rustc = self.make_compile_args(
1434            CompilerKind::Rustc,
1435            &self.config.minicore_path,
1436            TargetLocation::ThisFile(output_file_path.clone()),
1437            Emit::None,
1438            AllowUnused::Yes,
1439            LinkToAux::No,
1440            Edition::LATEST_STABLE,
1441            vec![],
1442        );
1443
1444        rustc.args(&["--crate-type", "rlib"]);
1445        rustc.arg("-Cpanic=abort");
1446        rustc.arg("--check-cfg=cfg(target_has_reliable_f16b)");
1447        rustc.args(self.props.minicore_compile_flags.clone());
1448
1449        let res =
1450            self.compose_and_run(rustc, self.config.host_compile_lib_path.as_path(), None, None);
1451        if !res.status.success() {
1452            self.fatal_proc_rec(
1453                &format!("auxiliary build of {} failed to compile: ", self.config.minicore_path),
1454                &res,
1455            );
1456        }
1457
1458        output_file_path
1459    }
1460
1461    /// Builds an aux dependency.
1462    ///
1463    /// If `aux_type` is `None`, then this will determine the aux-type automatically.
1464    fn build_auxiliary(
1465        &self,
1466        source_path: &str,
1467        aux_dir: &Utf8Path,
1468        aux_type: Option<AuxType>,
1469    ) -> AuxType {
1470        let aux_path = self.resolve_aux_path(source_path);
1471        let mut aux_props =
1472            self.props.from_aux_file(&aux_path, self.variant.revision(), self.config);
1473        if aux_type == Some(AuxType::ProcMacro) {
1474            if self.config.wasm_proc_macros {
1475                aux_props.compile_flags.push("--target=wasm32-wasip2".to_owned());
1476                // Override any earlier linkers for now, otherwise we fail to build since compiletest
1477                // thinks we're building for a different target and passes its linker (if one is
1478                // configured).
1479                //
1480                // wasm32-wasip2 should in principle always be able to link with wasm-component-ld +
1481                // wasm-ld. This does mean that rust.lld needs to be enabled to build wasm-ld wrapper
1482                // around rust-lld.
1483                aux_props.compile_flags.push("-Clinker=wasm-component-ld".to_owned());
1484                aux_props.compile_flags.push(format!(
1485                    "-Clink-arg=--wasm-ld-path={}",
1486                    self.config
1487                        .sysroot_base
1488                        .join("lib/rustlib")
1489                        .join(&self.config.host)
1490                        .join("bin/gcc-ld/wasm-ld")
1491                ));
1492            } else {
1493                aux_props.force_host = true;
1494            }
1495        } else if aux_type == Some(AuxType::Lint) {
1496            aux_props.force_host = true;
1497        }
1498        let mut aux_dir = aux_dir.to_path_buf();
1499        if aux_type == Some(AuxType::Bin) {
1500            // On unix, the binary of `auxiliary/foo.rs` will be named
1501            // `auxiliary/foo` which clashes with the _dir_ `auxiliary/foo`, so
1502            // put bins in a `bin` subfolder.
1503            aux_dir.push("bin");
1504        }
1505        let aux_output = TargetLocation::ThisDirectory(aux_dir.clone());
1506        let aux_cx = TestCx {
1507            config: self.config,
1508            stdout: self.stdout,
1509            stderr: self.stderr,
1510            props: &aux_props,
1511            testpaths: self.testpaths,
1512            variant: self.variant,
1513        };
1514        // Create the directory for the stdout/stderr files.
1515        create_dir_all(aux_cx.output_base_dir()).unwrap();
1516        let mut aux_rustc = aux_cx.make_compile_args(
1517            // Always use `rustc` for aux crates, even in rustdoc tests.
1518            CompilerKind::Rustc,
1519            &aux_path,
1520            aux_output,
1521            Emit::None,
1522            AllowUnused::No,
1523            LinkToAux::No,
1524            aux_cx.edition(),
1525            Vec::new(),
1526        );
1527        aux_cx.build_all_auxiliary(&aux_dir, &mut aux_rustc);
1528
1529        aux_rustc.envs(aux_props.rustc_env.clone());
1530        for key in &aux_props.unset_rustc_env {
1531            aux_rustc.env_remove(key);
1532        }
1533
1534        let (aux_type, crate_type) = if aux_type == Some(AuxType::Bin) {
1535            (AuxType::Bin, Some("bin"))
1536        } else if aux_type == Some(AuxType::ProcMacro) {
1537            (AuxType::ProcMacro, Some("proc-macro"))
1538        } else if aux_type == Some(AuxType::Lint) {
1539            (AuxType::Lint, Some("dylib"))
1540        } else if aux_type.is_some() {
1541            panic!("aux_type {aux_type:?} not expected");
1542        } else if aux_props.no_prefer_dynamic {
1543            (AuxType::Lib, None)
1544        } else if self.config.target.contains("emscripten")
1545            || (self.config.target.contains("musl")
1546                && !aux_props.force_host
1547                && !self.config.host.contains("musl"))
1548            || self.config.target.contains("wasm32")
1549            || self.config.target.contains("nvptx")
1550            || self.is_vxworks_pure_static()
1551            || self.config.target.contains("bpf")
1552            || !self.config.target_cfg().dynamic_linking
1553            || matches!(self.config.mode, TestMode::CoverageMap | TestMode::CoverageRun)
1554        {
1555            // We primarily compile all auxiliary libraries as dynamic libraries
1556            // to avoid code size bloat and large binaries as much as possible
1557            // for the test suite (otherwise including libstd statically in all
1558            // executables takes up quite a bit of space).
1559            //
1560            // For targets like MUSL or Emscripten, however, there is no support for
1561            // dynamic libraries so we just go back to building a normal library. Note,
1562            // however, that for MUSL if the library is built with `force_host` then
1563            // it's ok to be a dylib as the host should always support dylibs.
1564            //
1565            // Coverage tests want static linking by default so that coverage
1566            // mappings in auxiliary libraries can be merged into the final
1567            // executable.
1568            (AuxType::Lib, Some("lib"))
1569        } else {
1570            (AuxType::Dylib, Some("dylib"))
1571        };
1572
1573        if let Some(crate_type) = crate_type {
1574            aux_rustc.args(&["--crate-type", crate_type]);
1575        }
1576
1577        if aux_type == AuxType::ProcMacro {
1578            // For convenience, but this only works on 2018.
1579            aux_rustc.args(&["--extern", "proc_macro"]);
1580        }
1581
1582        aux_rustc.arg("-L").arg(&aux_dir);
1583
1584        if aux_props.add_minicore {
1585            let minicore_path = self.build_minicore();
1586            aux_rustc.arg("--extern");
1587            aux_rustc.arg(&format!("minicore={}", minicore_path));
1588        }
1589
1590        let auxres = aux_cx.compose_and_run(
1591            aux_rustc,
1592            aux_cx.config.host_compile_lib_path.as_path(),
1593            Some(aux_dir.as_path()),
1594            None,
1595        );
1596        if !auxres.status.success() {
1597            self.fatal_proc_rec(
1598                &format!("auxiliary build of {aux_path} failed to compile: "),
1599                &auxres,
1600            );
1601        }
1602        aux_type
1603    }
1604
1605    fn read2_abbreviated(&self, child: Child) -> (Output, Truncated) {
1606        let mut filter_paths_from_len = Vec::new();
1607        let mut add_path = |path: &Utf8Path| {
1608            let path = path.to_string();
1609            let windows = path.replace("\\", "\\\\");
1610            if windows != path {
1611                filter_paths_from_len.push(windows);
1612            }
1613            filter_paths_from_len.push(path);
1614        };
1615
1616        // List of paths that will not be measured when determining whether the output is larger
1617        // than the output truncation threshold.
1618        //
1619        // Note: avoid adding a subdirectory of an already filtered directory here, otherwise the
1620        // same slice of text will be double counted and the truncation might not happen.
1621        add_path(&self.config.src_test_suite_root);
1622        add_path(&self.config.build_test_suite_root);
1623
1624        read2_abbreviated(child, &filter_paths_from_len).expect("failed to read output")
1625    }
1626
1627    fn compose_and_run(
1628        &self,
1629        mut command: Command,
1630        lib_path: &Utf8Path,
1631        aux_path: Option<&Utf8Path>,
1632        input: Option<String>,
1633    ) -> ProcRes {
1634        command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
1635
1636        let lint_driver_path =
1637            self.config.rustc_lint_driver_lib_path.as_ref().map(Utf8PathBuf::as_path);
1638        // Need to be sure to put both the lib_path and the aux path in the dylib
1639        // search path for the child.
1640        add_dylib_path(
1641            &mut command,
1642            iter::once(lib_path)
1643                .chain(aux_path)
1644                .chain(lint_driver_path.filter(|_| !self.props.aux.lints.is_empty())),
1645        );
1646
1647        let cmdline = format!("{command:?}");
1648        self.logv(format_args!("executing {cmdline}"));
1649
1650        let mut child = disable_error_reporting(|| command.spawn())
1651            .unwrap_or_else(|e| panic!("failed to exec `{command:?}`: {e:?}"));
1652        if let Some(input) = input {
1653            child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
1654        }
1655
1656        let (Output { status, stdout, stderr }, truncated) = self.read2_abbreviated(child);
1657
1658        let result = ProcRes {
1659            status,
1660            stdout: String::from_utf8_lossy(&stdout).into_owned(),
1661            stderr: String::from_utf8_lossy(&stderr).into_owned(),
1662            truncated,
1663            cmdline,
1664        };
1665
1666        self.dump_output(
1667            self.config.verbose || (!result.status.success() && self.config.mode != TestMode::Ui),
1668            &command.get_program().to_string_lossy(),
1669            &result.stdout,
1670            &result.stderr,
1671        );
1672
1673        result
1674    }
1675
1676    /// Choose a compiler kind (rustc or rustdoc) for compiling test files,
1677    /// based on the test suite being tested.
1678    fn compiler_kind_for_non_aux(&self) -> CompilerKind {
1679        if !self.props.aux.lints.is_empty() {
1680            return CompilerKind::LintDriver;
1681        }
1682        match self.config.suite {
1683            TestSuite::RustdocJs | TestSuite::RustdocJson | TestSuite::RustdocUi => {
1684                CompilerKind::Rustdoc
1685            }
1686
1687            // Exhaustively match all other suites.
1688            // Note that some suites never actually use this method, so the
1689            // return value for those suites is not necessarily meaningful.
1690            TestSuite::AssemblyGcc
1691            | TestSuite::AssemblyLlvm
1692            | TestSuite::BuildStd
1693            | TestSuite::CodegenLlvm
1694            | TestSuite::CodegenUnits
1695            | TestSuite::Coverage
1696            | TestSuite::CoverageRunRustdoc
1697            | TestSuite::Crashes
1698            | TestSuite::Debuginfo
1699            | TestSuite::Incremental
1700            | TestSuite::MirOpt
1701            | TestSuite::Pretty
1702            | TestSuite::RunMake
1703            | TestSuite::RunMakeCargo
1704            | TestSuite::RustdocGui
1705            | TestSuite::RustdocHtml
1706            | TestSuite::RustdocJsStd
1707            | TestSuite::Ui
1708            | TestSuite::UiFullDeps => CompilerKind::Rustc,
1709        }
1710    }
1711
1712    fn make_compile_args(
1713        &self,
1714        compiler_kind: CompilerKind,
1715        input_file: &Utf8Path,
1716        output_file: TargetLocation,
1717        emit: Emit,
1718        allow_unused: AllowUnused,
1719        link_to_aux: LinkToAux,
1720        edition: Edition,
1721        passes: Vec<String>, // Vec of passes under mir-opt test to be dumped
1722    ) -> Command {
1723        // FIXME(Zalathar): We should have a cleaner distinction between
1724        // `rustc` flags, `rustdoc` flags, and flags shared by both.
1725        let mut compiler = match compiler_kind {
1726            CompilerKind::Rustc => Command::new(&self.config.rustc_path),
1727            CompilerKind::Rustdoc => {
1728                Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1729            }
1730            CompilerKind::LintDriver => Command::new(
1731                self.config.rustc_lint_driver_path.as_ref().expect("no rustc lint driver provided"),
1732            ),
1733        };
1734        compiler.arg(input_file);
1735
1736        // Enable wasm proc macros.
1737        if self.config.wasm_proc_macros {
1738            compiler.arg("-Zwasm-proc-macros");
1739        }
1740
1741        // `--disable-minification` is an unstable rustdoc option. Rustdoc UI tests intentionally
1742        // exercise diagnostics for unstable options, so don't enable them for that suite.
1743        if compiler_kind == CompilerKind::Rustdoc
1744            && self.config.disable_minification
1745            && self.config.mode != TestMode::Ui
1746        {
1747            compiler.arg("-Zunstable-options").arg("--disable-minification");
1748        }
1749
1750        // Note: when adding new unstable compile flags here, also update
1751        // `COMPILETEST_UI_SUITE_UNSTABLE_FLAGS`
1752
1753        // Hide libstd sources from ui tests to make sure we generate the stderr
1754        // output that users will see.
1755        // Without this, we may be producing good diagnostics in-tree but users
1756        // will not see half the information.
1757        //
1758        // This also has the benefit of more effectively normalizing output between different
1759        // compilers, so that we don't have to know the `/rustc/$sha` output to normalize after the
1760        // fact.
1761        compiler.arg("-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX");
1762        compiler.arg("-Ztranslate-remapped-path-to-local-path=no");
1763
1764        // Hide Cargo dependency sources from ui tests to make sure the error message doesn't
1765        // change depending on whether $CARGO_HOME is remapped or not. If this is not present,
1766        // when $CARGO_HOME is remapped the source won't be shown, and when it's not remapped the
1767        // source will be shown, causing a blessing hell.
1768        compiler.arg("-Z").arg(format!(
1769            "ignore-directory-in-diagnostics-source-blocks={}",
1770            home::cargo_home().expect("failed to find cargo home").to_str().unwrap()
1771        ));
1772        // Similarly, vendored sources shouldn't be shown when running from a dist tarball.
1773        compiler.arg("-Z").arg(format!(
1774            "ignore-directory-in-diagnostics-source-blocks={}",
1775            self.config.src_root.join("vendor"),
1776        ));
1777
1778        // Optionally prevent default --sysroot if specified in test compile-flags.
1779        //
1780        // FIXME: I feel like this logic is fairly sus.
1781        if !self.props.compile_flags.iter().any(|flag| flag.starts_with("--sysroot"))
1782            && !self.config.host_rustcflags.iter().any(|flag| flag == "--sysroot")
1783        {
1784            if compiler_kind == CompilerKind::LintDriver {
1785                compiler
1786                    .arg("--sysroot")
1787                    .arg(self.config.rustc_lint_driver_sysroot.as_ref().unwrap());
1788            } else {
1789                // In stage 0, make sure we use `stage0-sysroot` instead of the bootstrap sysroot.
1790                compiler.arg("--sysroot").arg(&self.config.sysroot_base);
1791            }
1792        }
1793
1794        // If the provided codegen backend is not LLVM, we need to pass it.
1795        if let Some(ref backend) = self.config.override_codegen_backend {
1796            compiler.arg(format!("-Zcodegen-backend={}", backend));
1797        }
1798
1799        // Optionally prevent default --target if specified in test compile-flags.
1800        let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target"));
1801
1802        if !custom_target {
1803            let target =
1804                if self.props.force_host { &*self.config.host } else { &*self.config.target };
1805
1806            compiler.arg(&format!("--target={}", target));
1807            if target.ends_with(".json") {
1808                // `-Zunstable-options` is necessary when compiletest is running with custom targets
1809                // (such as synthetic targets used to bless mir-opt tests).
1810                compiler.arg("-Zunstable-options");
1811            }
1812        }
1813        self.set_revision_flags(&mut compiler);
1814
1815        if compiler_kind == CompilerKind::Rustc {
1816            if let Some(ref incremental_dir) = self.props.incremental_dir {
1817                compiler.args(&["-C", &format!("incremental={}", incremental_dir)]);
1818                compiler.args(&["-Z", "incremental-verify-ich"]);
1819            }
1820
1821            if self.config.mode == TestMode::CodegenUnits {
1822                compiler.args(&["-Z", "human_readable_cgu_names"]);
1823            }
1824
1825            if self.config.mode == TestMode::DebugInfo && cfg!(target_os = "windows") {
1826                // Prevent debugger processes from creating new console windows.
1827                compiler.args(&["-Z", r#"crate-attr=windows_subsystem="windows""#]);
1828            }
1829        }
1830
1831        if self.config.optimize_tests && compiler_kind == CompilerKind::Rustc {
1832            match self.config.mode {
1833                TestMode::Ui => {
1834                    // If optimize-tests is true we still only want to optimize tests that actually get
1835                    // executed and that don't specify their own optimization levels.
1836                    // Note: aux libs don't have a pass/fail mode, so they won't get optimized
1837                    // unless compile-flags are set in the aux file.
1838                    // FIXME(Zalathar): We could also optimize run-fail/run-crash tests,
1839                    // but it's unclear whether that would be helpful or a waste of time.
1840                    if self.effective_pass_fail_mode() == Some(PassFailMode::RunPass)
1841                        && !self
1842                            .props
1843                            .compile_flags
1844                            .iter()
1845                            .any(|arg| arg == "-O" || arg.contains("opt-level"))
1846                    {
1847                        compiler.arg("-O");
1848                    }
1849                }
1850                TestMode::DebugInfo => { /* debuginfo tests must be unoptimized */ }
1851                TestMode::CoverageMap | TestMode::CoverageRun => {
1852                    // Coverage mappings and coverage reports are affected by
1853                    // optimization level, so they ignore the optimize-tests
1854                    // setting and set an optimization level in their mode's
1855                    // compile flags (below) or in per-test `compile-flags`.
1856                }
1857                _ => {
1858                    compiler.arg("-O");
1859                }
1860            }
1861        }
1862
1863        let set_mir_dump_dir = |rustc: &mut Command| {
1864            let mir_dump_dir = self.output_base_dir();
1865            let mut dir_opt = "-Zdump-mir-dir=".to_string();
1866            dir_opt.push_str(mir_dump_dir.as_str());
1867            debug!("dir_opt: {:?}", dir_opt);
1868            rustc.arg(dir_opt);
1869        };
1870
1871        if !self.config.parallel_frontend_enabled() {
1872            // If the parallel frontend thread count was not specified, we override
1873            // it to 1, because the tested toolchain might have a different default
1874            // value for the frontend thread count, but we want to run tests in
1875            // compiletest with the sequential frontend for now, until we prepare the testing
1876            // infrastructure of all test suites to support potentially non-deterministic order of
1877            // diagnostics.
1878
1879            // We can't set this option if the test already specifies the frontend thread count
1880            // though.
1881            if !self
1882                .props
1883                .compile_flags
1884                .iter()
1885                .any(|flag| flag.contains("-Zthreads") || flag.contains("--jobs-frontend"))
1886            {
1887                compiler.arg("-Zthreads=1");
1888            }
1889        }
1890
1891        match self.config.mode {
1892            TestMode::Incremental => {
1893                // If we are extracting and matching errors in the new
1894                // fashion, then you want JSON mode. Old-skool error
1895                // patterns still match the raw compiler output.
1896                if self.props.error_patterns.is_empty()
1897                    && self.props.regex_error_patterns.is_empty()
1898                {
1899                    compiler.args(&["--error-format", "json"]);
1900                    compiler.args(&["--json", "future-incompat"]);
1901                }
1902                compiler.arg("-Zui-testing");
1903                compiler.arg("-Zdeduplicate-diagnostics=no");
1904            }
1905            TestMode::Ui => {
1906                if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) {
1907                    compiler.args(&["--error-format", "json"]);
1908                    compiler.args(&["--json", "future-incompat"]);
1909                }
1910                compiler.arg("-Ccodegen-units=1");
1911                // Hide line numbers to reduce churn
1912                compiler.arg("-Zui-testing");
1913                compiler.arg("-Zdeduplicate-diagnostics=no");
1914                compiler.arg("-Zwrite-long-types-to-disk=no");
1915                // FIXME: use this for other modes too, for perf?
1916                compiler.arg("-Cstrip=debuginfo");
1917
1918                if self.config.parallel_frontend_enabled() {
1919                    // Currently, we only use multiple threads for the UI test suite,
1920                    // because UI tests can effectively verify the parallel frontend and
1921                    // require minimal modification. The option will later be extended to
1922                    // other test suites.
1923                    compiler.arg(&format!("-Zthreads={}", self.config.parallel_frontend_threads));
1924                }
1925            }
1926            TestMode::MirOpt => {
1927                // We check passes under test to minimize the mir-opt test dump
1928                // if files_for_miropt_test parses the passes, we dump only those passes
1929                // otherwise we conservatively pass -Zdump-mir=all
1930                let zdump_arg = if !passes.is_empty() {
1931                    format!("-Zdump-mir={}", passes.join(" | "))
1932                } else {
1933                    "-Zdump-mir=all".to_string()
1934                };
1935
1936                compiler.args(&[
1937                    "-Copt-level=1",
1938                    &zdump_arg,
1939                    "-Zvalidate-mir",
1940                    "-Zlint-mir",
1941                    "-Zdump-mir-exclude-pass-number",
1942                    "-Zmir-include-spans=false", // remove span comments from NLL MIR dumps
1943                    "--crate-type=rlib",
1944                ]);
1945                if let Some(pass) = &self.props.mir_unit_test {
1946                    compiler
1947                        .args(&["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{}", pass)]);
1948                } else {
1949                    compiler.args(&[
1950                        "-Zmir-opt-level=4",
1951                        "-Zmir-enable-passes=+ReorderBasicBlocks,+ReorderLocals",
1952                    ]);
1953                }
1954
1955                set_mir_dump_dir(&mut compiler);
1956            }
1957            TestMode::CoverageMap => {
1958                compiler.arg("-Cinstrument-coverage");
1959                // These tests only compile to LLVM IR, so they don't need the
1960                // profiler runtime to be present.
1961                compiler.arg("-Zno-profiler-runtime");
1962                // Coverage mappings are sensitive to MIR optimizations, and
1963                // the current snapshots assume `opt-level=2` unless overridden
1964                // by `compile-flags`.
1965                compiler.arg("-Copt-level=2");
1966            }
1967            TestMode::CoverageRun => {
1968                compiler.arg("-Cinstrument-coverage");
1969                // Coverage reports are sometimes sensitive to optimizations,
1970                // and the current snapshots assume `opt-level=2` unless
1971                // overridden by `compile-flags`.
1972                compiler.arg("-Copt-level=2");
1973            }
1974            TestMode::Assembly | TestMode::Codegen => {
1975                compiler.arg("-Cdebug-assertions=no");
1976                // For assembly and codegen tests, we want to use the same order
1977                // of the items of a codegen unit as the source order, so that
1978                // we can compare the output with the source code through filecheck.
1979                compiler.arg("-Zcodegen-source-order");
1980            }
1981            TestMode::Crashes => {
1982                set_mir_dump_dir(&mut compiler);
1983            }
1984            TestMode::CodegenUnits => {
1985                compiler.arg("-Zprint-mono-items");
1986            }
1987            TestMode::Pretty
1988            | TestMode::DebugInfo
1989            | TestMode::RustdocHtml
1990            | TestMode::RustdocJson
1991            | TestMode::RunMake
1992            | TestMode::RustdocJs => {
1993                // do not use JSON output
1994            }
1995        }
1996
1997        if self.props.remap_src_base {
1998            compiler.arg(format!(
1999                "--remap-path-prefix={}={}",
2000                self.config.src_test_suite_root, FAKE_SRC_BASE,
2001            ));
2002        }
2003
2004        if compiler_kind == CompilerKind::Rustc {
2005            match emit {
2006                Emit::None => {}
2007                Emit::Metadata => {
2008                    compiler.args(&["--emit", "metadata"]);
2009                }
2010                Emit::LlvmIr => {
2011                    compiler.args(&["--emit", "llvm-ir"]);
2012                }
2013                Emit::Mir => {
2014                    compiler.args(&["--emit", "mir"]);
2015                }
2016                Emit::Asm => {
2017                    compiler.args(&["--emit", "asm"]);
2018                }
2019                Emit::LinkArgsAsm => {
2020                    compiler.args(&["-Clink-args=--emit=asm"]);
2021                }
2022            }
2023        }
2024
2025        if compiler_kind == CompilerKind::Rustc {
2026            if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() {
2027                // rustc.arg("-g"); // get any backtrace at all on errors
2028            } else if !self.props.no_prefer_dynamic {
2029                compiler.args(&["-C", "prefer-dynamic"]);
2030            }
2031        }
2032
2033        match output_file {
2034            // If the test's compile flags specify an output path with `-o`,
2035            // avoid a compiler warning about `--out-dir` being ignored.
2036            _ if self.props.compile_flags.iter().any(|flag| flag == "-o") => {}
2037            TargetLocation::ThisFile(path) => {
2038                compiler.arg("-o").arg(path);
2039            }
2040            TargetLocation::ThisDirectory(path) => match compiler_kind {
2041                CompilerKind::Rustdoc => {
2042                    // `rustdoc` uses `-o` for the output directory.
2043                    compiler.arg("-o").arg(path);
2044                }
2045                CompilerKind::Rustc | CompilerKind::LintDriver => {
2046                    compiler.arg("--out-dir").arg(path);
2047                }
2048            },
2049        }
2050
2051        // FIXME(#160895): While the new solver is enabled by default on nightly,
2052        // we don't want to use it in our tests for now.
2053        compiler.args(["-Znext-solver=coherence"]);
2054
2055        match self.config.compare_mode {
2056            Some(CompareMode::Polonius) => {
2057                compiler.args(&["-Zpolonius=next"]);
2058            }
2059            Some(CompareMode::NextSolver) => {
2060                compiler.args(&["-Znext-solver"]);
2061            }
2062            Some(CompareMode::SplitDwarf) if self.config.target.contains("windows") => {
2063                compiler.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]);
2064            }
2065            Some(CompareMode::SplitDwarf) => {
2066                compiler.args(&["-Csplit-debuginfo=unpacked"]);
2067            }
2068            Some(CompareMode::SplitDwarfSingle) => {
2069                compiler.args(&["-Csplit-debuginfo=packed"]);
2070            }
2071            None => {}
2072        }
2073
2074        // Add `-A unused` before `config` flags and in-test (`props`) flags, so that they can
2075        // overwrite this.
2076        // Don't allow `unused_attributes` since these are usually actual mistakes, rather than just unused code.
2077        if let AllowUnused::Yes = allow_unused {
2078            compiler.args(&["-A", "unused", "-W", "unused_attributes"]);
2079        }
2080
2081        // Allow tests to use internal and incomplete features.
2082        compiler.args(&["-A", "internal_features"]);
2083        compiler.args(&["-A", "incomplete_features"]);
2084
2085        // Allow tests to have unused parens and braces.
2086        // Add #![deny(unused_parens, unused_braces)] to the test file if you want to
2087        // test that these lints are working.
2088        compiler.args(&["-A", "unused_parens"]);
2089        compiler.args(&["-A", "unused_braces"]);
2090
2091        if self.props.force_host {
2092            self.maybe_add_external_args(&mut compiler, &self.config.host_rustcflags);
2093            if compiler_kind == CompilerKind::Rustc
2094                && let Some(ref linker) = self.config.host_linker
2095            {
2096                compiler.arg(format!("-Clinker={linker}"));
2097            }
2098        } else {
2099            self.maybe_add_external_args(&mut compiler, &self.config.target_rustcflags);
2100            if compiler_kind == CompilerKind::Rustc
2101                && let Some(ref linker) = self.config.target_linker
2102            {
2103                compiler.arg(format!("-Clinker={linker}"));
2104            }
2105        }
2106
2107        // Use dynamic musl for tests because static doesn't allow creating dylibs
2108        if self.config.host.contains("musl") || self.is_vxworks_pure_dynamic() {
2109            compiler.arg("-Ctarget-feature=-crt-static");
2110        }
2111
2112        if let LinkToAux::Yes = link_to_aux {
2113            // if we pass an `-L` argument to a directory that doesn't exist,
2114            // macOS ld emits warnings which disrupt the .stderr files
2115            if self.has_aux_dir() {
2116                compiler.arg("-L").arg(self.aux_output_dir_name());
2117            }
2118        }
2119
2120        // FIXME(jieyouxu): we should report a fatal error or warning if user wrote `-Cpanic=` with
2121        // something that's not `abort` and `-Cforce-unwind-tables` with a value that is not `yes`.
2122        //
2123        // We could apply these last and override any provided flags. That would ensure that the
2124        // build works, but some tests want to exercise that mixing panic modes in specific ways is
2125        // rejected. So we enable aborting panics and unwind tables before adding flags, just to
2126        // change the default.
2127        //
2128        // `minicore` requires `#![no_std]` and `#![no_core]`, which means no unwinding panics.
2129        if self.props.add_minicore {
2130            compiler.arg("-Cpanic=abort");
2131            compiler.arg("-Cforce-unwind-tables=yes");
2132        }
2133
2134        compiler.arg(edition.to_flag());
2135        compiler.args(&self.props.compile_flags);
2136
2137        compiler
2138    }
2139
2140    fn make_exe_name(&self) -> Utf8PathBuf {
2141        // Using a single letter here to keep the path length down for
2142        // Windows.  Some test names get very long.  rustc creates `rcgu`
2143        // files with the module name appended to it which can more than
2144        // double the length.
2145        let mut f = self.output_base_dir().join("a");
2146        // FIXME: This is using the host architecture exe suffix, not target!
2147        if self.config.target.contains("emscripten") {
2148            f = f.with_extra_extension("js");
2149        } else if self.config.target.starts_with("wasm") {
2150            f = f.with_extra_extension("wasm");
2151        } else if self.config.target.contains("spirv") {
2152            f = f.with_extra_extension("spv");
2153        } else if !env::consts::EXE_SUFFIX.is_empty() {
2154            f = f.with_extra_extension(env::consts::EXE_SUFFIX);
2155        }
2156        f
2157    }
2158
2159    fn make_run_args(&self) -> ProcArgs {
2160        // If we've got another tool to run under (valgrind),
2161        // then split apart its command
2162        let mut args = self.split_maybe_args(&self.config.runner);
2163
2164        let exe_file = self.make_exe_name();
2165
2166        args.push(exe_file.into_os_string());
2167
2168        // Add the arguments in the run_flags directive
2169        args.extend(self.props.run_flags.iter().map(OsString::from));
2170
2171        let prog = args.remove(0);
2172        ProcArgs { prog, args }
2173    }
2174
2175    fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<OsString> {
2176        match *argstr {
2177            Some(ref s) => s
2178                .split(' ')
2179                .filter_map(|s| {
2180                    if s.chars().all(|c| c.is_whitespace()) {
2181                        None
2182                    } else {
2183                        Some(OsString::from(s))
2184                    }
2185                })
2186                .collect(),
2187            None => Vec::new(),
2188        }
2189    }
2190
2191    fn dump_output(&self, print_output: bool, proc_name: &str, out: &str, err: &str) {
2192        let revision =
2193            if let Some(r) = self.variant.revision() { format!("{}.", r) } else { String::new() };
2194
2195        self.dump_output_file(out, &format!("{}out", revision));
2196        self.dump_output_file(err, &format!("{}err", revision));
2197
2198        if !print_output {
2199            return;
2200        }
2201
2202        let path = Utf8Path::new(proc_name);
2203        let proc_name = if path.file_stem().is_some_and(|p| p == "rmake") {
2204            String::from_iter(
2205                path.parent()
2206                    .unwrap()
2207                    .file_name()
2208                    .into_iter()
2209                    .chain(Some("/"))
2210                    .chain(path.file_name()),
2211            )
2212        } else {
2213            path.file_name().unwrap().into()
2214        };
2215        writeln!(self.stdout, "------{proc_name} stdout------------------------------");
2216        writeln!(self.stdout, "{}", out);
2217        writeln!(self.stdout, "------{proc_name} stderr------------------------------");
2218        writeln!(self.stdout, "{}", err);
2219        writeln!(self.stdout, "------------------------------------------");
2220    }
2221
2222    fn dump_output_file(&self, out: &str, extension: &str) {
2223        let outfile = self.make_out_name(extension);
2224        fs::write(outfile.as_std_path(), out)
2225            .unwrap_or_else(|err| panic!("failed to write {outfile}: {err:?}"));
2226    }
2227
2228    /// Creates a filename for output with the given extension.
2229    /// E.g., `/.../testname.revision.mode/testname.extension`.
2230    fn make_out_name(&self, extension: &str) -> Utf8PathBuf {
2231        self.output_base_name().with_extension(extension)
2232    }
2233
2234    /// Gets the directory where auxiliary files are written.
2235    /// E.g., `/.../testname.revision.mode/auxiliary/`.
2236    fn aux_output_dir_name(&self) -> Utf8PathBuf {
2237        self.output_base_dir()
2238            .join("auxiliary")
2239            .with_extra_extension(self.config.mode.aux_dir_disambiguator())
2240    }
2241
2242    /// Gets the directory where auxiliary binaries are written.
2243    /// E.g., `/.../testname.revision.mode/auxiliary/bin`.
2244    fn aux_bin_output_dir_name(&self) -> Utf8PathBuf {
2245        self.aux_output_dir_name().join("bin")
2246    }
2247
2248    /// The revision, ignored for incremental compilation since it wants all revisions in
2249    /// the same directory.
2250    fn variant_with_safe_revision(&self) -> TestVariant {
2251        if self.config.mode == TestMode::Incremental {
2252            TestVariant { revision: None, debugger: self.variant.debugger }
2253        } else {
2254            self.variant.clone()
2255        }
2256    }
2257
2258    /// Gets the absolute path to the directory where all output for the given
2259    /// test/revision should reside.
2260    /// E.g., `/path/to/build/host-tuple/test/ui/relative/testname.revision.mode/`.
2261    fn output_base_dir(&self) -> Utf8PathBuf {
2262        output_base_dir(self.config, self.testpaths, &self.variant_with_safe_revision())
2263    }
2264
2265    /// Gets the absolute path to the base filename used as output for the given
2266    /// test/revision.
2267    /// E.g., `/.../relative/testname.revision.mode/testname`.
2268    fn output_base_name(&self) -> Utf8PathBuf {
2269        output_base_name(self.config, self.testpaths, &self.variant_with_safe_revision())
2270    }
2271
2272    /// Prints a message to (captured) stdout if `config.verbose` is true.
2273    /// The message is also logged to `tracing::debug!` regardless of verbosity.
2274    ///
2275    /// Use `format_args!` as the argument to perform formatting if required.
2276    fn logv(&self, message: impl fmt::Display) {
2277        debug!("{message}");
2278        if self.config.verbose {
2279            // Note: `./x test ... --verbose --no-capture` is needed to see this print.
2280            writeln!(self.stdout, "{message}");
2281        }
2282    }
2283
2284    /// Prefix to print before error messages. Normally just `error`, but also
2285    /// includes the revision name for tests that use revisions.
2286    #[must_use]
2287    fn error_prefix(&self) -> String {
2288        match self.variant.revision() {
2289            Some(rev) => format!("error in revision `{rev}`"),
2290            None => format!("error"),
2291        }
2292    }
2293
2294    #[track_caller]
2295    fn fatal(&self, err: &str) -> ! {
2296        writeln!(self.stdout, "\n{prefix}: {err}", prefix = self.error_prefix());
2297        error!("fatal error, panic: {:?}", err);
2298        panic!("fatal error");
2299    }
2300
2301    fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2302        self.fatal_proc_rec_general(err, None, proc_res, || ());
2303    }
2304
2305    /// Underlying implementation of [`Self::fatal_proc_rec`], providing some
2306    /// extra capabilities not needed by most callers.
2307    fn fatal_proc_rec_general(
2308        &self,
2309        err: &str,
2310        extra_note: Option<&str>,
2311        proc_res: &ProcRes,
2312        callback_before_unwind: impl FnOnce(),
2313    ) -> ! {
2314        writeln!(self.stdout, "\n{prefix}: {err}", prefix = self.error_prefix());
2315
2316        // Some callers want to print additional notes after the main error message.
2317        if let Some(note) = extra_note {
2318            writeln!(self.stdout, "{note}");
2319        }
2320
2321        // Print the details and output of the subprocess that caused this test to fail.
2322        writeln!(self.stdout, "{}", proc_res.format_info());
2323
2324        // Some callers want print more context or show a custom diff before the unwind occurs.
2325        callback_before_unwind();
2326
2327        // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from
2328        // compiletest, which is unnecessary noise.
2329        std::panic::resume_unwind(Box::new(()));
2330    }
2331
2332    // codegen tests (using FileCheck)
2333
2334    fn compile_test_and_save_ir(&self) -> (ProcRes, Utf8PathBuf) {
2335        let output_path = self.output_base_name().with_extension("ll");
2336        let input_file = &self.testpaths.file;
2337        let rustc = self.make_compile_args(
2338            CompilerKind::Rustc,
2339            input_file,
2340            TargetLocation::ThisFile(output_path.clone()),
2341            Emit::LlvmIr,
2342            AllowUnused::No,
2343            LinkToAux::Yes,
2344            self.edition(),
2345            Vec::new(),
2346        );
2347
2348        let proc_res = self.compose_and_run_compiler(rustc, None);
2349        (proc_res, output_path)
2350    }
2351
2352    fn verify_with_filecheck(&self, output: &Utf8Path) -> ProcRes {
2353        let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2354        filecheck.arg("--input-file").arg(output).arg(&self.testpaths.file);
2355
2356        // Because we use custom prefixes, we also have to register the default prefix.
2357        filecheck.arg("--check-prefix=CHECK");
2358
2359        // FIXME(#134510): auto-registering revision names as check prefix is a bit sketchy, and
2360        // that having to pass `--allow-unused-prefix` is an unfortunate side-effect of not knowing
2361        // whether the test author actually wanted revision-specific check prefixes or not.
2362        //
2363        // TL;DR We may not want to conflate `compiletest` revisions and `FileCheck` prefixes.
2364
2365        // HACK: tests are allowed to use a revision name as a check prefix.
2366        if let Some(rev) = self.variant.revision() {
2367            filecheck.arg("--check-prefix").arg(rev);
2368        }
2369
2370        // HACK: the filecheck tool normally fails if a prefix is defined but not used. However,
2371        // sometimes revisions are used to specify *compiletest* directives which are not FileCheck
2372        // concerns.
2373        filecheck.arg("--allow-unused-prefixes");
2374
2375        // Provide more context on failures.
2376        filecheck.args(&["--dump-input-context", "100"]);
2377
2378        // Add custom flags supplied by the `filecheck-flags:` test directive.
2379        filecheck.args(&self.props.filecheck_flags);
2380
2381        // FIXME(jieyouxu): don't pass an empty Path
2382        self.compose_and_run(filecheck, Utf8Path::new(""), None, None)
2383    }
2384
2385    fn get_lines(&self, path: &Utf8Path, mut other_files: Option<&mut Vec<String>>) -> Vec<usize> {
2386        let content = fs::read_to_string(path.as_std_path()).unwrap();
2387        let mut ignore = false;
2388        content
2389            .lines()
2390            .enumerate()
2391            .filter_map(|(line_nb, line)| {
2392                if (line.trim_start().starts_with("pub mod ")
2393                    || line.trim_start().starts_with("mod "))
2394                    && line.ends_with(';')
2395                {
2396                    if let Some(ref mut other_files) = other_files {
2397                        other_files.push(line.rsplit("mod ").next().unwrap().replace(';', ""));
2398                    }
2399                    None
2400                } else {
2401                    let sline = line.rsplit("///").next().unwrap();
2402                    let line = sline.trim_start();
2403                    if line.starts_with("```") {
2404                        if ignore {
2405                            ignore = false;
2406                            None
2407                        } else {
2408                            ignore = true;
2409                            Some(line_nb + 1)
2410                        }
2411                    } else {
2412                        None
2413                    }
2414                }
2415            })
2416            .collect()
2417    }
2418
2419    /// This method is used for `//@ check-test-line-numbers-match`.
2420    ///
2421    /// It checks that doctests line in the displayed doctest "name" matches where they are
2422    /// defined in source code.
2423    fn check_rustdoc_test_option(&self, res: ProcRes) {
2424        let mut other_files = Vec::new();
2425        let mut files: HashMap<String, Vec<usize>> = HashMap::new();
2426        let normalized = fs::canonicalize(&self.testpaths.file).expect("failed to canonicalize");
2427        let normalized = normalized.to_str().unwrap().replace('\\', "/");
2428        files.insert(normalized, self.get_lines(&self.testpaths.file, Some(&mut other_files)));
2429        for other_file in other_files {
2430            let mut path = self.testpaths.file.clone();
2431            path.set_file_name(&format!("{}.rs", other_file));
2432            let path = path.canonicalize_utf8().expect("failed to canonicalize");
2433            let normalized = path.as_str().replace('\\', "/");
2434            files.insert(normalized, self.get_lines(&path, None));
2435        }
2436
2437        let mut tested = 0;
2438        for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| {
2439            if let Some((left, right)) = s.split_once(" - ") {
2440                let path = left.rsplit("test ").next().unwrap();
2441                let path = fs::canonicalize(&path).expect("failed to canonicalize");
2442                let path = path.to_str().unwrap().replace('\\', "/");
2443                if let Some(ref mut v) = files.get_mut(&path) {
2444                    tested += 1;
2445                    let mut iter = right.split("(line ");
2446                    iter.next();
2447                    let line = iter
2448                        .next()
2449                        .unwrap_or(")")
2450                        .split(')')
2451                        .next()
2452                        .unwrap_or("0")
2453                        .parse()
2454                        .unwrap_or(0);
2455                    if let Ok(pos) = v.binary_search(&line) {
2456                        v.remove(pos);
2457                    } else {
2458                        self.fatal_proc_rec(
2459                            &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2460                            &res,
2461                        );
2462                    }
2463                }
2464            }
2465        }) {}
2466        if tested == 0 {
2467            self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2468        } else {
2469            for (entry, v) in &files {
2470                if !v.is_empty() {
2471                    self.fatal_proc_rec(
2472                        &format!(
2473                            "Not found test at line{} \"{}\":{:?}",
2474                            if v.len() > 1 { "s" } else { "" },
2475                            entry,
2476                            v
2477                        ),
2478                        &res,
2479                    );
2480                }
2481            }
2482        }
2483    }
2484
2485    fn force_color_svg(&self) -> bool {
2486        self.props.compile_flags.iter().any(|s| s.contains("--color=always"))
2487    }
2488
2489    /// Returns the lines for the by-lines comparison, normalized for the
2490    /// parallel front-end: for SVG output, strip the header line and `y`
2491    /// offsets; otherwise, filter out padded empty code lines (a single `|`).
2492    fn lines_for_comparison(&self, output: &str) -> Vec<String> {
2493        if self.force_color_svg() {
2494            let strip_y = static_regex!(r#"y="\d+px""#);
2495            output
2496                .lines()
2497                // anstyle_svg causes environment-dependent width parameter
2498                .skip(1)
2499                .map(|line| strip_y.replace_all(line, r#"y="0px""#).into_owned())
2500                .collect()
2501        } else {
2502            output.lines().filter(|l| l.trim() != "|").map(str::to_owned).collect()
2503        }
2504    }
2505
2506    fn load_compare_outputs(
2507        &self,
2508        proc_res: &ProcRes,
2509        output_kind: TestOutput,
2510        explicit_format: bool,
2511    ) -> usize {
2512        let stderr_bits = format!("{}bit.stderr", self.config.get_pointer_width());
2513        let (stderr_kind, stdout_kind) = match output_kind {
2514            TestOutput::Compile => (
2515                if self.force_color_svg() {
2516                    UI_SVG
2517                } else if self.props.stderr_per_bitwidth {
2518                    &stderr_bits
2519                } else {
2520                    UI_STDERR
2521                },
2522                UI_STDOUT,
2523            ),
2524            TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
2525        };
2526
2527        let expected_stderr = self.load_expected_output(stderr_kind);
2528        let expected_stdout = self.load_expected_output(stdout_kind);
2529
2530        let mut normalized_stdout =
2531            self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout);
2532        match output_kind {
2533            TestOutput::Run if self.config.remote_test_client.is_some() => {
2534                // When tests are run using the remote-test-client, the string
2535                // 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"'
2536                // is printed to stdout by the client and then captured in the ProcRes,
2537                // so it needs to be removed when comparing the run-pass test execution output.
2538                normalized_stdout = static_regex!(
2539                    "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-.]+)+\", waiting for result\n"
2540                )
2541                .replace(&normalized_stdout, "")
2542                .to_string();
2543                // When there is a panic, the remote-test-client also prints "died due to signal";
2544                // that needs to be removed as well.
2545                normalized_stdout = static_regex!("^died due to signal [0-9]+\n")
2546                    .replace(&normalized_stdout, "")
2547                    .to_string();
2548                // FIXME: it would be much nicer if we could just tell the remote-test-client to not
2549                // print these things.
2550            }
2551            _ => {}
2552        };
2553
2554        let stderr;
2555        let normalized_stderr;
2556
2557        if self.force_color_svg() {
2558            let normalized = self.normalize_output(&proc_res.stderr, &self.props.normalize_stderr);
2559            stderr = anstyle_svg::Term::new().render_svg(&normalized);
2560            normalized_stderr = stderr.clone();
2561        } else {
2562            stderr = if explicit_format {
2563                proc_res.stderr.clone()
2564            } else {
2565                json::extract_rendered(&proc_res.stderr)
2566            };
2567            normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
2568        }
2569
2570        let mut errors = 0;
2571        match output_kind {
2572            TestOutput::Compile => {
2573                if !self.props.dont_check_compiler_stdout {
2574                    if self
2575                        .compare_output(
2576                            stdout_kind,
2577                            &normalized_stdout,
2578                            &proc_res.stdout,
2579                            &expected_stdout,
2580                        )
2581                        .should_error()
2582                    {
2583                        errors += 1;
2584                    }
2585                }
2586                if !self.props.dont_check_compiler_stderr {
2587                    if self
2588                        .compare_output(stderr_kind, &normalized_stderr, &stderr, &expected_stderr)
2589                        .should_error()
2590                    {
2591                        errors += 1;
2592                    }
2593                }
2594            }
2595            TestOutput::Run => {
2596                if self
2597                    .compare_output(
2598                        stdout_kind,
2599                        &normalized_stdout,
2600                        &proc_res.stdout,
2601                        &expected_stdout,
2602                    )
2603                    .should_error()
2604                {
2605                    errors += 1;
2606                }
2607
2608                if self
2609                    .compare_output(stderr_kind, &normalized_stderr, &stderr, &expected_stderr)
2610                    .should_error()
2611                {
2612                    errors += 1;
2613                }
2614            }
2615        }
2616        errors
2617    }
2618
2619    fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> String {
2620        // Crude heuristic to detect when the output should have JSON-specific
2621        // normalization steps applied.
2622        let rflags = self.props.run_flags.join(" ");
2623        let cflags = self.props.compile_flags.join(" ");
2624        let json = rflags.contains("--format json")
2625            || rflags.contains("--format=json")
2626            || cflags.contains("--error-format json")
2627            || cflags.contains("--error-format pretty-json")
2628            || cflags.contains("--error-format=json")
2629            || cflags.contains("--error-format=pretty-json")
2630            || cflags.contains("--output-format json")
2631            || cflags.contains("--output-format=json");
2632
2633        let mut normalized = output.to_string();
2634
2635        let mut normalize_path = |from: &Utf8Path, to: &str| {
2636            let from = if json { &from.as_str().replace("\\", "\\\\") } else { from.as_str() };
2637
2638            normalized = normalized.replace(from, to);
2639        };
2640
2641        let parent_dir = self.testpaths.file.parent().unwrap();
2642        normalize_path(parent_dir, "$DIR");
2643
2644        if self.props.remap_src_base {
2645            let mut remapped_parent_dir = Utf8PathBuf::from(FAKE_SRC_BASE);
2646            if self.testpaths.relative_dir != Utf8Path::new("") {
2647                remapped_parent_dir.push(&self.testpaths.relative_dir);
2648            }
2649            normalize_path(&remapped_parent_dir, "$DIR");
2650        }
2651
2652        let base_dir = Utf8Path::new("/rustc/FAKE_PREFIX");
2653        // Fake paths into the libstd/libcore
2654        normalize_path(&base_dir.join("library"), "$SRC_DIR");
2655        // `ui-fulldeps` tests can show paths to the compiler source when testing macros from
2656        // `rustc_macros`
2657        // eg. /home/user/rust/compiler
2658        normalize_path(&base_dir.join("compiler"), "$COMPILER_DIR");
2659
2660        // Real paths into the libstd/libcore
2661        let rust_src_dir = &self.config.sysroot_base.join("lib/rustlib/src/rust");
2662        rust_src_dir.try_exists().expect(&*format!("{} should exists", rust_src_dir));
2663        let rust_src_dir =
2664            rust_src_dir.read_link_utf8().unwrap_or_else(|_| rust_src_dir.to_path_buf());
2665        normalize_path(&rust_src_dir.join("library"), "$SRC_DIR_REAL");
2666
2667        // Real paths into the compiler
2668        let rustc_src_dir = &self.config.sysroot_base.join("lib/rustlib/rustc-src/rust");
2669        rustc_src_dir.try_exists().expect(&*format!("{} should exists", rustc_src_dir));
2670        let rustc_src_dir = rustc_src_dir.read_link_utf8().unwrap_or(rustc_src_dir.to_path_buf());
2671        normalize_path(&rustc_src_dir.join("compiler"), "$COMPILER_DIR_REAL");
2672
2673        // eg.
2674        // /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui/<test_dir>/$name.$revision.$mode/
2675        normalize_path(&self.output_base_dir(), "$TEST_BUILD_DIR");
2676        // Same as above, but with a canonicalized path.
2677        // This is required because some tests print canonical paths inside test build directory,
2678        // so if the build directory is a symlink, normalization doesn't help.
2679        //
2680        // NOTE: There are also tests which print the non-canonical name, so we need both this and
2681        // the above normalizations.
2682        normalize_path(&self.output_base_dir().canonicalize_utf8().unwrap(), "$TEST_BUILD_DIR");
2683        // eg. /home/user/rust/build
2684        normalize_path(&self.config.build_root, "$BUILD_DIR");
2685
2686        if json {
2687            // escaped newlines in json strings should be readable
2688            // in the stderr files. There's no point in being correct,
2689            // since only humans process the stderr files.
2690            // Thus we just turn escaped newlines back into newlines.
2691            normalized = normalized.replace("\\n", "\n");
2692        }
2693
2694        // If there are `$SRC_DIR` normalizations with line and column numbers, then replace them
2695        // with placeholders as we do not want tests needing updated when compiler source code
2696        // changes.
2697        // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
2698        normalized = static_regex!("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?")
2699            .replace_all(&normalized, "SRC_DIR$1:LL:COL")
2700            .into_owned();
2701
2702        normalized = Self::normalize_platform_differences(&normalized);
2703
2704        // Normalize long type name hash.
2705        normalized =
2706            static_regex!(r"\$TEST_BUILD_DIR/(?P<filename>[^\.]+).long-type-(?P<hash>\d+).txt")
2707                .replace_all(&normalized, |caps: &Captures<'_>| {
2708                    format!(
2709                        "$TEST_BUILD_DIR/{filename}.long-type-$LONG_TYPE_HASH.txt",
2710                        filename = &caps["filename"]
2711                    )
2712                })
2713                .into_owned();
2714
2715        // Normalize thread IDs in panic messages
2716        normalized = static_regex!(r"thread '(?P<name>.*?)' \((rtid )?\d+\) panicked")
2717            .replace_all(&normalized, "thread '$name' ($$TID) panicked")
2718            .into_owned();
2719
2720        normalized = normalized.replace("\t", "\\t"); // makes tabs visible
2721
2722        // Remove test annotations like `//~ ERROR text` from the output,
2723        // since they duplicate actual errors and make the output hard to read.
2724        // This mirrors the regex in src/tools/tidy/src/style.rs, please update
2725        // both if either are changed.
2726        normalized =
2727            static_regex!("\\s*//(\\[.*\\])?~.*").replace_all(&normalized, "").into_owned();
2728
2729        // This code normalizes various hashes in v0 symbol mangling that is
2730        // emitted in the ui and mir-opt tests.
2731        let v0_crate_hash_prefix_re = static_regex!(r"_R.*?Cs[0-9a-zA-Z]+_");
2732        let v0_crate_hash_re = static_regex!(r"Cs[0-9a-zA-Z]+_");
2733
2734        const V0_CRATE_HASH_PLACEHOLDER: &str = r"CsCRATE_HASH_";
2735        if v0_crate_hash_prefix_re.is_match(&normalized) {
2736            // Normalize crate hash
2737            normalized =
2738                v0_crate_hash_re.replace_all(&normalized, V0_CRATE_HASH_PLACEHOLDER).into_owned();
2739        }
2740
2741        let v0_back_ref_prefix_re = static_regex!(r"\(_R.*?B[0-9a-zA-Z]_");
2742        let v0_back_ref_re = static_regex!(r"B[0-9a-zA-Z]_");
2743
2744        const V0_BACK_REF_PLACEHOLDER: &str = r"B<REF>_";
2745        if v0_back_ref_prefix_re.is_match(&normalized) {
2746            // Normalize back references (see RFC 2603)
2747            normalized =
2748                v0_back_ref_re.replace_all(&normalized, V0_BACK_REF_PLACEHOLDER).into_owned();
2749        }
2750
2751        // AllocId are numbered globally in a compilation session. This can lead to changes
2752        // depending on the exact compilation flags and host architecture. Meanwhile, we want
2753        // to keep them numbered, to see if the same id appears multiple times.
2754        // So we remap to deterministic numbers that only depend on the subset of allocations
2755        // that actually appear in the output.
2756        // We use uppercase ALLOC to distinguish from the non-normalized version.
2757        {
2758            match self.config.mode {
2759                // Unfortunately, due to parallel frontend assigning alloc-ids
2760                // nondeterministically we resort to dropping ids altogether for now
2761                // in ui tests
2762                TestMode::Ui => {
2763                    // The alloc-id appears in pretty-printed allocations.
2764                    normalized = static_regex!(
2765                        r"╾─*(a(lloc)?|A(LLOC)?)\d+(\+0x[0-9a-f]+)?(<imm>)?( ?\(\d+ ptr bytes\))?─*╼"
2766                    )
2767                    .replace_all(&normalized, |_: &Captures<'_>| "╾ALLOC$ID╼".to_string())
2768                    .into_owned();
2769
2770                    // The alloc-id appears in a sentence.
2771                    normalized = static_regex!(r"\b(alloc|ALLOC)\d+\b")
2772                        .replace_all(&normalized, |_: &Captures<'_>| "ALLOC$ID".to_string())
2773                        .into_owned();
2774                }
2775                // use consistent `AllocId`s in other test modes, where parallel frontend
2776                // should not (theoretically) be an issue
2777                _ => {
2778                    let mut seen_allocs = indexmap::IndexSet::new();
2779                    // The alloc-id appears in pretty-printed allocations.
2780                    normalized = static_regex!(
2781                        r"╾─*a(lloc)?([0-9]+)(\+0x[0-9a-f]+)?(<imm>)?( \([0-9]+ ptr bytes\))?─*╼"
2782                    )
2783                    .replace_all(&normalized, |caps: &Captures<'_>| {
2784                        // Renumber the captured index.
2785                        let index = caps.get(2).unwrap().as_str().to_string();
2786                        let (index, _) = seen_allocs.insert_full(index);
2787                        let offset = caps.get(3).map_or("", |c| c.as_str());
2788                        let imm = caps.get(4).map_or("", |c| c.as_str());
2789                        // Do not bother keeping it pretty, just make it deterministic.
2790                        format!("╾ALLOC{index}{offset}{imm}╼")
2791                    })
2792                    .into_owned();
2793
2794                    // The alloc-id appears in a sentence.
2795                    normalized = static_regex!(r"\balloc([0-9]+)\b")
2796                        .replace_all(&normalized, |caps: &Captures<'_>| {
2797                            let index = caps.get(1).unwrap().as_str().to_string();
2798                            let (index, _) = seen_allocs.insert_full(index);
2799                            format!("ALLOC{index}")
2800                        })
2801                        .into_owned();
2802                }
2803            }
2804        }
2805
2806        // Custom normalization rules
2807        for rule in custom_rules {
2808            let re = Regex::new(&rule.0).expect("bad regex in custom normalization rule");
2809            normalized = re.replace_all(&normalized, &rule.1[..]).into_owned();
2810        }
2811        normalized
2812    }
2813
2814    /// Normalize output differences across platforms. Generally changes Windows output to be more
2815    /// Unix-like.
2816    ///
2817    /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
2818    /// with LF.
2819    fn normalize_platform_differences(output: &str) -> String {
2820        let output = output.replace(r"\\", r"\");
2821
2822        // Used to find Windows paths.
2823        //
2824        // It's not possible to detect paths in the error messages generally, but this is a
2825        // decent enough heuristic.
2826        let re = static_regex!(
2827            r#"(?x)
2828                (?:
2829                  # Match paths that don't include spaces.
2830                  (?:\\[\pL\pN\.\-_']+)+\.\pL+
2831                |
2832                  # If the path starts with a well-known root, then allow spaces and no file extension.
2833                  \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_'\ ]+)+
2834                )"#
2835        );
2836        re.replace_all(&output, |caps: &Captures<'_>| caps[0].replace(r"\", "/"))
2837            .replace("\r\n", "\n")
2838    }
2839
2840    fn expected_output_path(&self, kind: &str) -> Utf8PathBuf {
2841        let mut path = expected_output_path(
2842            &self.testpaths,
2843            self.variant.revision(),
2844            &self.config.compare_mode,
2845            kind,
2846        );
2847
2848        if !path.exists() {
2849            if let Some(CompareMode::Polonius) = self.config.compare_mode {
2850                path = expected_output_path(&self.testpaths, self.variant.revision(), &None, kind);
2851            }
2852        }
2853
2854        if !path.exists() {
2855            path = expected_output_path(&self.testpaths, self.variant.revision(), &None, kind);
2856        }
2857
2858        path
2859    }
2860
2861    fn load_expected_output(&self, kind: &str) -> String {
2862        let path = self.expected_output_path(kind);
2863        if path.exists() {
2864            match self.load_expected_output_from_path(&path) {
2865                Ok(x) => x,
2866                Err(x) => self.fatal(&x),
2867            }
2868        } else {
2869            String::new()
2870        }
2871    }
2872
2873    fn load_expected_output_from_path(&self, path: &Utf8Path) -> Result<String, String> {
2874        fs::read_to_string(path)
2875            .map_err(|err| format!("failed to load expected output from `{}`: {}", path, err))
2876    }
2877
2878    /// Attempts to delete a file, succeeding if the file does not exist.
2879    fn delete_file(&self, file: &Utf8Path) {
2880        if let Err(e) = fs::remove_file(file.as_std_path())
2881            && e.kind() != io::ErrorKind::NotFound
2882        {
2883            self.fatal(&format!("failed to delete `{}`: {}", file, e,));
2884        }
2885    }
2886
2887    fn compare_output(
2888        &self,
2889        stream: &str,
2890        actual: &str,
2891        actual_unnormalized: &str,
2892        expected: &str,
2893    ) -> CompareOutcome {
2894        let expected_path = expected_output_path(
2895            self.testpaths,
2896            self.variant.revision(),
2897            &self.config.compare_mode,
2898            stream,
2899        );
2900
2901        if self.config.bless && actual.is_empty() && expected_path.exists() {
2902            self.delete_file(&expected_path);
2903        }
2904
2905        let are_different = match (self.force_color_svg(), expected.find('\n'), actual.find('\n')) {
2906            // FIXME: We ignore the first line of SVG files
2907            // because the width parameter is non-deterministic.
2908            (true, Some(nl_e), Some(nl_a)) => expected[nl_e..] != actual[nl_a..],
2909            _ => expected != actual,
2910        };
2911        if !are_different {
2912            return CompareOutcome::Same;
2913        }
2914
2915        // Wrapper tools set by `runner` might provide extra output on failure,
2916        // for example a WebAssembly runtime might print the stack trace of an
2917        // `unreachable` instruction by default.
2918        let compare_output_by_lines_subset = self.config.runner.is_some();
2919
2920        // Also, some tests like `ui/parallel-rustc` have non-deterministic
2921        // orders of output, so we need to compare by lines.
2922        let compare_output_by_lines = self.props.compare_output_by_lines;
2923
2924        let tmp;
2925        let (expected, actual): (&str, &str) = if compare_output_by_lines_subset {
2926            let actual_lines: HashSet<_> = actual.lines().collect();
2927            let expected_lines: Vec<_> = expected.lines().collect();
2928            let mut used = expected_lines.clone();
2929            used.retain(|line| actual_lines.contains(line));
2930
2931            // check if `expected` contains a subset of the lines of `actual`
2932            if used.len() == expected_lines.len() && (expected.is_empty() == actual.is_empty()) {
2933                return CompareOutcome::Same;
2934            }
2935            if expected_lines.is_empty() {
2936                // if we have no lines to check, force a full overwrite
2937                ("", actual)
2938            } else {
2939                // this prints/blesses the subset, not the actual
2940                tmp = (expected_lines.join("\n"), used.join("\n"));
2941                (&tmp.0, &tmp.1)
2942            }
2943        } else if compare_output_by_lines {
2944            let mut actual_lines = self.lines_for_comparison(actual);
2945            let mut expected_lines = self.lines_for_comparison(expected);
2946            actual_lines.sort_unstable();
2947            expected_lines.sort_unstable();
2948            if actual_lines == expected_lines {
2949                return CompareOutcome::Same;
2950            } else {
2951                (expected, actual)
2952            }
2953        } else {
2954            (expected, actual)
2955        };
2956
2957        // Write the actual output to a file in build directory.
2958        let actual_path = self
2959            .output_base_name()
2960            .with_extra_extension(self.variant.revision().unwrap_or(""))
2961            .with_extra_extension(
2962                self.config.compare_mode.as_ref().map(|cm| cm.to_str()).unwrap_or(""),
2963            )
2964            .with_extra_extension(stream);
2965
2966        if let Err(err) = fs::write(&actual_path, &actual) {
2967            self.fatal(&format!("failed to write {stream} to `{actual_path}`: {err}",));
2968        }
2969        writeln!(self.stdout, "Saved the actual {stream} to `{actual_path}`");
2970
2971        if !self.config.bless {
2972            if expected.is_empty() {
2973                writeln!(self.stdout, "normalized {}:\n{}\n", stream, actual);
2974            } else {
2975                self.show_diff(
2976                    stream,
2977                    &expected_path,
2978                    &actual_path,
2979                    expected,
2980                    actual,
2981                    actual_unnormalized,
2982                    compare_output_by_lines || compare_output_by_lines_subset,
2983                );
2984            }
2985        } else {
2986            // Delete non-revision .stderr/.stdout file if revisions are used.
2987            // Without this, we'd just generate the new files and leave the old files around.
2988            if self.variant.revision().is_some() {
2989                let old =
2990                    expected_output_path(self.testpaths, None, &self.config.compare_mode, stream);
2991                self.delete_file(&old);
2992            }
2993
2994            if !actual.is_empty() {
2995                if let Err(err) = fs::write(&expected_path, &actual) {
2996                    self.fatal(&format!("failed to write {stream} to `{expected_path}`: {err}"));
2997                }
2998                writeln!(
2999                    self.stdout,
3000                    "Blessing the {stream} of `{test_name}` as `{expected_path}`",
3001                    test_name = self.testpaths.file
3002                );
3003            }
3004        }
3005
3006        writeln!(self.stdout, "\nThe actual {stream} differed from the expected {stream}");
3007
3008        if self.config.bless { CompareOutcome::Blessed } else { CompareOutcome::Differed }
3009    }
3010
3011    /// Returns whether to show the full stderr/stdout.
3012    fn show_diff(
3013        &self,
3014        stream: &str,
3015        expected_path: &Utf8Path,
3016        actual_path: &Utf8Path,
3017        expected: &str,
3018        actual: &str,
3019        actual_unnormalized: &str,
3020        show_diff_by_lines: bool,
3021    ) {
3022        writeln!(self.stderr, "diff of {stream}:\n");
3023        if let Some(diff_command) = self.config.diff_command.as_deref() {
3024            let mut args = diff_command.split_whitespace();
3025            let name = args.next().unwrap();
3026            match Command::new(name).args(args).args([expected_path, actual_path]).output() {
3027                Err(err) => {
3028                    self.fatal(&format!(
3029                        "failed to call custom diff command `{diff_command}`: {err}"
3030                    ));
3031                }
3032                Ok(output) => {
3033                    let output = String::from_utf8_lossy(&output.stdout);
3034                    write!(self.stderr, "{output}");
3035                }
3036            }
3037        } else {
3038            write!(self.stderr, "{}", write_diff(expected, actual, 3));
3039        }
3040
3041        // NOTE: argument order is important, we need `actual` to be on the left so the line number match up when we compare it to `actual_unnormalized` below.
3042        let diff_results = make_diff(actual, expected, 0);
3043
3044        let (mut mismatches_normalized, mut mismatch_line_nos) = (String::new(), vec![]);
3045        for hunk in diff_results {
3046            let mut line_no = hunk.line_number;
3047            for line in hunk.lines {
3048                // NOTE: `Expected` is actually correct here, the argument order is reversed so our line numbers match up
3049                if let DiffLine::Expected(normalized) = line {
3050                    mismatches_normalized += &normalized;
3051                    mismatches_normalized += "\n";
3052                    mismatch_line_nos.push(line_no);
3053                    line_no += 1;
3054                }
3055            }
3056        }
3057        let mut mismatches_unnormalized = String::new();
3058        let diff_normalized = make_diff(actual, actual_unnormalized, 0);
3059        for hunk in diff_normalized {
3060            if mismatch_line_nos.contains(&hunk.line_number) {
3061                for line in hunk.lines {
3062                    if let DiffLine::Resulting(unnormalized) = line {
3063                        mismatches_unnormalized += &unnormalized;
3064                        mismatches_unnormalized += "\n";
3065                    }
3066                }
3067            }
3068        }
3069
3070        let normalized_diff = make_diff(&mismatches_normalized, &mismatches_unnormalized, 0);
3071        // HACK: instead of checking if each hunk is empty, this only checks if the whole input is empty. we should be smarter about this so we don't treat added or removed output as normalized.
3072        if !normalized_diff.is_empty()
3073            && !mismatches_unnormalized.is_empty()
3074            && !mismatches_normalized.is_empty()
3075        {
3076            writeln!(
3077                self.stderr,
3078                "Note: some mismatched output was normalized before being compared"
3079            );
3080            // FIXME: respect diff_command
3081            write!(
3082                self.stderr,
3083                "{}",
3084                write_diff(&mismatches_unnormalized, &mismatches_normalized, 0)
3085            );
3086        }
3087
3088        if show_diff_by_lines {
3089            let expected_lines = self.lines_for_comparison(expected);
3090            let actual_lines = self.lines_for_comparison(actual);
3091            write!(self.stderr, "{}", diff_by_lines(&expected_lines, &actual_lines));
3092        }
3093    }
3094
3095    fn check_and_prune_duplicate_outputs(
3096        &self,
3097        proc_res: &ProcRes,
3098        modes: &[CompareMode],
3099        require_same_modes: &[CompareMode],
3100    ) {
3101        for kind in UI_EXTENSIONS {
3102            let canon_comparison_path =
3103                expected_output_path(&self.testpaths, self.variant.revision(), &None, kind);
3104
3105            let canon = match self.load_expected_output_from_path(&canon_comparison_path) {
3106                Ok(canon) => canon,
3107                _ => continue,
3108            };
3109            let bless = self.config.bless;
3110            let check_and_prune_duplicate_outputs = |mode: &CompareMode, require_same: bool| {
3111                let examined_path = expected_output_path(
3112                    &self.testpaths,
3113                    self.variant.revision(),
3114                    &Some(mode.clone()),
3115                    kind,
3116                );
3117
3118                // If there is no output, there is nothing to do
3119                let examined_content = match self.load_expected_output_from_path(&examined_path) {
3120                    Ok(content) => content,
3121                    _ => return,
3122                };
3123
3124                let is_duplicate = canon == examined_content;
3125
3126                match (bless, require_same, is_duplicate) {
3127                    // If we're blessing and the output is the same, then delete the file.
3128                    (true, _, true) => {
3129                        self.delete_file(&examined_path);
3130                    }
3131                    // If we want them to be the same, but they are different, then error.
3132                    // We do this whether we bless or not
3133                    (_, true, false) => {
3134                        self.fatal_proc_rec(
3135                            &format!("`{}` should not have different output from base test!", kind),
3136                            proc_res,
3137                        );
3138                    }
3139                    _ => {}
3140                }
3141            };
3142            for mode in modes {
3143                check_and_prune_duplicate_outputs(mode, false);
3144            }
3145            for mode in require_same_modes {
3146                check_and_prune_duplicate_outputs(mode, true);
3147            }
3148        }
3149    }
3150
3151    fn create_stamp(&self) {
3152        let stamp_file_path =
3153            discovery::stamp_file_path(&self.config, self.testpaths, self.variant);
3154        fs::write(&stamp_file_path, compute_stamp_hash(&self.config, self.variant)).unwrap();
3155    }
3156
3157    fn init_incremental_test(&self) {
3158        // (See `run_incremental_test` for an overview of how incremental tests work.)
3159
3160        // Before any of the revisions have executed, create the
3161        // incremental workproduct directory.  Delete any old
3162        // incremental work products that may be there from prior
3163        // runs.
3164        let incremental_dir = self.props.incremental_dir.as_ref().unwrap();
3165        if incremental_dir.exists() {
3166            // Canonicalizing the path will convert it to the //?/ format
3167            // on Windows, which enables paths longer than 260 character
3168            let canonicalized = incremental_dir.canonicalize().unwrap();
3169            fs::remove_dir_all(canonicalized).unwrap();
3170        }
3171        fs::create_dir_all(&incremental_dir).unwrap();
3172
3173        if self.config.verbose {
3174            writeln!(self.stdout, "init_incremental_test: incremental_dir={incremental_dir}");
3175        }
3176    }
3177}
3178
3179struct ProcArgs {
3180    prog: OsString,
3181    args: Vec<OsString>,
3182}
3183
3184#[derive(Debug)]
3185pub(crate) struct ProcRes {
3186    status: ExitStatus,
3187    stdout: String,
3188    stderr: String,
3189    truncated: Truncated,
3190    cmdline: String,
3191}
3192
3193impl ProcRes {
3194    #[must_use]
3195    pub(crate) fn format_info(&self) -> String {
3196        fn render(name: &str, contents: &str) -> String {
3197            let contents = json::extract_rendered(contents);
3198            let contents = contents.trim_end();
3199            if contents.is_empty() {
3200                format!("{name}: none")
3201            } else {
3202                format!(
3203                    "\
3204                     --- {name} -------------------------------\n\
3205                     {contents}\n\
3206                     ------------------------------------------",
3207                )
3208            }
3209        }
3210
3211        format!(
3212            "status: {}\ncommand: {}\n{}\n{}\n",
3213            self.status,
3214            self.cmdline,
3215            render("stdout", &self.stdout),
3216            render("stderr", &self.stderr),
3217        )
3218    }
3219}
3220
3221#[derive(Debug)]
3222enum TargetLocation {
3223    ThisFile(Utf8PathBuf),
3224    ThisDirectory(Utf8PathBuf),
3225}
3226
3227enum AllowUnused {
3228    Yes,
3229    No,
3230}
3231
3232enum LinkToAux {
3233    Yes,
3234    No,
3235}
3236
3237#[derive(Debug, PartialEq)]
3238enum AuxType {
3239    Bin,
3240    Lib,
3241    Dylib,
3242    ProcMacro,
3243    Lint,
3244}
3245
3246/// Outcome of comparing a stream to a blessed file,
3247/// e.g. `.stderr` and `.fixed`.
3248#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3249enum CompareOutcome {
3250    /// Expected and actual outputs are the same
3251    Same,
3252    /// Outputs differed but were blessed
3253    Blessed,
3254    /// Outputs differed and an error should be emitted
3255    Differed,
3256}
3257
3258#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3259enum DocKind {
3260    Html,
3261    Json,
3262}
3263
3264impl CompareOutcome {
3265    fn should_error(&self) -> bool {
3266        matches!(self, CompareOutcome::Differed)
3267    }
3268}