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