]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/runtest.rs
8af5f1da694b9f59bd87a7611495c10f1f70b9ea
[rust.git] / src / tools / compiletest / src / runtest.rs
1 // ignore-tidy-filelength
2
3 use crate::common::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT};
4 use crate::common::{incremental_dir, output_base_dir, output_base_name, output_testname_unique};
5 use crate::common::{Assembly, Incremental, JsDocTest, MirOpt, RunMake, RustdocJson, Ui};
6 use crate::common::{Codegen, CodegenUnits, DebugInfo, Debugger, Rustdoc};
7 use crate::common::{CompareMode, FailMode, PassMode};
8 use crate::common::{Config, TestPaths};
9 use crate::common::{Pretty, RunPassValgrind};
10 use crate::common::{UI_RUN_STDERR, UI_RUN_STDOUT};
11 use crate::compute_diff::{write_diff, write_filtered_diff};
12 use crate::errors::{self, Error, ErrorKind};
13 use crate::header::TestProps;
14 use crate::json;
15 use crate::read2::read2_abbreviated;
16 use crate::util::{logv, PathBufExt};
17 use crate::ColorConfig;
18 use regex::{Captures, Regex};
19 use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
20
21 use std::collections::hash_map::DefaultHasher;
22 use std::collections::{HashMap, HashSet};
23 use std::env;
24 use std::ffi::{OsStr, OsString};
25 use std::fs::{self, create_dir_all, File, OpenOptions};
26 use std::hash::{Hash, Hasher};
27 use std::io::prelude::*;
28 use std::io::{self, BufReader};
29 use std::path::{Path, PathBuf};
30 use std::process::{Child, Command, ExitStatus, Output, Stdio};
31 use std::str;
32
33 use glob::glob;
34 use lazy_static::lazy_static;
35 use tracing::*;
36
37 use crate::extract_gdb_version;
38 use crate::is_android_gdb_target;
39
40 mod debugger;
41 use debugger::{check_debugger_output, DebuggerCommands};
42
43 #[cfg(test)]
44 mod tests;
45
46 #[cfg(windows)]
47 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
48     use std::sync::Mutex;
49     use winapi::um::errhandlingapi::SetErrorMode;
50     use winapi::um::winbase::SEM_NOGPFAULTERRORBOX;
51
52     lazy_static! {
53         static ref LOCK: Mutex<()> = Mutex::new(());
54     }
55     // Error mode is a global variable, so lock it so only one thread will change it
56     let _lock = LOCK.lock().unwrap();
57
58     // Tell Windows to not show any UI on errors (such as terminating abnormally).
59     // This is important for running tests, since some of them use abnormal
60     // termination by design. This mode is inherited by all child processes.
61     unsafe {
62         let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX); // read inherited flags
63         SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX);
64         let r = f();
65         SetErrorMode(old_mode);
66         r
67     }
68 }
69
70 #[cfg(not(windows))]
71 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
72     f()
73 }
74
75 /// The name of the environment variable that holds dynamic library locations.
76 pub fn dylib_env_var() -> &'static str {
77     if cfg!(windows) {
78         "PATH"
79     } else if cfg!(target_os = "macos") {
80         "DYLD_LIBRARY_PATH"
81     } else if cfg!(target_os = "haiku") {
82         "LIBRARY_PATH"
83     } else {
84         "LD_LIBRARY_PATH"
85     }
86 }
87
88 /// The platform-specific library name
89 pub fn get_lib_name(lib: &str, dylib: bool) -> String {
90     // In some casess (e.g. MUSL), we build a static
91     // library, rather than a dynamic library.
92     // In this case, the only path we can pass
93     // with '--extern-meta' is the '.lib' file
94     if !dylib {
95         return format!("lib{}.rlib", lib);
96     }
97
98     if cfg!(windows) {
99         format!("{}.dll", lib)
100     } else if cfg!(target_os = "macos") {
101         format!("lib{}.dylib", lib)
102     } else {
103         format!("lib{}.so", lib)
104     }
105 }
106
107 pub fn run(config: Config, testpaths: &TestPaths, revision: Option<&str>) {
108     match &*config.target {
109         "arm-linux-androideabi"
110         | "armv7-linux-androideabi"
111         | "thumbv7neon-linux-androideabi"
112         | "aarch64-linux-android" => {
113             if !config.adb_device_status {
114                 panic!("android device not available");
115             }
116         }
117
118         _ => {
119             // android has its own gdb handling
120             if config.debugger == Some(Debugger::Gdb) && config.gdb.is_none() {
121                 panic!("gdb not available but debuginfo gdb debuginfo test requested");
122             }
123         }
124     }
125
126     if config.verbose {
127         // We're going to be dumping a lot of info. Start on a new line.
128         print!("\n\n");
129     }
130     debug!("running {:?}", testpaths.file.display());
131     let mut props = TestProps::from_file(&testpaths.file, revision, &config);
132     if props.incremental {
133         props.incremental_dir = Some(incremental_dir(&config, testpaths));
134     }
135
136     let cx = TestCx { config: &config, props: &props, testpaths, revision };
137     create_dir_all(&cx.output_base_dir()).unwrap();
138     if props.incremental {
139         cx.init_incremental_test();
140     }
141
142     if config.mode == Incremental {
143         // Incremental tests are special because they cannot be run in
144         // parallel.
145         assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
146         for revision in &props.revisions {
147             let mut revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
148             revision_props.incremental_dir = props.incremental_dir.clone();
149             let rev_cx = TestCx {
150                 config: &config,
151                 props: &revision_props,
152                 testpaths,
153                 revision: Some(revision),
154             };
155             rev_cx.run_revision();
156         }
157     } else {
158         cx.run_revision();
159     }
160
161     cx.create_stamp();
162 }
163
164 pub fn compute_stamp_hash(config: &Config) -> String {
165     let mut hash = DefaultHasher::new();
166     config.stage_id.hash(&mut hash);
167     config.run.hash(&mut hash);
168
169     match config.debugger {
170         Some(Debugger::Cdb) => {
171             config.cdb.hash(&mut hash);
172         }
173
174         Some(Debugger::Gdb) => {
175             config.gdb.hash(&mut hash);
176             env::var_os("PATH").hash(&mut hash);
177             env::var_os("PYTHONPATH").hash(&mut hash);
178         }
179
180         Some(Debugger::Lldb) => {
181             config.python.hash(&mut hash);
182             config.lldb_python_dir.hash(&mut hash);
183             env::var_os("PATH").hash(&mut hash);
184             env::var_os("PYTHONPATH").hash(&mut hash);
185         }
186
187         None => {}
188     }
189
190     if let Ui = config.mode {
191         config.force_pass_mode.hash(&mut hash);
192     }
193
194     format!("{:x}", hash.finish())
195 }
196
197 #[derive(Copy, Clone)]
198 struct TestCx<'test> {
199     config: &'test Config,
200     props: &'test TestProps,
201     testpaths: &'test TestPaths,
202     revision: Option<&'test str>,
203 }
204
205 enum ReadFrom {
206     Path,
207     Stdin(String),
208 }
209
210 enum TestOutput {
211     Compile,
212     Run,
213 }
214
215 /// Will this test be executed? Should we use `make_exe_name`?
216 #[derive(Copy, Clone, PartialEq)]
217 enum WillExecute {
218     Yes,
219     No,
220     Disabled,
221 }
222
223 /// Should `--emit metadata` be used?
224 #[derive(Copy, Clone)]
225 enum EmitMetadata {
226     Yes,
227     No,
228 }
229
230 impl<'test> TestCx<'test> {
231     /// Code executed for each revision in turn (or, if there are no
232     /// revisions, exactly once, with revision == None).
233     fn run_revision(&self) {
234         if self.props.should_ice && self.config.mode != Incremental {
235             self.fatal("cannot use should-ice in a test that is not cfail");
236         }
237         match self.config.mode {
238             RunPassValgrind => self.run_valgrind_test(),
239             Pretty => self.run_pretty_test(),
240             DebugInfo => self.run_debuginfo_test(),
241             Codegen => self.run_codegen_test(),
242             Rustdoc => self.run_rustdoc_test(),
243             RustdocJson => self.run_rustdoc_json_test(),
244             CodegenUnits => self.run_codegen_units_test(),
245             Incremental => self.run_incremental_test(),
246             RunMake => self.run_rmake_test(),
247             Ui => self.run_ui_test(),
248             MirOpt => self.run_mir_opt_test(),
249             Assembly => self.run_assembly_test(),
250             JsDocTest => self.run_js_doc_test(),
251         }
252     }
253
254     fn pass_mode(&self) -> Option<PassMode> {
255         self.props.pass_mode(self.config)
256     }
257
258     fn should_run(&self, pm: Option<PassMode>) -> WillExecute {
259         let test_should_run = match self.config.mode {
260             Ui if pm == Some(PassMode::Run) || self.props.fail_mode == Some(FailMode::Run) => true,
261             MirOpt if pm == Some(PassMode::Run) => true,
262             Ui | MirOpt => false,
263             mode => panic!("unimplemented for mode {:?}", mode),
264         };
265         if test_should_run { self.run_if_enabled() } else { WillExecute::No }
266     }
267
268     fn run_if_enabled(&self) -> WillExecute {
269         if self.config.run_enabled() { WillExecute::Yes } else { WillExecute::Disabled }
270     }
271
272     fn should_run_successfully(&self, pm: Option<PassMode>) -> bool {
273         match self.config.mode {
274             Ui | MirOpt => pm == Some(PassMode::Run),
275             mode => panic!("unimplemented for mode {:?}", mode),
276         }
277     }
278
279     fn should_compile_successfully(&self, pm: Option<PassMode>) -> bool {
280         match self.config.mode {
281             JsDocTest => true,
282             Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
283             Incremental => {
284                 let revision =
285                     self.revision.expect("incremental tests require a list of revisions");
286                 if revision.starts_with("rpass") || revision.starts_with("rfail") {
287                     true
288                 } else if revision.starts_with("cfail") {
289                     // FIXME: would be nice if incremental revs could start with "cpass"
290                     pm.is_some()
291                 } else {
292                     panic!("revision name must begin with rpass, rfail, or cfail");
293                 }
294             }
295             mode => panic!("unimplemented for mode {:?}", mode),
296         }
297     }
298
299     fn check_if_test_should_compile(&self, proc_res: &ProcRes, pm: Option<PassMode>) {
300         if self.should_compile_successfully(pm) {
301             if !proc_res.status.success() {
302                 self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res);
303             }
304         } else {
305             if proc_res.status.success() {
306                 self.fatal_proc_rec(
307                     &format!("{} test compiled successfully!", self.config.mode)[..],
308                     proc_res,
309                 );
310             }
311
312             self.check_correct_failure_status(proc_res);
313         }
314     }
315
316     fn run_cfail_test(&self) {
317         let pm = self.pass_mode();
318         let proc_res = self.compile_test(WillExecute::No, self.should_emit_metadata(pm));
319         self.check_if_test_should_compile(&proc_res, pm);
320         self.check_no_compiler_crash(&proc_res, self.props.should_ice);
321
322         let output_to_check = self.get_output(&proc_res);
323         let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
324         if !expected_errors.is_empty() {
325             if !self.props.error_patterns.is_empty() || !self.props.regex_error_patterns.is_empty()
326             {
327                 self.fatal("both error pattern and expected errors specified");
328             }
329             self.check_expected_errors(expected_errors, &proc_res);
330         } else {
331             self.check_all_error_patterns(&output_to_check, &proc_res, pm);
332         }
333         if self.props.should_ice {
334             match proc_res.status.code() {
335                 Some(101) => (),
336                 _ => self.fatal("expected ICE"),
337             }
338         }
339
340         self.check_forbid_output(&output_to_check, &proc_res);
341     }
342
343     fn run_rfail_test(&self) {
344         let pm = self.pass_mode();
345         let should_run = self.run_if_enabled();
346         let proc_res = self.compile_test(should_run, self.should_emit_metadata(pm));
347
348         if !proc_res.status.success() {
349             self.fatal_proc_rec("compilation failed!", &proc_res);
350         }
351
352         if let WillExecute::Disabled = should_run {
353             return;
354         }
355
356         let proc_res = self.exec_compiled_test();
357
358         // The value our Makefile configures valgrind to return on failure
359         const VALGRIND_ERR: i32 = 100;
360         if proc_res.status.code() == Some(VALGRIND_ERR) {
361             self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
362         }
363
364         let output_to_check = self.get_output(&proc_res);
365         self.check_correct_failure_status(&proc_res);
366         self.check_all_error_patterns(&output_to_check, &proc_res, pm);
367     }
368
369     fn get_output(&self, proc_res: &ProcRes) -> String {
370         if self.props.check_stdout {
371             format!("{}{}", proc_res.stdout, proc_res.stderr)
372         } else {
373             proc_res.stderr.clone()
374         }
375     }
376
377     fn check_correct_failure_status(&self, proc_res: &ProcRes) {
378         let expected_status = Some(self.props.failure_status);
379         let received_status = proc_res.status.code();
380
381         if expected_status != received_status {
382             self.fatal_proc_rec(
383                 &format!(
384                     "Error: expected failure status ({:?}) but received status {:?}.",
385                     expected_status, received_status
386                 ),
387                 proc_res,
388             );
389         }
390     }
391
392     fn run_rpass_test(&self) {
393         let emit_metadata = self.should_emit_metadata(self.pass_mode());
394         let should_run = self.run_if_enabled();
395         let proc_res = self.compile_test(should_run, emit_metadata);
396
397         if !proc_res.status.success() {
398             self.fatal_proc_rec("compilation failed!", &proc_res);
399         }
400
401         if let WillExecute::Disabled = should_run {
402             return;
403         }
404
405         // FIXME(#41968): Move this check to tidy?
406         let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
407         assert!(
408             expected_errors.is_empty(),
409             "run-pass tests with expected warnings should be moved to ui/"
410         );
411
412         let proc_res = self.exec_compiled_test();
413         if !proc_res.status.success() {
414             self.fatal_proc_rec("test run failed!", &proc_res);
415         }
416     }
417
418     fn run_valgrind_test(&self) {
419         assert!(self.revision.is_none(), "revisions not relevant here");
420
421         if self.config.valgrind_path.is_none() {
422             assert!(!self.config.force_valgrind);
423             return self.run_rpass_test();
424         }
425
426         let should_run = self.run_if_enabled();
427         let mut proc_res = self.compile_test(should_run, EmitMetadata::No);
428
429         if !proc_res.status.success() {
430             self.fatal_proc_rec("compilation failed!", &proc_res);
431         }
432
433         if let WillExecute::Disabled = should_run {
434             return;
435         }
436
437         let mut new_config = self.config.clone();
438         new_config.runtool = new_config.valgrind_path.clone();
439         let new_cx = TestCx { config: &new_config, ..*self };
440         proc_res = new_cx.exec_compiled_test();
441
442         if !proc_res.status.success() {
443             self.fatal_proc_rec("test run failed!", &proc_res);
444         }
445     }
446
447     fn run_pretty_test(&self) {
448         if self.props.pp_exact.is_some() {
449             logv(self.config, "testing for exact pretty-printing".to_owned());
450         } else {
451             logv(self.config, "testing for converging pretty-printing".to_owned());
452         }
453
454         let rounds = match self.props.pp_exact {
455             Some(_) => 1,
456             None => 2,
457         };
458
459         let src = fs::read_to_string(&self.testpaths.file).unwrap();
460         let mut srcs = vec![src];
461
462         let mut round = 0;
463         while round < rounds {
464             logv(
465                 self.config,
466                 format!("pretty-printing round {} revision {:?}", round, self.revision),
467             );
468             let read_from =
469                 if round == 0 { ReadFrom::Path } else { ReadFrom::Stdin(srcs[round].to_owned()) };
470
471             let proc_res = self.print_source(read_from, &self.props.pretty_mode);
472             if !proc_res.status.success() {
473                 self.fatal_proc_rec(
474                     &format!(
475                         "pretty-printing failed in round {} revision {:?}",
476                         round, self.revision
477                     ),
478                     &proc_res,
479                 );
480             }
481
482             let ProcRes { stdout, .. } = proc_res;
483             srcs.push(stdout);
484             round += 1;
485         }
486
487         let mut expected = match self.props.pp_exact {
488             Some(ref file) => {
489                 let filepath = self.testpaths.file.parent().unwrap().join(file);
490                 fs::read_to_string(&filepath).unwrap()
491             }
492             None => srcs[srcs.len() - 2].clone(),
493         };
494         let mut actual = srcs[srcs.len() - 1].clone();
495
496         if self.props.pp_exact.is_some() {
497             // Now we have to care about line endings
498             let cr = "\r".to_owned();
499             actual = actual.replace(&cr, "");
500             expected = expected.replace(&cr, "");
501         }
502
503         if !self.config.bless {
504             self.compare_source(&expected, &actual);
505         } else if expected != actual {
506             let filepath_buf;
507             let filepath = match &self.props.pp_exact {
508                 Some(file) => {
509                     filepath_buf = self.testpaths.file.parent().unwrap().join(file);
510                     &filepath_buf
511                 }
512                 None => &self.testpaths.file,
513             };
514             fs::write(filepath, &actual).unwrap();
515         }
516
517         // If we're only making sure that the output matches then just stop here
518         if self.props.pretty_compare_only {
519             return;
520         }
521
522         // Finally, let's make sure it actually appears to remain valid code
523         let proc_res = self.typecheck_source(actual);
524         if !proc_res.status.success() {
525             self.fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
526         }
527
528         if !self.props.pretty_expanded {
529             return;
530         }
531
532         // additionally, run `-Zunpretty=expanded` and try to build it.
533         let proc_res = self.print_source(ReadFrom::Path, "expanded");
534         if !proc_res.status.success() {
535             self.fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
536         }
537
538         let ProcRes { stdout: expanded_src, .. } = proc_res;
539         let proc_res = self.typecheck_source(expanded_src);
540         if !proc_res.status.success() {
541             self.fatal_proc_rec("pretty-printed source (expanded) does not typecheck", &proc_res);
542         }
543     }
544
545     fn print_source(&self, read_from: ReadFrom, pretty_type: &str) -> ProcRes {
546         let aux_dir = self.aux_output_dir_name();
547         let input: &str = match read_from {
548             ReadFrom::Stdin(_) => "-",
549             ReadFrom::Path => self.testpaths.file.to_str().unwrap(),
550         };
551
552         let mut rustc = Command::new(&self.config.rustc_path);
553         rustc
554             .arg(input)
555             .args(&["-Z", &format!("unpretty={}", pretty_type)])
556             .args(&["--target", &self.config.target])
557             .arg("-L")
558             .arg(&aux_dir)
559             .args(&self.props.compile_flags)
560             .envs(self.props.rustc_env.clone());
561         self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
562
563         let src = match read_from {
564             ReadFrom::Stdin(src) => Some(src),
565             ReadFrom::Path => None,
566         };
567
568         self.compose_and_run(
569             rustc,
570             self.config.compile_lib_path.to_str().unwrap(),
571             Some(aux_dir.to_str().unwrap()),
572             src,
573         )
574     }
575
576     fn compare_source(&self, expected: &str, actual: &str) {
577         if expected != actual {
578             self.fatal(&format!(
579                 "pretty-printed source does not match expected source\n\
580                  expected:\n\
581                  ------------------------------------------\n\
582                  {}\n\
583                  ------------------------------------------\n\
584                  actual:\n\
585                  ------------------------------------------\n\
586                  {}\n\
587                  ------------------------------------------\n\
588                  diff:\n\
589                  ------------------------------------------\n\
590                  {}\n",
591                 expected,
592                 actual,
593                 write_diff(expected, actual, 3),
594             ));
595         }
596     }
597
598     fn set_revision_flags(&self, cmd: &mut Command) {
599         if let Some(revision) = self.revision {
600             // Normalize revisions to be lowercase and replace `-`s with `_`s.
601             // Otherwise the `--cfg` flag is not valid.
602             let normalized_revision = revision.to_lowercase().replace("-", "_");
603             cmd.args(&["--cfg", &normalized_revision]);
604         }
605     }
606
607     fn typecheck_source(&self, src: String) -> ProcRes {
608         let mut rustc = Command::new(&self.config.rustc_path);
609
610         let out_dir = self.output_base_name().with_extension("pretty-out");
611         let _ = fs::remove_dir_all(&out_dir);
612         create_dir_all(&out_dir).unwrap();
613
614         let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
615
616         let aux_dir = self.aux_output_dir_name();
617
618         rustc
619             .arg("-")
620             .arg("-Zno-codegen")
621             .arg("--out-dir")
622             .arg(&out_dir)
623             .arg(&format!("--target={}", target))
624             .arg("-L")
625             .arg(&self.config.build_base)
626             .arg("-L")
627             .arg(aux_dir);
628         self.set_revision_flags(&mut rustc);
629         self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
630         rustc.args(&self.props.compile_flags);
631
632         self.compose_and_run_compiler(rustc, Some(src))
633     }
634
635     fn run_debuginfo_test(&self) {
636         match self.config.debugger.unwrap() {
637             Debugger::Cdb => self.run_debuginfo_cdb_test(),
638             Debugger::Gdb => self.run_debuginfo_gdb_test(),
639             Debugger::Lldb => self.run_debuginfo_lldb_test(),
640         }
641     }
642
643     fn run_debuginfo_cdb_test(&self) {
644         let config = Config {
645             target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
646             host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
647             ..self.config.clone()
648         };
649
650         let test_cx = TestCx { config: &config, ..*self };
651
652         test_cx.run_debuginfo_cdb_test_no_opt();
653     }
654
655     fn run_debuginfo_cdb_test_no_opt(&self) {
656         let exe_file = self.make_exe_name();
657
658         // Existing PDB files are update in-place. When changing the debuginfo
659         // the compiler generates for something, this can lead to the situation
660         // where both the old and the new version of the debuginfo for the same
661         // type is present in the PDB, which is very confusing.
662         // Therefore we delete any existing PDB file before compiling the test
663         // case.
664         // FIXME: If can reliably detect that MSVC's link.exe is used, then
665         //        passing `/INCREMENTAL:NO` might be a cleaner way to do this.
666         let pdb_file = exe_file.with_extension(".pdb");
667         if pdb_file.exists() {
668             std::fs::remove_file(pdb_file).unwrap();
669         }
670
671         // compile test file (it should have 'compile-flags:-g' in the header)
672         let should_run = self.run_if_enabled();
673         let compile_result = self.compile_test(should_run, EmitMetadata::No);
674         if !compile_result.status.success() {
675             self.fatal_proc_rec("compilation failed!", &compile_result);
676         }
677         if let WillExecute::Disabled = should_run {
678             return;
679         }
680
681         let prefixes = {
682             static PREFIXES: &[&str] = &["cdb", "cdbg"];
683             // No "native rust support" variation for CDB yet.
684             PREFIXES
685         };
686
687         // Parse debugger commands etc from test files
688         let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
689             match DebuggerCommands::parse_from(
690                 &self.testpaths.file,
691                 self.config,
692                 prefixes,
693                 self.revision,
694             ) {
695                 Ok(cmds) => cmds,
696                 Err(e) => self.fatal(&e),
697             };
698
699         // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-commands
700         let mut script_str = String::with_capacity(2048);
701         script_str.push_str("version\n"); // List CDB (and more) version info in test output
702         script_str.push_str(".nvlist\n"); // List loaded `*.natvis` files, bulk of custom MSVC debug
703
704         // If a .js file exists next to the source file being tested, then this is a JavaScript
705         // debugging extension that needs to be loaded.
706         let mut js_extension = self.testpaths.file.clone();
707         js_extension.set_extension("cdb.js");
708         if js_extension.exists() {
709             script_str.push_str(&format!(".scriptload \"{}\"\n", js_extension.to_string_lossy()));
710         }
711
712         // Set breakpoints on every line that contains the string "#break"
713         let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
714         for line in &breakpoint_lines {
715             script_str.push_str(&format!("bp `{}:{}`\n", source_file_name, line));
716         }
717
718         // Append the other `cdb-command:`s
719         for line in &commands {
720             script_str.push_str(line);
721             script_str.push_str("\n");
722         }
723
724         script_str.push_str("\nqq\n"); // Quit the debugger (including remote debugger, if any)
725
726         // Write the script into a file
727         debug!("script_str = {}", script_str);
728         self.dump_output_file(&script_str, "debugger.script");
729         let debugger_script = self.make_out_name("debugger.script");
730
731         let cdb_path = &self.config.cdb.as_ref().unwrap();
732         let mut cdb = Command::new(cdb_path);
733         cdb.arg("-lines") // Enable source line debugging.
734             .arg("-cf")
735             .arg(&debugger_script)
736             .arg(&exe_file);
737
738         let debugger_run_result = self.compose_and_run(
739             cdb,
740             self.config.run_lib_path.to_str().unwrap(),
741             None, // aux_path
742             None, // input
743         );
744
745         if !debugger_run_result.status.success() {
746             self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
747         }
748
749         if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
750             self.fatal_proc_rec(&e, &debugger_run_result);
751         }
752     }
753
754     fn run_debuginfo_gdb_test(&self) {
755         let config = Config {
756             target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
757             host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
758             ..self.config.clone()
759         };
760
761         let test_cx = TestCx { config: &config, ..*self };
762
763         test_cx.run_debuginfo_gdb_test_no_opt();
764     }
765
766     fn run_debuginfo_gdb_test_no_opt(&self) {
767         let prefixes = if self.config.gdb_native_rust {
768             // GDB with Rust
769             static PREFIXES: &[&str] = &["gdb", "gdbr"];
770             println!("NOTE: compiletest thinks it is using GDB with native rust support");
771             PREFIXES
772         } else {
773             // Generic GDB
774             static PREFIXES: &[&str] = &["gdb", "gdbg"];
775             println!("NOTE: compiletest thinks it is using GDB without native rust support");
776             PREFIXES
777         };
778
779         let DebuggerCommands { commands, check_lines, breakpoint_lines } =
780             match DebuggerCommands::parse_from(
781                 &self.testpaths.file,
782                 self.config,
783                 prefixes,
784                 self.revision,
785             ) {
786                 Ok(cmds) => cmds,
787                 Err(e) => self.fatal(&e),
788             };
789         let mut cmds = commands.join("\n");
790
791         // compile test file (it should have 'compile-flags:-g' in the header)
792         let should_run = self.run_if_enabled();
793         let compiler_run_result = self.compile_test(should_run, EmitMetadata::No);
794         if !compiler_run_result.status.success() {
795             self.fatal_proc_rec("compilation failed!", &compiler_run_result);
796         }
797         if let WillExecute::Disabled = should_run {
798             return;
799         }
800
801         let exe_file = self.make_exe_name();
802
803         let debugger_run_result;
804         if is_android_gdb_target(&self.config.target) {
805             cmds = cmds.replace("run", "continue");
806
807             let tool_path = match self.config.android_cross_path.to_str() {
808                 Some(x) => x.to_owned(),
809                 None => self.fatal("cannot find android cross path"),
810             };
811
812             // write debugger script
813             let mut script_str = String::with_capacity(2048);
814             script_str.push_str(&format!("set charset {}\n", Self::charset()));
815             script_str.push_str(&format!("set sysroot {}\n", tool_path));
816             script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
817             script_str.push_str("target remote :5039\n");
818             script_str.push_str(&format!(
819                 "set solib-search-path \
820                  ./{}/stage2/lib/rustlib/{}/lib/\n",
821                 self.config.host, self.config.target
822             ));
823             for line in &breakpoint_lines {
824                 script_str.push_str(
825                     &format!(
826                         "break {:?}:{}\n",
827                         self.testpaths.file.file_name().unwrap().to_string_lossy(),
828                         *line
829                     )[..],
830                 );
831             }
832             script_str.push_str(&cmds);
833             script_str.push_str("\nquit\n");
834
835             debug!("script_str = {}", script_str);
836             self.dump_output_file(&script_str, "debugger.script");
837
838             let adb_path = &self.config.adb_path;
839
840             Command::new(adb_path)
841                 .arg("push")
842                 .arg(&exe_file)
843                 .arg(&self.config.adb_test_dir)
844                 .status()
845                 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
846
847             Command::new(adb_path)
848                 .args(&["forward", "tcp:5039", "tcp:5039"])
849                 .status()
850                 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
851
852             let adb_arg = format!(
853                 "export LD_LIBRARY_PATH={}; \
854                  gdbserver{} :5039 {}/{}",
855                 self.config.adb_test_dir.clone(),
856                 if self.config.target.contains("aarch64") { "64" } else { "" },
857                 self.config.adb_test_dir.clone(),
858                 exe_file.file_name().unwrap().to_str().unwrap()
859             );
860
861             debug!("adb arg: {}", adb_arg);
862             let mut adb = Command::new(adb_path)
863                 .args(&["shell", &adb_arg])
864                 .stdout(Stdio::piped())
865                 .stderr(Stdio::inherit())
866                 .spawn()
867                 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
868
869             // Wait for the gdbserver to print out "Listening on port ..."
870             // at which point we know that it's started and then we can
871             // execute the debugger below.
872             let mut stdout = BufReader::new(adb.stdout.take().unwrap());
873             let mut line = String::new();
874             loop {
875                 line.truncate(0);
876                 stdout.read_line(&mut line).unwrap();
877                 if line.starts_with("Listening on port 5039") {
878                     break;
879                 }
880             }
881             drop(stdout);
882
883             let mut debugger_script = OsString::from("-command=");
884             debugger_script.push(self.make_out_name("debugger.script"));
885             let debugger_opts: &[&OsStr] =
886                 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
887
888             let gdb_path = self.config.gdb.as_ref().unwrap();
889             let Output { status, stdout, stderr } = Command::new(&gdb_path)
890                 .args(debugger_opts)
891                 .output()
892                 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", gdb_path));
893             let cmdline = {
894                 let mut gdb = Command::new(&format!("{}-gdb", self.config.target));
895                 gdb.args(debugger_opts);
896                 let cmdline = self.make_cmdline(&gdb, "");
897                 logv(self.config, format!("executing {}", cmdline));
898                 cmdline
899             };
900
901             debugger_run_result = ProcRes {
902                 status,
903                 stdout: String::from_utf8(stdout).unwrap(),
904                 stderr: String::from_utf8(stderr).unwrap(),
905                 cmdline,
906             };
907             if adb.kill().is_err() {
908                 println!("Adb process is already finished.");
909             }
910         } else {
911             let rust_src_root =
912                 self.config.find_rust_src_root().expect("Could not find Rust source root");
913             let rust_pp_module_rel_path = Path::new("./src/etc");
914             let rust_pp_module_abs_path =
915                 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
916             // write debugger script
917             let mut script_str = String::with_capacity(2048);
918             script_str.push_str(&format!("set charset {}\n", Self::charset()));
919             script_str.push_str("show version\n");
920
921             match self.config.gdb_version {
922                 Some(version) => {
923                     println!("NOTE: compiletest thinks it is using GDB version {}", version);
924
925                     if version > extract_gdb_version("7.4").unwrap() {
926                         // Add the directory containing the pretty printers to
927                         // GDB's script auto loading safe path
928                         script_str.push_str(&format!(
929                             "add-auto-load-safe-path {}\n",
930                             rust_pp_module_abs_path.replace(r"\", r"\\")
931                         ));
932
933                         let output_base_dir = self.output_base_dir().to_str().unwrap().to_owned();
934
935                         // Add the directory containing the output binary to
936                         // include embedded pretty printers to GDB's script
937                         // auto loading safe path
938                         script_str.push_str(&format!(
939                             "add-auto-load-safe-path {}\n",
940                             output_base_dir.replace(r"\", r"\\")
941                         ));
942                     }
943                 }
944                 _ => {
945                     println!(
946                         "NOTE: compiletest does not know which version of \
947                          GDB it is using"
948                     );
949                 }
950             }
951
952             // The following line actually doesn't have to do anything with
953             // pretty printing, it just tells GDB to print values on one line:
954             script_str.push_str("set print pretty off\n");
955
956             // Add the pretty printer directory to GDB's source-file search path
957             script_str
958                 .push_str(&format!("directory {}\n", rust_pp_module_abs_path.replace(r"\", r"\\")));
959
960             // Load the target executable
961             script_str
962                 .push_str(&format!("file {}\n", exe_file.to_str().unwrap().replace(r"\", r"\\")));
963
964             // Force GDB to print values in the Rust format.
965             if self.config.gdb_native_rust {
966                 script_str.push_str("set language rust\n");
967             }
968
969             // Add line breakpoints
970             for line in &breakpoint_lines {
971                 script_str.push_str(&format!(
972                     "break '{}':{}\n",
973                     self.testpaths.file.file_name().unwrap().to_string_lossy(),
974                     *line
975                 ));
976             }
977
978             script_str.push_str(&cmds);
979             script_str.push_str("\nquit\n");
980
981             debug!("script_str = {}", script_str);
982             self.dump_output_file(&script_str, "debugger.script");
983
984             let mut debugger_script = OsString::from("-command=");
985             debugger_script.push(self.make_out_name("debugger.script"));
986
987             let debugger_opts: &[&OsStr] =
988                 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
989
990             let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
991             gdb.args(debugger_opts).env("PYTHONPATH", rust_pp_module_abs_path);
992
993             debugger_run_result =
994                 self.compose_and_run(gdb, self.config.run_lib_path.to_str().unwrap(), None, None);
995         }
996
997         if !debugger_run_result.status.success() {
998             self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
999         }
1000
1001         if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
1002             self.fatal_proc_rec(&e, &debugger_run_result);
1003         }
1004     }
1005
1006     fn run_debuginfo_lldb_test(&self) {
1007         if self.config.lldb_python_dir.is_none() {
1008             self.fatal("Can't run LLDB test because LLDB's python path is not set.");
1009         }
1010
1011         let config = Config {
1012             target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
1013             host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
1014             ..self.config.clone()
1015         };
1016
1017         let test_cx = TestCx { config: &config, ..*self };
1018
1019         test_cx.run_debuginfo_lldb_test_no_opt();
1020     }
1021
1022     fn run_debuginfo_lldb_test_no_opt(&self) {
1023         // compile test file (it should have 'compile-flags:-g' in the header)
1024         let should_run = self.run_if_enabled();
1025         let compile_result = self.compile_test(should_run, EmitMetadata::No);
1026         if !compile_result.status.success() {
1027             self.fatal_proc_rec("compilation failed!", &compile_result);
1028         }
1029         if let WillExecute::Disabled = should_run {
1030             return;
1031         }
1032
1033         let exe_file = self.make_exe_name();
1034
1035         match self.config.lldb_version {
1036             Some(ref version) => {
1037                 println!("NOTE: compiletest thinks it is using LLDB version {}", version);
1038             }
1039             _ => {
1040                 println!(
1041                     "NOTE: compiletest does not know which version of \
1042                      LLDB it is using"
1043                 );
1044             }
1045         }
1046
1047         let prefixes = if self.config.lldb_native_rust {
1048             static PREFIXES: &[&str] = &["lldb", "lldbr"];
1049             println!("NOTE: compiletest thinks it is using LLDB with native rust support");
1050             PREFIXES
1051         } else {
1052             static PREFIXES: &[&str] = &["lldb", "lldbg"];
1053             println!("NOTE: compiletest thinks it is using LLDB without native rust support");
1054             PREFIXES
1055         };
1056
1057         // Parse debugger commands etc from test files
1058         let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
1059             match DebuggerCommands::parse_from(
1060                 &self.testpaths.file,
1061                 self.config,
1062                 prefixes,
1063                 self.revision,
1064             ) {
1065                 Ok(cmds) => cmds,
1066                 Err(e) => self.fatal(&e),
1067             };
1068
1069         // Write debugger script:
1070         // We don't want to hang when calling `quit` while the process is still running
1071         let mut script_str = String::from("settings set auto-confirm true\n");
1072
1073         // Make LLDB emit its version, so we have it documented in the test output
1074         script_str.push_str("version\n");
1075
1076         // Switch LLDB into "Rust mode"
1077         let rust_src_root =
1078             self.config.find_rust_src_root().expect("Could not find Rust source root");
1079         let rust_pp_module_rel_path = Path::new("./src/etc/lldb_lookup.py");
1080         let rust_pp_module_abs_path =
1081             rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
1082
1083         let rust_type_regexes = vec![
1084             "^(alloc::([a-z_]+::)+)String$",
1085             "^&(mut )?str$",
1086             "^&(mut )?\\[.+\\]$",
1087             "^(std::ffi::([a-z_]+::)+)OsString$",
1088             "^(alloc::([a-z_]+::)+)Vec<.+>$",
1089             "^(alloc::([a-z_]+::)+)VecDeque<.+>$",
1090             "^(alloc::([a-z_]+::)+)BTreeSet<.+>$",
1091             "^(alloc::([a-z_]+::)+)BTreeMap<.+>$",
1092             "^(std::collections::([a-z_]+::)+)HashMap<.+>$",
1093             "^(std::collections::([a-z_]+::)+)HashSet<.+>$",
1094             "^(alloc::([a-z_]+::)+)Rc<.+>$",
1095             "^(alloc::([a-z_]+::)+)Arc<.+>$",
1096             "^(core::([a-z_]+::)+)Cell<.+>$",
1097             "^(core::([a-z_]+::)+)Ref<.+>$",
1098             "^(core::([a-z_]+::)+)RefMut<.+>$",
1099             "^(core::([a-z_]+::)+)RefCell<.+>$",
1100             "^core::num::([a-z_]+::)*NonZero.+$",
1101         ];
1102
1103         script_str
1104             .push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[..])[..]);
1105         script_str.push_str("type synthetic add -l lldb_lookup.synthetic_lookup -x '.*' ");
1106         script_str.push_str("--category Rust\n");
1107         for type_regex in rust_type_regexes {
1108             script_str.push_str("type summary add -F lldb_lookup.summary_lookup  -e -x -h ");
1109             script_str.push_str(&format!("'{}' ", type_regex));
1110             script_str.push_str("--category Rust\n");
1111         }
1112         script_str.push_str("type category enable Rust\n");
1113
1114         // Set breakpoints on every line that contains the string "#break"
1115         let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
1116         for line in &breakpoint_lines {
1117             script_str.push_str(&format!(
1118                 "breakpoint set --file '{}' --line {}\n",
1119                 source_file_name, line
1120             ));
1121         }
1122
1123         // Append the other commands
1124         for line in &commands {
1125             script_str.push_str(line);
1126             script_str.push_str("\n");
1127         }
1128
1129         // Finally, quit the debugger
1130         script_str.push_str("\nquit\n");
1131
1132         // Write the script into a file
1133         debug!("script_str = {}", script_str);
1134         self.dump_output_file(&script_str, "debugger.script");
1135         let debugger_script = self.make_out_name("debugger.script");
1136
1137         // Let LLDB execute the script via lldb_batchmode.py
1138         let debugger_run_result = self.run_lldb(&exe_file, &debugger_script, &rust_src_root);
1139
1140         if !debugger_run_result.status.success() {
1141             self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
1142         }
1143
1144         if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
1145             self.fatal_proc_rec(&e, &debugger_run_result);
1146         }
1147     }
1148
1149     fn run_lldb(
1150         &self,
1151         test_executable: &Path,
1152         debugger_script: &Path,
1153         rust_src_root: &Path,
1154     ) -> ProcRes {
1155         // Prepare the lldb_batchmode which executes the debugger script
1156         let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
1157         self.cmd2procres(
1158             Command::new(&self.config.python)
1159                 .arg(&lldb_script_path)
1160                 .arg(test_executable)
1161                 .arg(debugger_script)
1162                 .env("PYTHONUNBUFFERED", "1") // Help debugging #78665
1163                 .env("PYTHONPATH", self.config.lldb_python_dir.as_ref().unwrap()),
1164         )
1165     }
1166
1167     fn cmd2procres(&self, cmd: &mut Command) -> ProcRes {
1168         let (status, out, err) = match cmd.output() {
1169             Ok(Output { status, stdout, stderr }) => {
1170                 (status, String::from_utf8(stdout).unwrap(), String::from_utf8(stderr).unwrap())
1171             }
1172             Err(e) => self.fatal(&format!(
1173                 "Failed to setup Python process for \
1174                  LLDB script: {}",
1175                 e
1176             )),
1177         };
1178
1179         self.dump_output(&out, &err);
1180         ProcRes { status, stdout: out, stderr: err, cmdline: format!("{:?}", cmd) }
1181     }
1182
1183     fn cleanup_debug_info_options(&self, options: &Vec<String>) -> Vec<String> {
1184         // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
1185         let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
1186
1187         options.iter().filter(|x| !options_to_remove.contains(x)).map(|x| x.clone()).collect()
1188     }
1189
1190     fn maybe_add_external_args(&self, cmd: &mut Command, args: &Vec<String>) {
1191         // Filter out the arguments that should not be added by runtest here.
1192         //
1193         // Notable use-cases are: do not add our optimisation flag if
1194         // `compile-flags: -Copt-level=x` and similar for debug-info level as well.
1195         const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", /*-C<space>*/ "opt-level="];
1196         const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", /*-C<space>*/ "debuginfo="];
1197
1198         // FIXME: ideally we would "just" check the `cmd` itself, but it does not allow inspecting
1199         // its arguments. They need to be collected separately. For now I cannot be bothered to
1200         // implement this the "right" way.
1201         let have_opt_flag =
1202             self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
1203         let have_debug_flag = self
1204             .props
1205             .compile_flags
1206             .iter()
1207             .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
1208
1209         for arg in args {
1210             if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
1211                 continue;
1212             }
1213             if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
1214                 continue;
1215             }
1216             cmd.arg(arg);
1217         }
1218     }
1219
1220     fn check_all_error_patterns(
1221         &self,
1222         output_to_check: &str,
1223         proc_res: &ProcRes,
1224         pm: Option<PassMode>,
1225     ) {
1226         if self.props.error_patterns.is_empty() && self.props.regex_error_patterns.is_empty() {
1227             if pm.is_some() {
1228                 // FIXME(#65865)
1229                 return;
1230             } else {
1231                 self.fatal(&format!(
1232                     "no error pattern specified in {:?}",
1233                     self.testpaths.file.display()
1234                 ));
1235             }
1236         }
1237
1238         let mut missing_patterns: Vec<String> = Vec::new();
1239
1240         self.check_error_patterns(output_to_check, &mut missing_patterns);
1241         self.check_regex_error_patterns(output_to_check, proc_res, &mut missing_patterns);
1242
1243         if missing_patterns.is_empty() {
1244             return;
1245         }
1246
1247         if missing_patterns.len() == 1 {
1248             self.fatal_proc_rec(
1249                 &format!("error pattern '{}' not found!", missing_patterns[0]),
1250                 proc_res,
1251             );
1252         } else {
1253             for pattern in missing_patterns {
1254                 self.error(&format!("error pattern '{}' not found!", pattern));
1255             }
1256             self.fatal_proc_rec("multiple error patterns not found", proc_res);
1257         }
1258     }
1259
1260     fn check_error_patterns(&self, output_to_check: &str, missing_patterns: &mut Vec<String>) {
1261         debug!("check_error_patterns");
1262         for pattern in &self.props.error_patterns {
1263             if output_to_check.contains(pattern.trim()) {
1264                 debug!("found error pattern {}", pattern);
1265             } else {
1266                 missing_patterns.push(pattern.to_string());
1267             }
1268         }
1269     }
1270
1271     fn check_regex_error_patterns(
1272         &self,
1273         output_to_check: &str,
1274         proc_res: &ProcRes,
1275         missing_patterns: &mut Vec<String>,
1276     ) {
1277         debug!("check_regex_error_patterns");
1278
1279         for pattern in &self.props.regex_error_patterns {
1280             let pattern = pattern.trim();
1281             let re = match Regex::new(pattern) {
1282                 Ok(re) => re,
1283                 Err(err) => {
1284                     self.fatal_proc_rec(
1285                         &format!("invalid regex error pattern '{}': {:?}", pattern, err),
1286                         proc_res,
1287                     );
1288                 }
1289             };
1290             if re.is_match(output_to_check) {
1291                 debug!("found regex error pattern {}", pattern);
1292             } else {
1293                 missing_patterns.push(pattern.to_string());
1294             }
1295         }
1296     }
1297
1298     fn check_no_compiler_crash(&self, proc_res: &ProcRes, should_ice: bool) {
1299         match proc_res.status.code() {
1300             Some(101) if !should_ice => {
1301                 self.fatal_proc_rec("compiler encountered internal error", proc_res)
1302             }
1303             None => self.fatal_proc_rec("compiler terminated by signal", proc_res),
1304             _ => (),
1305         }
1306     }
1307
1308     fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
1309         for pat in &self.props.forbid_output {
1310             if output_to_check.contains(pat) {
1311                 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
1312             }
1313         }
1314     }
1315
1316     fn check_expected_errors(&self, expected_errors: Vec<errors::Error>, proc_res: &ProcRes) {
1317         debug!(
1318             "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
1319             expected_errors, proc_res.status
1320         );
1321         if proc_res.status.success()
1322             && expected_errors.iter().any(|x| x.kind == Some(ErrorKind::Error))
1323         {
1324             self.fatal_proc_rec("process did not return an error status", proc_res);
1325         }
1326
1327         if self.props.known_bug {
1328             if !expected_errors.is_empty() {
1329                 self.fatal_proc_rec(
1330                     "`known_bug` tests should not have an expected errors",
1331                     proc_res,
1332                 );
1333             }
1334             return;
1335         }
1336
1337         // On Windows, keep all '\' path separators to match the paths reported in the JSON output
1338         // from the compiler
1339         let os_file_name = self.testpaths.file.display().to_string();
1340
1341         // on windows, translate all '\' path separators to '/'
1342         let file_name = format!("{}", self.testpaths.file.display()).replace(r"\", "/");
1343
1344         // If the testcase being checked contains at least one expected "help"
1345         // message, then we'll ensure that all "help" messages are expected.
1346         // Otherwise, all "help" messages reported by the compiler will be ignored.
1347         // This logic also applies to "note" messages.
1348         let expect_help = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Help));
1349         let expect_note = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Note));
1350
1351         // Parse the JSON output from the compiler and extract out the messages.
1352         let actual_errors = json::parse_output(&os_file_name, &proc_res.stderr, proc_res);
1353         let mut unexpected = Vec::new();
1354         let mut found = vec![false; expected_errors.len()];
1355         for actual_error in &actual_errors {
1356             let opt_index =
1357                 expected_errors.iter().enumerate().position(|(index, expected_error)| {
1358                     !found[index]
1359                         && actual_error.line_num == expected_error.line_num
1360                         && (expected_error.kind.is_none()
1361                             || actual_error.kind == expected_error.kind)
1362                         && actual_error.msg.contains(&expected_error.msg)
1363                 });
1364
1365             match opt_index {
1366                 Some(index) => {
1367                     // found a match, everybody is happy
1368                     assert!(!found[index]);
1369                     found[index] = true;
1370                 }
1371
1372                 None => {
1373                     // If the test is a known bug, don't require that the error is annotated
1374                     if self.is_unexpected_compiler_message(actual_error, expect_help, expect_note) {
1375                         self.error(&format!(
1376                             "{}:{}: unexpected {}: '{}'",
1377                             file_name,
1378                             actual_error.line_num,
1379                             actual_error
1380                                 .kind
1381                                 .as_ref()
1382                                 .map_or(String::from("message"), |k| k.to_string()),
1383                             actual_error.msg
1384                         ));
1385                         unexpected.push(actual_error);
1386                     }
1387                 }
1388             }
1389         }
1390
1391         let mut not_found = Vec::new();
1392         // anything not yet found is a problem
1393         for (index, expected_error) in expected_errors.iter().enumerate() {
1394             if !found[index] {
1395                 self.error(&format!(
1396                     "{}:{}: expected {} not found: {}",
1397                     file_name,
1398                     expected_error.line_num,
1399                     expected_error.kind.as_ref().map_or("message".into(), |k| k.to_string()),
1400                     expected_error.msg
1401                 ));
1402                 not_found.push(expected_error);
1403             }
1404         }
1405
1406         if !unexpected.is_empty() || !not_found.is_empty() {
1407             self.error(&format!(
1408                 "{} unexpected errors found, {} expected errors not found",
1409                 unexpected.len(),
1410                 not_found.len()
1411             ));
1412             println!("status: {}\ncommand: {}", proc_res.status, proc_res.cmdline);
1413             if !unexpected.is_empty() {
1414                 println!("unexpected errors (from JSON output): {:#?}\n", unexpected);
1415             }
1416             if !not_found.is_empty() {
1417                 println!("not found errors (from test file): {:#?}\n", not_found);
1418             }
1419             panic!();
1420         }
1421     }
1422
1423     /// Returns `true` if we should report an error about `actual_error`,
1424     /// which did not match any of the expected error. We always require
1425     /// errors/warnings to be explicitly listed, but only require
1426     /// helps/notes if there are explicit helps/notes given.
1427     fn is_unexpected_compiler_message(
1428         &self,
1429         actual_error: &Error,
1430         expect_help: bool,
1431         expect_note: bool,
1432     ) -> bool {
1433         match actual_error.kind {
1434             Some(ErrorKind::Help) => expect_help,
1435             Some(ErrorKind::Note) => expect_note,
1436             Some(ErrorKind::Error) | Some(ErrorKind::Warning) => true,
1437             Some(ErrorKind::Suggestion) | None => false,
1438         }
1439     }
1440
1441     fn should_emit_metadata(&self, pm: Option<PassMode>) -> EmitMetadata {
1442         match (pm, self.props.fail_mode, self.config.mode) {
1443             (Some(PassMode::Check), ..) | (_, Some(FailMode::Check), Ui) => EmitMetadata::Yes,
1444             _ => EmitMetadata::No,
1445         }
1446     }
1447
1448     fn compile_test(&self, will_execute: WillExecute, emit_metadata: EmitMetadata) -> ProcRes {
1449         self.compile_test_general(will_execute, emit_metadata, self.props.local_pass_mode())
1450     }
1451
1452     fn compile_test_general(
1453         &self,
1454         will_execute: WillExecute,
1455         emit_metadata: EmitMetadata,
1456         local_pm: Option<PassMode>,
1457     ) -> ProcRes {
1458         // Only use `make_exe_name` when the test ends up being executed.
1459         let output_file = match will_execute {
1460             WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
1461             WillExecute::No | WillExecute::Disabled => {
1462                 TargetLocation::ThisDirectory(self.output_base_dir())
1463             }
1464         };
1465
1466         let allow_unused = match self.config.mode {
1467             Ui => {
1468                 // UI tests tend to have tons of unused code as
1469                 // it's just testing various pieces of the compile, but we don't
1470                 // want to actually assert warnings about all this code. Instead
1471                 // let's just ignore unused code warnings by defaults and tests
1472                 // can turn it back on if needed.
1473                 if !self.is_rustdoc()
1474                     // Note that we use the local pass mode here as we don't want
1475                     // to set unused to allow if we've overridden the pass mode
1476                     // via command line flags.
1477                     && local_pm != Some(PassMode::Run)
1478                 {
1479                     AllowUnused::Yes
1480                 } else {
1481                     AllowUnused::No
1482                 }
1483             }
1484             _ => AllowUnused::No,
1485         };
1486
1487         let mut rustc =
1488             self.make_compile_args(&self.testpaths.file, output_file, emit_metadata, allow_unused);
1489
1490         rustc.arg("-L").arg(&self.aux_output_dir_name());
1491
1492         self.compose_and_run_compiler(rustc, None)
1493     }
1494
1495     fn document(&self, out_dir: &Path) -> ProcRes {
1496         if self.props.build_aux_docs {
1497             for rel_ab in &self.props.aux_builds {
1498                 let aux_testpaths = self.compute_aux_test_paths(rel_ab);
1499                 let aux_props =
1500                     self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1501                 let aux_cx = TestCx {
1502                     config: self.config,
1503                     props: &aux_props,
1504                     testpaths: &aux_testpaths,
1505                     revision: self.revision,
1506                 };
1507                 // Create the directory for the stdout/stderr files.
1508                 create_dir_all(aux_cx.output_base_dir()).unwrap();
1509                 let auxres = aux_cx.document(out_dir);
1510                 if !auxres.status.success() {
1511                     return auxres;
1512                 }
1513             }
1514         }
1515
1516         let aux_dir = self.aux_output_dir_name();
1517
1518         let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path not passed");
1519         let mut rustdoc = Command::new(rustdoc_path);
1520
1521         rustdoc
1522             .arg("-L")
1523             .arg(self.config.run_lib_path.to_str().unwrap())
1524             .arg("-L")
1525             .arg(aux_dir)
1526             .arg("-o")
1527             .arg(out_dir)
1528             .arg("--deny")
1529             .arg("warnings")
1530             .arg(&self.testpaths.file)
1531             .args(&self.props.compile_flags);
1532
1533         if self.config.mode == RustdocJson {
1534             rustdoc.arg("--output-format").arg("json").arg("-Zunstable-options");
1535         }
1536
1537         if let Some(ref linker) = self.config.linker {
1538             rustdoc.arg(format!("-Clinker={}", linker));
1539         }
1540
1541         self.compose_and_run_compiler(rustdoc, None)
1542     }
1543
1544     fn exec_compiled_test(&self) -> ProcRes {
1545         let env = &self.props.exec_env;
1546
1547         let proc_res = match &*self.config.target {
1548             // This is pretty similar to below, we're transforming:
1549             //
1550             //      program arg1 arg2
1551             //
1552             // into
1553             //
1554             //      remote-test-client run program 2 support-lib.so support-lib2.so arg1 arg2
1555             //
1556             // The test-client program will upload `program` to the emulator
1557             // along with all other support libraries listed (in this case
1558             // `support-lib.so` and `support-lib2.so`. It will then execute
1559             // the program on the emulator with the arguments specified
1560             // (in the environment we give the process) and then report back
1561             // the same result.
1562             _ if self.config.remote_test_client.is_some() => {
1563                 let aux_dir = self.aux_output_dir_name();
1564                 let ProcArgs { prog, args } = self.make_run_args();
1565                 let mut support_libs = Vec::new();
1566                 if let Ok(entries) = aux_dir.read_dir() {
1567                     for entry in entries {
1568                         let entry = entry.unwrap();
1569                         if !entry.path().is_file() {
1570                             continue;
1571                         }
1572                         support_libs.push(entry.path());
1573                     }
1574                 }
1575                 let mut test_client =
1576                     Command::new(self.config.remote_test_client.as_ref().unwrap());
1577                 test_client
1578                     .args(&["run", &support_libs.len().to_string(), &prog])
1579                     .args(support_libs)
1580                     .args(args)
1581                     .envs(env.clone());
1582                 self.compose_and_run(
1583                     test_client,
1584                     self.config.run_lib_path.to_str().unwrap(),
1585                     Some(aux_dir.to_str().unwrap()),
1586                     None,
1587                 )
1588             }
1589             _ if self.config.target.contains("vxworks") => {
1590                 let aux_dir = self.aux_output_dir_name();
1591                 let ProcArgs { prog, args } = self.make_run_args();
1592                 let mut wr_run = Command::new("wr-run");
1593                 wr_run.args(&[&prog]).args(args).envs(env.clone());
1594                 self.compose_and_run(
1595                     wr_run,
1596                     self.config.run_lib_path.to_str().unwrap(),
1597                     Some(aux_dir.to_str().unwrap()),
1598                     None,
1599                 )
1600             }
1601             _ => {
1602                 let aux_dir = self.aux_output_dir_name();
1603                 let ProcArgs { prog, args } = self.make_run_args();
1604                 let mut program = Command::new(&prog);
1605                 program.args(args).current_dir(&self.output_base_dir()).envs(env.clone());
1606                 self.compose_and_run(
1607                     program,
1608                     self.config.run_lib_path.to_str().unwrap(),
1609                     Some(aux_dir.to_str().unwrap()),
1610                     None,
1611                 )
1612             }
1613         };
1614
1615         if proc_res.status.success() {
1616             // delete the executable after running it to save space.
1617             // it is ok if the deletion failed.
1618             let _ = fs::remove_file(self.make_exe_name());
1619         }
1620
1621         proc_res
1622     }
1623
1624     /// For each `aux-build: foo/bar` annotation, we check to find the
1625     /// file in an `auxiliary` directory relative to the test itself.
1626     fn compute_aux_test_paths(&self, rel_ab: &str) -> TestPaths {
1627         let test_ab = self
1628             .testpaths
1629             .file
1630             .parent()
1631             .expect("test file path has no parent")
1632             .join("auxiliary")
1633             .join(rel_ab);
1634         if !test_ab.exists() {
1635             self.fatal(&format!("aux-build `{}` source not found", test_ab.display()))
1636         }
1637
1638         TestPaths {
1639             file: test_ab,
1640             relative_dir: self
1641                 .testpaths
1642                 .relative_dir
1643                 .join(self.output_testname_unique())
1644                 .join("auxiliary")
1645                 .join(rel_ab)
1646                 .parent()
1647                 .expect("aux-build path has no parent")
1648                 .to_path_buf(),
1649         }
1650     }
1651
1652     fn is_vxworks_pure_static(&self) -> bool {
1653         if self.config.target.contains("vxworks") {
1654             match env::var("RUST_VXWORKS_TEST_DYLINK") {
1655                 Ok(s) => s != "1",
1656                 _ => true,
1657             }
1658         } else {
1659             false
1660         }
1661     }
1662
1663     fn is_vxworks_pure_dynamic(&self) -> bool {
1664         self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1665     }
1666
1667     fn build_all_auxiliary(&self, rustc: &mut Command) -> PathBuf {
1668         let aux_dir = self.aux_output_dir_name();
1669
1670         if !self.props.aux_builds.is_empty() {
1671             let _ = fs::remove_dir_all(&aux_dir);
1672             create_dir_all(&aux_dir).unwrap();
1673         }
1674
1675         for rel_ab in &self.props.aux_builds {
1676             self.build_auxiliary(rel_ab, &aux_dir);
1677         }
1678
1679         for (aux_name, aux_path) in &self.props.aux_crates {
1680             let is_dylib = self.build_auxiliary(&aux_path, &aux_dir);
1681             let lib_name =
1682                 get_lib_name(&aux_path.trim_end_matches(".rs").replace('-', "_"), is_dylib);
1683             rustc.arg("--extern").arg(format!("{}={}/{}", aux_name, aux_dir.display(), lib_name));
1684         }
1685
1686         aux_dir
1687     }
1688
1689     fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1690         let aux_dir = self.build_all_auxiliary(&mut rustc);
1691         self.props.unset_rustc_env.iter().fold(&mut rustc, Command::env_remove);
1692         rustc.envs(self.props.rustc_env.clone());
1693         self.compose_and_run(
1694             rustc,
1695             self.config.compile_lib_path.to_str().unwrap(),
1696             Some(aux_dir.to_str().unwrap()),
1697             input,
1698         )
1699     }
1700
1701     /// Builds an aux dependency.
1702     ///
1703     /// Returns whether or not it is a dylib.
1704     fn build_auxiliary(&self, source_path: &str, aux_dir: &Path) -> bool {
1705         let aux_testpaths = self.compute_aux_test_paths(source_path);
1706         let aux_props = self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1707         let aux_output = TargetLocation::ThisDirectory(self.aux_output_dir_name());
1708         let aux_cx = TestCx {
1709             config: self.config,
1710             props: &aux_props,
1711             testpaths: &aux_testpaths,
1712             revision: self.revision,
1713         };
1714         // Create the directory for the stdout/stderr files.
1715         create_dir_all(aux_cx.output_base_dir()).unwrap();
1716         let input_file = &aux_testpaths.file;
1717         let mut aux_rustc =
1718             aux_cx.make_compile_args(input_file, aux_output, EmitMetadata::No, AllowUnused::No);
1719
1720         for key in &aux_props.unset_rustc_env {
1721             aux_rustc.env_remove(key);
1722         }
1723         aux_rustc.envs(aux_props.rustc_env.clone());
1724
1725         let (dylib, crate_type) = if aux_props.no_prefer_dynamic {
1726             (true, None)
1727         } else if self.config.target.contains("emscripten")
1728             || (self.config.target.contains("musl")
1729                 && !aux_props.force_host
1730                 && !self.config.host.contains("musl"))
1731             || self.config.target.contains("wasm32")
1732             || self.config.target.contains("nvptx")
1733             || self.is_vxworks_pure_static()
1734             || self.config.target.contains("sgx")
1735             || self.config.target.contains("bpf")
1736         {
1737             // We primarily compile all auxiliary libraries as dynamic libraries
1738             // to avoid code size bloat and large binaries as much as possible
1739             // for the test suite (otherwise including libstd statically in all
1740             // executables takes up quite a bit of space).
1741             //
1742             // For targets like MUSL or Emscripten, however, there is no support for
1743             // dynamic libraries so we just go back to building a normal library. Note,
1744             // however, that for MUSL if the library is built with `force_host` then
1745             // it's ok to be a dylib as the host should always support dylibs.
1746             (false, Some("lib"))
1747         } else {
1748             (true, Some("dylib"))
1749         };
1750
1751         if let Some(crate_type) = crate_type {
1752             aux_rustc.args(&["--crate-type", crate_type]);
1753         }
1754
1755         aux_rustc.arg("-L").arg(&aux_dir);
1756
1757         let auxres = aux_cx.compose_and_run(
1758             aux_rustc,
1759             aux_cx.config.compile_lib_path.to_str().unwrap(),
1760             Some(aux_dir.to_str().unwrap()),
1761             None,
1762         );
1763         if !auxres.status.success() {
1764             self.fatal_proc_rec(
1765                 &format!(
1766                     "auxiliary build of {:?} failed to compile: ",
1767                     aux_testpaths.file.display()
1768                 ),
1769                 &auxres,
1770             );
1771         }
1772         dylib
1773     }
1774
1775     fn read2_abbreviated(&self, child: Child) -> Output {
1776         let mut filter_paths_from_len = Vec::new();
1777         let mut add_path = |path: &Path| {
1778             let path = path.display().to_string();
1779             let windows = path.replace("\\", "\\\\");
1780             if windows != path {
1781                 filter_paths_from_len.push(windows);
1782             }
1783             filter_paths_from_len.push(path);
1784         };
1785
1786         // List of paths that will not be measured when determining whether the output is larger
1787         // than the output truncation threshold.
1788         //
1789         // Note: avoid adding a subdirectory of an already filtered directory here, otherwise the
1790         // same slice of text will be double counted and the truncation might not happen.
1791         add_path(&self.config.src_base);
1792         add_path(&self.config.build_base);
1793
1794         read2_abbreviated(child, &filter_paths_from_len).expect("failed to read output")
1795     }
1796
1797     fn compose_and_run(
1798         &self,
1799         mut command: Command,
1800         lib_path: &str,
1801         aux_path: Option<&str>,
1802         input: Option<String>,
1803     ) -> ProcRes {
1804         let cmdline = {
1805             let cmdline = self.make_cmdline(&command, lib_path);
1806             logv(self.config, format!("executing {}", cmdline));
1807             cmdline
1808         };
1809
1810         command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
1811
1812         // Need to be sure to put both the lib_path and the aux path in the dylib
1813         // search path for the child.
1814         let mut path =
1815             env::split_paths(&env::var_os(dylib_env_var()).unwrap_or_default()).collect::<Vec<_>>();
1816         if let Some(p) = aux_path {
1817             path.insert(0, PathBuf::from(p))
1818         }
1819         path.insert(0, PathBuf::from(lib_path));
1820
1821         // Add the new dylib search path var
1822         let newpath = env::join_paths(&path).unwrap();
1823         command.env(dylib_env_var(), newpath);
1824
1825         let mut child = disable_error_reporting(|| command.spawn())
1826             .unwrap_or_else(|_| panic!("failed to exec `{:?}`", &command));
1827         if let Some(input) = input {
1828             child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
1829         }
1830
1831         let Output { status, stdout, stderr } = self.read2_abbreviated(child);
1832
1833         let result = ProcRes {
1834             status,
1835             stdout: String::from_utf8_lossy(&stdout).into_owned(),
1836             stderr: String::from_utf8_lossy(&stderr).into_owned(),
1837             cmdline,
1838         };
1839
1840         self.dump_output(&result.stdout, &result.stderr);
1841
1842         result
1843     }
1844
1845     fn is_rustdoc(&self) -> bool {
1846         self.config.src_base.ends_with("rustdoc-ui")
1847             || self.config.src_base.ends_with("rustdoc-js")
1848             || self.config.src_base.ends_with("rustdoc-json")
1849     }
1850
1851     fn make_compile_args(
1852         &self,
1853         input_file: &Path,
1854         output_file: TargetLocation,
1855         emit_metadata: EmitMetadata,
1856         allow_unused: AllowUnused,
1857     ) -> Command {
1858         let is_aux = input_file.components().map(|c| c.as_os_str()).any(|c| c == "auxiliary");
1859         let is_rustdoc = self.is_rustdoc() && !is_aux;
1860         let mut rustc = if !is_rustdoc {
1861             Command::new(&self.config.rustc_path)
1862         } else {
1863             Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1864         };
1865         rustc.arg(input_file);
1866
1867         // Use a single thread for efficiency and a deterministic error message order
1868         rustc.arg("-Zthreads=1");
1869
1870         // Optionally prevent default --target if specified in test compile-flags.
1871         let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target"));
1872
1873         if !custom_target {
1874             let target =
1875                 if self.props.force_host { &*self.config.host } else { &*self.config.target };
1876
1877             rustc.arg(&format!("--target={}", target));
1878         }
1879         self.set_revision_flags(&mut rustc);
1880
1881         if !is_rustdoc {
1882             if let Some(ref incremental_dir) = self.props.incremental_dir {
1883                 rustc.args(&["-C", &format!("incremental={}", incremental_dir.display())]);
1884                 rustc.args(&["-Z", "incremental-verify-ich"]);
1885             }
1886
1887             if self.config.mode == CodegenUnits {
1888                 rustc.args(&["-Z", "human_readable_cgu_names"]);
1889             }
1890         }
1891
1892         if self.config.optimize_tests && !is_rustdoc {
1893             match self.config.mode {
1894                 Ui => {
1895                     // If optimize-tests is true we still only want to optimize tests that actually get
1896                     // executed and that don't specify their own optimization levels.
1897                     // Note: aux libs don't have a pass-mode, so they won't get optimized
1898                     // unless compile-flags are set in the aux file.
1899                     if self.config.optimize_tests
1900                         && self.props.pass_mode(&self.config) == Some(PassMode::Run)
1901                         && !self
1902                             .props
1903                             .compile_flags
1904                             .iter()
1905                             .any(|arg| arg == "-O" || arg.contains("opt-level"))
1906                     {
1907                         rustc.arg("-O");
1908                     }
1909                 }
1910                 DebugInfo => { /* debuginfo tests must be unoptimized */ }
1911                 _ => {
1912                     rustc.arg("-O");
1913                 }
1914             }
1915         }
1916
1917         match self.config.mode {
1918             Incremental => {
1919                 // If we are extracting and matching errors in the new
1920                 // fashion, then you want JSON mode. Old-skool error
1921                 // patterns still match the raw compiler output.
1922                 if self.props.error_patterns.is_empty()
1923                     && self.props.regex_error_patterns.is_empty()
1924                 {
1925                     rustc.args(&["--error-format", "json"]);
1926                     rustc.args(&["--json", "future-incompat"]);
1927                 }
1928                 rustc.arg("-Zui-testing");
1929                 rustc.arg("-Zdeduplicate-diagnostics=no");
1930             }
1931             Ui => {
1932                 if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) {
1933                     rustc.args(&["--error-format", "json"]);
1934                     rustc.args(&["--json", "future-incompat"]);
1935                 }
1936                 rustc.arg("-Ccodegen-units=1");
1937                 rustc.arg("-Zui-testing");
1938                 rustc.arg("-Zdeduplicate-diagnostics=no");
1939                 // FIXME: use this for other modes too, for perf?
1940                 rustc.arg("-Cstrip=debuginfo");
1941             }
1942             MirOpt => {
1943                 rustc.args(&[
1944                     "-Copt-level=1",
1945                     "-Zdump-mir=all",
1946                     "-Zvalidate-mir",
1947                     "-Zdump-mir-exclude-pass-number",
1948                     "-Zmir-pretty-relative-line-numbers=yes",
1949                 ]);
1950                 if let Some(pass) = &self.props.mir_unit_test {
1951                     rustc.args(&["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{}", pass)]);
1952                 } else {
1953                     rustc.arg("-Zmir-opt-level=4");
1954                 }
1955
1956                 let mir_dump_dir = self.get_mir_dump_dir();
1957                 let _ = fs::remove_dir_all(&mir_dump_dir);
1958                 create_dir_all(mir_dump_dir.as_path()).unwrap();
1959                 let mut dir_opt = "-Zdump-mir-dir=".to_string();
1960                 dir_opt.push_str(mir_dump_dir.to_str().unwrap());
1961                 debug!("dir_opt: {:?}", dir_opt);
1962
1963                 rustc.arg(dir_opt);
1964             }
1965             RunPassValgrind | Pretty | DebugInfo | Codegen | Rustdoc | RustdocJson | RunMake
1966             | CodegenUnits | JsDocTest | Assembly => {
1967                 // do not use JSON output
1968             }
1969         }
1970
1971         if let (false, EmitMetadata::Yes) = (is_rustdoc, emit_metadata) {
1972             rustc.args(&["--emit", "metadata"]);
1973         }
1974
1975         if !is_rustdoc {
1976             if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() {
1977                 // rustc.arg("-g"); // get any backtrace at all on errors
1978             } else if !self.props.no_prefer_dynamic {
1979                 rustc.args(&["-C", "prefer-dynamic"]);
1980             }
1981         }
1982
1983         match output_file {
1984             TargetLocation::ThisFile(path) => {
1985                 rustc.arg("-o").arg(path);
1986             }
1987             TargetLocation::ThisDirectory(path) => {
1988                 if is_rustdoc {
1989                     // `rustdoc` uses `-o` for the output directory.
1990                     rustc.arg("-o").arg(path);
1991                 } else {
1992                     rustc.arg("--out-dir").arg(path);
1993                 }
1994             }
1995         }
1996
1997         match self.config.compare_mode {
1998             Some(CompareMode::Polonius) => {
1999                 rustc.args(&["-Zpolonius"]);
2000             }
2001             Some(CompareMode::Chalk) => {
2002                 rustc.args(&["-Zchalk"]);
2003             }
2004             Some(CompareMode::SplitDwarf) if self.config.target.contains("windows") => {
2005                 rustc.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]);
2006             }
2007             Some(CompareMode::SplitDwarf) => {
2008                 rustc.args(&["-Csplit-debuginfo=unpacked"]);
2009             }
2010             Some(CompareMode::SplitDwarfSingle) => {
2011                 rustc.args(&["-Csplit-debuginfo=packed"]);
2012             }
2013             None => {}
2014         }
2015
2016         // Add `-A unused` before `config` flags and in-test (`props`) flags, so that they can
2017         // overwrite this.
2018         if let AllowUnused::Yes = allow_unused {
2019             rustc.args(&["-A", "unused"]);
2020         }
2021
2022         if self.props.force_host {
2023             self.maybe_add_external_args(&mut rustc, &self.config.host_rustcflags);
2024         } else {
2025             self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
2026             if !is_rustdoc {
2027                 if let Some(ref linker) = self.config.linker {
2028                     rustc.arg(format!("-Clinker={}", linker));
2029                 }
2030             }
2031         }
2032
2033         // Use dynamic musl for tests because static doesn't allow creating dylibs
2034         if self.config.host.contains("musl") || self.is_vxworks_pure_dynamic() {
2035             rustc.arg("-Ctarget-feature=-crt-static");
2036         }
2037
2038         rustc.args(&self.props.compile_flags);
2039
2040         rustc
2041     }
2042
2043     fn make_exe_name(&self) -> PathBuf {
2044         // Using a single letter here to keep the path length down for
2045         // Windows.  Some test names get very long.  rustc creates `rcgu`
2046         // files with the module name appended to it which can more than
2047         // double the length.
2048         let mut f = self.output_base_dir().join("a");
2049         // FIXME: This is using the host architecture exe suffix, not target!
2050         if self.config.target.contains("emscripten") {
2051             f = f.with_extra_extension("js");
2052         } else if self.config.target.contains("wasm32") {
2053             f = f.with_extra_extension("wasm");
2054         } else if self.config.target.contains("spirv") {
2055             f = f.with_extra_extension("spv");
2056         } else if !env::consts::EXE_SUFFIX.is_empty() {
2057             f = f.with_extra_extension(env::consts::EXE_SUFFIX);
2058         }
2059         f
2060     }
2061
2062     fn make_run_args(&self) -> ProcArgs {
2063         // If we've got another tool to run under (valgrind),
2064         // then split apart its command
2065         let mut args = self.split_maybe_args(&self.config.runtool);
2066
2067         // If this is emscripten, then run tests under nodejs
2068         if self.config.target.contains("emscripten") {
2069             if let Some(ref p) = self.config.nodejs {
2070                 args.push(p.clone());
2071             } else {
2072                 self.fatal("no NodeJS binary found (--nodejs)");
2073             }
2074         // If this is otherwise wasm, then run tests under nodejs with our
2075         // shim
2076         } else if self.config.target.contains("wasm32") {
2077             if let Some(ref p) = self.config.nodejs {
2078                 args.push(p.clone());
2079             } else {
2080                 self.fatal("no NodeJS binary found (--nodejs)");
2081             }
2082
2083             let src = self
2084                 .config
2085                 .src_base
2086                 .parent()
2087                 .unwrap() // chop off `ui`
2088                 .parent()
2089                 .unwrap() // chop off `test`
2090                 .parent()
2091                 .unwrap(); // chop off `src`
2092             args.push(src.join("src/etc/wasm32-shim.js").display().to_string());
2093         }
2094
2095         let exe_file = self.make_exe_name();
2096
2097         // FIXME (#9639): This needs to handle non-utf8 paths
2098         args.push(exe_file.to_str().unwrap().to_owned());
2099
2100         // Add the arguments in the run_flags directive
2101         args.extend(self.split_maybe_args(&self.props.run_flags));
2102
2103         let prog = args.remove(0);
2104         ProcArgs { prog, args }
2105     }
2106
2107     fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<String> {
2108         match *argstr {
2109             Some(ref s) => s
2110                 .split(' ')
2111                 .filter_map(|s| {
2112                     if s.chars().all(|c| c.is_whitespace()) { None } else { Some(s.to_owned()) }
2113                 })
2114                 .collect(),
2115             None => Vec::new(),
2116         }
2117     }
2118
2119     fn make_cmdline(&self, command: &Command, libpath: &str) -> String {
2120         use crate::util;
2121
2122         // Linux and mac don't require adjusting the library search path
2123         if cfg!(unix) {
2124             format!("{:?}", command)
2125         } else {
2126             // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
2127             // for diagnostic purposes
2128             fn lib_path_cmd_prefix(path: &str) -> String {
2129                 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
2130             }
2131
2132             format!("{} {:?}", lib_path_cmd_prefix(libpath), command)
2133         }
2134     }
2135
2136     fn dump_output(&self, out: &str, err: &str) {
2137         let revision = if let Some(r) = self.revision { format!("{}.", r) } else { String::new() };
2138
2139         self.dump_output_file(out, &format!("{}out", revision));
2140         self.dump_output_file(err, &format!("{}err", revision));
2141         self.maybe_dump_to_stdout(out, err);
2142     }
2143
2144     fn dump_output_file(&self, out: &str, extension: &str) {
2145         let outfile = self.make_out_name(extension);
2146         fs::write(&outfile, out).unwrap();
2147     }
2148
2149     /// Creates a filename for output with the given extension.
2150     /// E.g., `/.../testname.revision.mode/testname.extension`.
2151     fn make_out_name(&self, extension: &str) -> PathBuf {
2152         self.output_base_name().with_extension(extension)
2153     }
2154
2155     /// Gets the directory where auxiliary files are written.
2156     /// E.g., `/.../testname.revision.mode/auxiliary/`.
2157     fn aux_output_dir_name(&self) -> PathBuf {
2158         self.output_base_dir()
2159             .join("auxiliary")
2160             .with_extra_extension(self.config.mode.disambiguator())
2161     }
2162
2163     /// Generates a unique name for the test, such as `testname.revision.mode`.
2164     fn output_testname_unique(&self) -> PathBuf {
2165         output_testname_unique(self.config, self.testpaths, self.safe_revision())
2166     }
2167
2168     /// The revision, ignored for incremental compilation since it wants all revisions in
2169     /// the same directory.
2170     fn safe_revision(&self) -> Option<&str> {
2171         if self.config.mode == Incremental { None } else { self.revision }
2172     }
2173
2174     /// Gets the absolute path to the directory where all output for the given
2175     /// test/revision should reside.
2176     /// E.g., `/path/to/build/host-triple/test/ui/relative/testname.revision.mode/`.
2177     fn output_base_dir(&self) -> PathBuf {
2178         output_base_dir(self.config, self.testpaths, self.safe_revision())
2179     }
2180
2181     /// Gets the absolute path to the base filename used as output for the given
2182     /// test/revision.
2183     /// E.g., `/.../relative/testname.revision.mode/testname`.
2184     fn output_base_name(&self) -> PathBuf {
2185         output_base_name(self.config, self.testpaths, self.safe_revision())
2186     }
2187
2188     fn maybe_dump_to_stdout(&self, out: &str, err: &str) {
2189         if self.config.verbose {
2190             println!("------stdout------------------------------");
2191             println!("{}", out);
2192             println!("------stderr------------------------------");
2193             println!("{}", err);
2194             println!("------------------------------------------");
2195         }
2196     }
2197
2198     fn error(&self, err: &str) {
2199         match self.revision {
2200             Some(rev) => println!("\nerror in revision `{}`: {}", rev, err),
2201             None => println!("\nerror: {}", err),
2202         }
2203     }
2204
2205     fn fatal(&self, err: &str) -> ! {
2206         self.error(err);
2207         error!("fatal error, panic: {:?}", err);
2208         panic!("fatal error");
2209     }
2210
2211     fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2212         self.error(err);
2213         proc_res.fatal(None, || ());
2214     }
2215
2216     fn fatal_proc_rec_with_ctx(
2217         &self,
2218         err: &str,
2219         proc_res: &ProcRes,
2220         on_failure: impl FnOnce(Self),
2221     ) -> ! {
2222         self.error(err);
2223         proc_res.fatal(None, || on_failure(*self));
2224     }
2225
2226     // codegen tests (using FileCheck)
2227
2228     fn compile_test_and_save_ir(&self) -> ProcRes {
2229         let aux_dir = self.aux_output_dir_name();
2230
2231         let output_file = TargetLocation::ThisDirectory(self.output_base_dir());
2232         let input_file = &self.testpaths.file;
2233         let mut rustc =
2234             self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2235         rustc.arg("-L").arg(aux_dir).arg("--emit=llvm-ir");
2236
2237         self.compose_and_run_compiler(rustc, None)
2238     }
2239
2240     fn compile_test_and_save_assembly(&self) -> (ProcRes, PathBuf) {
2241         // This works with both `--emit asm` (as default output name for the assembly)
2242         // and `ptx-linker` because the latter can write output at requested location.
2243         let output_path = self.output_base_name().with_extension("s");
2244
2245         let output_file = TargetLocation::ThisFile(output_path.clone());
2246         let input_file = &self.testpaths.file;
2247         let mut rustc =
2248             self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2249
2250         rustc.arg("-L").arg(self.aux_output_dir_name());
2251
2252         match self.props.assembly_output.as_ref().map(AsRef::as_ref) {
2253             Some("emit-asm") => {
2254                 rustc.arg("--emit=asm");
2255             }
2256
2257             Some("ptx-linker") => {
2258                 // No extra flags needed.
2259             }
2260
2261             Some(_) => self.fatal("unknown 'assembly-output' header"),
2262             None => self.fatal("missing 'assembly-output' header"),
2263         }
2264
2265         (self.compose_and_run_compiler(rustc, None), output_path)
2266     }
2267
2268     fn verify_with_filecheck(&self, output: &Path) -> ProcRes {
2269         let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2270         filecheck.arg("--input-file").arg(output).arg(&self.testpaths.file);
2271         // It would be more appropriate to make most of the arguments configurable through
2272         // a comment-attribute similar to `compile-flags`. For example, --check-prefixes is a very
2273         // useful flag.
2274         //
2275         // For now, though…
2276         let prefix_for_target =
2277             if self.config.target.contains("msvc") { "MSVC" } else { "NONMSVC" };
2278         let prefixes = if let Some(rev) = self.revision {
2279             format!("CHECK,{},{}", prefix_for_target, rev)
2280         } else {
2281             format!("CHECK,{}", prefix_for_target)
2282         };
2283         if self.config.llvm_version.unwrap_or(0) >= 130000 {
2284             filecheck.args(&["--allow-unused-prefixes", "--check-prefixes", &prefixes]);
2285         } else {
2286             filecheck.args(&["--check-prefixes", &prefixes]);
2287         }
2288         self.compose_and_run(filecheck, "", None, None)
2289     }
2290
2291     fn run_codegen_test(&self) {
2292         if self.config.llvm_filecheck.is_none() {
2293             self.fatal("missing --llvm-filecheck");
2294         }
2295
2296         let proc_res = self.compile_test_and_save_ir();
2297         if !proc_res.status.success() {
2298             self.fatal_proc_rec("compilation failed!", &proc_res);
2299         }
2300
2301         let output_path = self.output_base_name().with_extension("ll");
2302         let proc_res = self.verify_with_filecheck(&output_path);
2303         if !proc_res.status.success() {
2304             self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2305         }
2306     }
2307
2308     fn run_assembly_test(&self) {
2309         if self.config.llvm_filecheck.is_none() {
2310             self.fatal("missing --llvm-filecheck");
2311         }
2312
2313         let (proc_res, output_path) = self.compile_test_and_save_assembly();
2314         if !proc_res.status.success() {
2315             self.fatal_proc_rec("compilation failed!", &proc_res);
2316         }
2317
2318         let proc_res = self.verify_with_filecheck(&output_path);
2319         if !proc_res.status.success() {
2320             self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2321         }
2322     }
2323
2324     fn charset() -> &'static str {
2325         // FreeBSD 10.1 defaults to GDB 6.1.1 which doesn't support "auto" charset
2326         if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" }
2327     }
2328
2329     fn run_rustdoc_test(&self) {
2330         assert!(self.revision.is_none(), "revisions not relevant here");
2331
2332         let out_dir = self.output_base_dir();
2333         let _ = fs::remove_dir_all(&out_dir);
2334         create_dir_all(&out_dir).unwrap();
2335
2336         let proc_res = self.document(&out_dir);
2337         if !proc_res.status.success() {
2338             self.fatal_proc_rec("rustdoc failed!", &proc_res);
2339         }
2340
2341         if self.props.check_test_line_numbers_match {
2342             self.check_rustdoc_test_option(proc_res);
2343         } else {
2344             let root = self.config.find_rust_src_root().unwrap();
2345             let mut cmd = Command::new(&self.config.python);
2346             cmd.arg(root.join("src/etc/htmldocck.py")).arg(&out_dir).arg(&self.testpaths.file);
2347             if self.config.bless {
2348                 cmd.arg("--bless");
2349             }
2350             let res = self.cmd2procres(&mut cmd);
2351             if !res.status.success() {
2352                 self.fatal_proc_rec_with_ctx("htmldocck failed!", &res, |mut this| {
2353                     this.compare_to_default_rustdoc(&out_dir)
2354                 });
2355             }
2356         }
2357     }
2358
2359     fn compare_to_default_rustdoc(&mut self, out_dir: &Path) {
2360         if !self.config.has_tidy {
2361             return;
2362         }
2363         println!("info: generating a diff against nightly rustdoc");
2364
2365         let suffix =
2366             self.safe_revision().map_or("nightly".into(), |path| path.to_owned() + "-nightly");
2367         let compare_dir = output_base_dir(self.config, self.testpaths, Some(&suffix));
2368         // Don't give an error if the directory didn't already exist
2369         let _ = fs::remove_dir_all(&compare_dir);
2370         create_dir_all(&compare_dir).unwrap();
2371
2372         // We need to create a new struct for the lifetimes on `config` to work.
2373         let new_rustdoc = TestCx {
2374             config: &Config {
2375                 // FIXME: use beta or a user-specified rustdoc instead of
2376                 // hardcoding the default toolchain
2377                 rustdoc_path: Some("rustdoc".into()),
2378                 // Needed for building auxiliary docs below
2379                 rustc_path: "rustc".into(),
2380                 ..self.config.clone()
2381             },
2382             ..*self
2383         };
2384
2385         let output_file = TargetLocation::ThisDirectory(new_rustdoc.aux_output_dir_name());
2386         let mut rustc = new_rustdoc.make_compile_args(
2387             &new_rustdoc.testpaths.file,
2388             output_file,
2389             EmitMetadata::No,
2390             AllowUnused::Yes,
2391         );
2392         rustc.arg("-L").arg(&new_rustdoc.aux_output_dir_name());
2393         new_rustdoc.build_all_auxiliary(&mut rustc);
2394
2395         let proc_res = new_rustdoc.document(&compare_dir);
2396         if !proc_res.status.success() {
2397             eprintln!("failed to run nightly rustdoc");
2398             return;
2399         }
2400
2401         #[rustfmt::skip]
2402         let tidy_args = [
2403             "--indent", "yes",
2404             "--indent-spaces", "2",
2405             "--wrap", "0",
2406             "--show-warnings", "no",
2407             "--markup", "yes",
2408             "--quiet", "yes",
2409             "-modify",
2410         ];
2411         let tidy_dir = |dir| {
2412             for entry in walkdir::WalkDir::new(dir) {
2413                 let entry = entry.expect("failed to read file");
2414                 if entry.file_type().is_file()
2415                     && entry.path().extension().and_then(|p| p.to_str()) == Some("html".into())
2416                 {
2417                     let status =
2418                         Command::new("tidy").args(&tidy_args).arg(entry.path()).status().unwrap();
2419                     // `tidy` returns 1 if it modified the file.
2420                     assert!(status.success() || status.code() == Some(1));
2421                 }
2422             }
2423         };
2424         tidy_dir(out_dir);
2425         tidy_dir(&compare_dir);
2426
2427         let pager = {
2428             let output = Command::new("git").args(&["config", "--get", "core.pager"]).output().ok();
2429             output.and_then(|out| {
2430                 if out.status.success() {
2431                     Some(String::from_utf8(out.stdout).expect("invalid UTF8 in git pager"))
2432                 } else {
2433                     None
2434                 }
2435             })
2436         };
2437
2438         let diff_filename = format!("build/tmp/rustdoc-compare-{}.diff", std::process::id());
2439
2440         if !write_filtered_diff(
2441             &diff_filename,
2442             out_dir,
2443             &compare_dir,
2444             self.config.verbose,
2445             |file_type, extension| {
2446                 file_type.is_file()
2447                     && (extension == Some("html".into()) || extension == Some("js".into()))
2448             },
2449         ) {
2450             return;
2451         }
2452
2453         match self.config.color {
2454             ColorConfig::AlwaysColor => colored::control::set_override(true),
2455             ColorConfig::NeverColor => colored::control::set_override(false),
2456             _ => {}
2457         }
2458
2459         if let Some(pager) = pager {
2460             let pager = pager.trim();
2461             if self.config.verbose {
2462                 eprintln!("using pager {}", pager);
2463             }
2464             let output = Command::new(pager)
2465                 // disable paging; we want this to be non-interactive
2466                 .env("PAGER", "")
2467                 .stdin(File::open(&diff_filename).unwrap())
2468                 // Capture output and print it explicitly so it will in turn be
2469                 // captured by libtest.
2470                 .output()
2471                 .unwrap();
2472             assert!(output.status.success());
2473             println!("{}", String::from_utf8_lossy(&output.stdout));
2474             eprintln!("{}", String::from_utf8_lossy(&output.stderr));
2475         } else {
2476             use colored::Colorize;
2477             eprintln!("warning: no pager configured, falling back to unified diff");
2478             eprintln!(
2479                 "help: try configuring a git pager (e.g. `delta`) with `git config --global core.pager delta`"
2480             );
2481             let mut out = io::stdout();
2482             let mut diff = BufReader::new(File::open(&diff_filename).unwrap());
2483             let mut line = Vec::new();
2484             loop {
2485                 line.truncate(0);
2486                 match diff.read_until(b'\n', &mut line) {
2487                     Ok(0) => break,
2488                     Ok(_) => {}
2489                     Err(e) => eprintln!("ERROR: {:?}", e),
2490                 }
2491                 match String::from_utf8(line.clone()) {
2492                     Ok(line) => {
2493                         if line.starts_with("+") {
2494                             write!(&mut out, "{}", line.green()).unwrap();
2495                         } else if line.starts_with("-") {
2496                             write!(&mut out, "{}", line.red()).unwrap();
2497                         } else if line.starts_with("@") {
2498                             write!(&mut out, "{}", line.blue()).unwrap();
2499                         } else {
2500                             out.write_all(line.as_bytes()).unwrap();
2501                         }
2502                     }
2503                     Err(_) => {
2504                         write!(&mut out, "{}", String::from_utf8_lossy(&line).reversed()).unwrap();
2505                     }
2506                 }
2507             }
2508         };
2509     }
2510
2511     fn run_rustdoc_json_test(&self) {
2512         //FIXME: Add bless option.
2513
2514         assert!(self.revision.is_none(), "revisions not relevant here");
2515
2516         let out_dir = self.output_base_dir();
2517         let _ = fs::remove_dir_all(&out_dir);
2518         create_dir_all(&out_dir).unwrap();
2519
2520         let proc_res = self.document(&out_dir);
2521         if !proc_res.status.success() {
2522             self.fatal_proc_rec("rustdoc failed!", &proc_res);
2523         }
2524
2525         let root = self.config.find_rust_src_root().unwrap();
2526         let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap());
2527         json_out.set_extension("json");
2528         let res = self.cmd2procres(
2529             Command::new(self.config.jsondocck_path.as_ref().unwrap())
2530                 .arg("--doc-dir")
2531                 .arg(root.join(&out_dir))
2532                 .arg("--template")
2533                 .arg(&self.testpaths.file),
2534         );
2535
2536         if !res.status.success() {
2537             self.fatal_proc_rec_with_ctx("jsondocck failed!", &res, |_| {
2538                 println!("Rustdoc Output:");
2539                 proc_res.print_info();
2540             })
2541         }
2542
2543         let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap());
2544         json_out.set_extension("json");
2545
2546         let res = self.cmd2procres(
2547             Command::new(self.config.jsondoclint_path.as_ref().unwrap()).arg(&json_out),
2548         );
2549
2550         if !res.status.success() {
2551             self.fatal_proc_rec("jsondoclint failed!", &res);
2552         }
2553     }
2554
2555     fn get_lines<P: AsRef<Path>>(
2556         &self,
2557         path: &P,
2558         mut other_files: Option<&mut Vec<String>>,
2559     ) -> Vec<usize> {
2560         let content = fs::read_to_string(&path).unwrap();
2561         let mut ignore = false;
2562         content
2563             .lines()
2564             .enumerate()
2565             .filter_map(|(line_nb, line)| {
2566                 if (line.trim_start().starts_with("pub mod ")
2567                     || line.trim_start().starts_with("mod "))
2568                     && line.ends_with(';')
2569                 {
2570                     if let Some(ref mut other_files) = other_files {
2571                         other_files.push(line.rsplit("mod ").next().unwrap().replace(";", ""));
2572                     }
2573                     None
2574                 } else {
2575                     let sline = line.rsplit("///").next().unwrap();
2576                     let line = sline.trim_start();
2577                     if line.starts_with("```") {
2578                         if ignore {
2579                             ignore = false;
2580                             None
2581                         } else {
2582                             ignore = true;
2583                             Some(line_nb + 1)
2584                         }
2585                     } else {
2586                         None
2587                     }
2588                 }
2589             })
2590             .collect()
2591     }
2592
2593     fn check_rustdoc_test_option(&self, res: ProcRes) {
2594         let mut other_files = Vec::new();
2595         let mut files: HashMap<String, Vec<usize>> = HashMap::new();
2596         let cwd = env::current_dir().unwrap();
2597         files.insert(
2598             self.testpaths
2599                 .file
2600                 .strip_prefix(&cwd)
2601                 .unwrap_or(&self.testpaths.file)
2602                 .to_str()
2603                 .unwrap()
2604                 .replace('\\', "/"),
2605             self.get_lines(&self.testpaths.file, Some(&mut other_files)),
2606         );
2607         for other_file in other_files {
2608             let mut path = self.testpaths.file.clone();
2609             path.set_file_name(&format!("{}.rs", other_file));
2610             files.insert(
2611                 path.strip_prefix(&cwd).unwrap_or(&path).to_str().unwrap().replace('\\', "/"),
2612                 self.get_lines(&path, None),
2613             );
2614         }
2615
2616         let mut tested = 0;
2617         for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| {
2618             if let Some((left, right)) = s.split_once(" - ") {
2619                 let path = left.rsplit("test ").next().unwrap();
2620                 if let Some(ref mut v) = files.get_mut(&path.replace('\\', "/")) {
2621                     tested += 1;
2622                     let mut iter = right.split("(line ");
2623                     iter.next();
2624                     let line = iter
2625                         .next()
2626                         .unwrap_or(")")
2627                         .split(')')
2628                         .next()
2629                         .unwrap_or("0")
2630                         .parse()
2631                         .unwrap_or(0);
2632                     if let Ok(pos) = v.binary_search(&line) {
2633                         v.remove(pos);
2634                     } else {
2635                         self.fatal_proc_rec(
2636                             &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2637                             &res,
2638                         );
2639                     }
2640                 }
2641             }
2642         }) {}
2643         if tested == 0 {
2644             self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2645         } else {
2646             for (entry, v) in &files {
2647                 if !v.is_empty() {
2648                     self.fatal_proc_rec(
2649                         &format!(
2650                             "Not found test at line{} \"{}\":{:?}",
2651                             if v.len() > 1 { "s" } else { "" },
2652                             entry,
2653                             v
2654                         ),
2655                         &res,
2656                     );
2657                 }
2658             }
2659         }
2660     }
2661
2662     fn run_codegen_units_test(&self) {
2663         assert!(self.revision.is_none(), "revisions not relevant here");
2664
2665         let proc_res = self.compile_test(WillExecute::No, EmitMetadata::No);
2666
2667         if !proc_res.status.success() {
2668             self.fatal_proc_rec("compilation failed!", &proc_res);
2669         }
2670
2671         self.check_no_compiler_crash(&proc_res, self.props.should_ice);
2672
2673         const PREFIX: &str = "MONO_ITEM ";
2674         const CGU_MARKER: &str = "@@";
2675
2676         let actual: Vec<MonoItem> = proc_res
2677             .stdout
2678             .lines()
2679             .filter(|line| line.starts_with(PREFIX))
2680             .map(|line| str_to_mono_item(line, true))
2681             .collect();
2682
2683         let expected: Vec<MonoItem> = errors::load_errors(&self.testpaths.file, None)
2684             .iter()
2685             .map(|e| str_to_mono_item(&e.msg[..], false))
2686             .collect();
2687
2688         let mut missing = Vec::new();
2689         let mut wrong_cgus = Vec::new();
2690
2691         for expected_item in &expected {
2692             let actual_item_with_same_name = actual.iter().find(|ti| ti.name == expected_item.name);
2693
2694             if let Some(actual_item) = actual_item_with_same_name {
2695                 if !expected_item.codegen_units.is_empty() &&
2696                    // Also check for codegen units
2697                    expected_item.codegen_units != actual_item.codegen_units
2698                 {
2699                     wrong_cgus.push((expected_item.clone(), actual_item.clone()));
2700                 }
2701             } else {
2702                 missing.push(expected_item.string.clone());
2703             }
2704         }
2705
2706         let unexpected: Vec<_> = actual
2707             .iter()
2708             .filter(|acgu| !expected.iter().any(|ecgu| acgu.name == ecgu.name))
2709             .map(|acgu| acgu.string.clone())
2710             .collect();
2711
2712         if !missing.is_empty() {
2713             missing.sort();
2714
2715             println!("\nThese items should have been contained but were not:\n");
2716
2717             for item in &missing {
2718                 println!("{}", item);
2719             }
2720
2721             println!("\n");
2722         }
2723
2724         if !unexpected.is_empty() {
2725             let sorted = {
2726                 let mut sorted = unexpected.clone();
2727                 sorted.sort();
2728                 sorted
2729             };
2730
2731             println!("\nThese items were contained but should not have been:\n");
2732
2733             for item in sorted {
2734                 println!("{}", item);
2735             }
2736
2737             println!("\n");
2738         }
2739
2740         if !wrong_cgus.is_empty() {
2741             wrong_cgus.sort_by_key(|pair| pair.0.name.clone());
2742             println!("\nThe following items were assigned to wrong codegen units:\n");
2743
2744             for &(ref expected_item, ref actual_item) in &wrong_cgus {
2745                 println!("{}", expected_item.name);
2746                 println!("  expected: {}", codegen_units_to_str(&expected_item.codegen_units));
2747                 println!("  actual:   {}", codegen_units_to_str(&actual_item.codegen_units));
2748                 println!();
2749             }
2750         }
2751
2752         if !(missing.is_empty() && unexpected.is_empty() && wrong_cgus.is_empty()) {
2753             panic!();
2754         }
2755
2756         #[derive(Clone, Eq, PartialEq)]
2757         struct MonoItem {
2758             name: String,
2759             codegen_units: HashSet<String>,
2760             string: String,
2761         }
2762
2763         // [MONO_ITEM] name [@@ (cgu)+]
2764         fn str_to_mono_item(s: &str, cgu_has_crate_disambiguator: bool) -> MonoItem {
2765             let s = if s.starts_with(PREFIX) { (&s[PREFIX.len()..]).trim() } else { s.trim() };
2766
2767             let full_string = format!("{}{}", PREFIX, s);
2768
2769             let parts: Vec<&str> =
2770                 s.split(CGU_MARKER).map(str::trim).filter(|s| !s.is_empty()).collect();
2771
2772             let name = parts[0].trim();
2773
2774             let cgus = if parts.len() > 1 {
2775                 let cgus_str = parts[1];
2776
2777                 cgus_str
2778                     .split(' ')
2779                     .map(str::trim)
2780                     .filter(|s| !s.is_empty())
2781                     .map(|s| {
2782                         if cgu_has_crate_disambiguator {
2783                             remove_crate_disambiguators_from_set_of_cgu_names(s)
2784                         } else {
2785                             s.to_string()
2786                         }
2787                     })
2788                     .collect()
2789             } else {
2790                 HashSet::new()
2791             };
2792
2793             MonoItem { name: name.to_owned(), codegen_units: cgus, string: full_string }
2794         }
2795
2796         fn codegen_units_to_str(cgus: &HashSet<String>) -> String {
2797             let mut cgus: Vec<_> = cgus.iter().collect();
2798             cgus.sort();
2799
2800             let mut string = String::new();
2801             for cgu in cgus {
2802                 string.push_str(&cgu[..]);
2803                 string.push_str(" ");
2804             }
2805
2806             string
2807         }
2808
2809         // Given a cgu-name-prefix of the form <crate-name>.<crate-disambiguator> or
2810         // the form <crate-name1>.<crate-disambiguator1>-in-<crate-name2>.<crate-disambiguator2>,
2811         // remove all crate-disambiguators.
2812         fn remove_crate_disambiguator_from_cgu(cgu: &str) -> String {
2813             lazy_static! {
2814                 static ref RE: Regex =
2815                     Regex::new(r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?")
2816                         .unwrap();
2817             }
2818
2819             let captures =
2820                 RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {}", cgu));
2821
2822             let mut new_name = cgu.to_owned();
2823
2824             if let Some(d2) = captures.name("d2") {
2825                 new_name.replace_range(d2.start()..d2.end(), "");
2826             }
2827
2828             let d1 = captures.name("d1").unwrap();
2829             new_name.replace_range(d1.start()..d1.end(), "");
2830
2831             new_name
2832         }
2833
2834         // The name of merged CGUs is constructed as the names of the original
2835         // CGUs joined with "--". This function splits such composite CGU names
2836         // and handles each component individually.
2837         fn remove_crate_disambiguators_from_set_of_cgu_names(cgus: &str) -> String {
2838             cgus.split("--")
2839                 .map(|cgu| remove_crate_disambiguator_from_cgu(cgu))
2840                 .collect::<Vec<_>>()
2841                 .join("--")
2842         }
2843     }
2844
2845     fn init_incremental_test(&self) {
2846         // (See `run_incremental_test` for an overview of how incremental tests work.)
2847
2848         // Before any of the revisions have executed, create the
2849         // incremental workproduct directory.  Delete any old
2850         // incremental work products that may be there from prior
2851         // runs.
2852         let incremental_dir = self.props.incremental_dir.as_ref().unwrap();
2853         if incremental_dir.exists() {
2854             // Canonicalizing the path will convert it to the //?/ format
2855             // on Windows, which enables paths longer than 260 character
2856             let canonicalized = incremental_dir.canonicalize().unwrap();
2857             fs::remove_dir_all(canonicalized).unwrap();
2858         }
2859         fs::create_dir_all(&incremental_dir).unwrap();
2860
2861         if self.config.verbose {
2862             println!("init_incremental_test: incremental_dir={}", incremental_dir.display());
2863         }
2864     }
2865
2866     fn run_incremental_test(&self) {
2867         // Basic plan for a test incremental/foo/bar.rs:
2868         // - load list of revisions rpass1, cfail2, rpass3
2869         //   - each should begin with `rpass`, `cfail`, or `rfail`
2870         //   - if `rpass`, expect compile and execution to succeed
2871         //   - if `cfail`, expect compilation to fail
2872         //   - if `rfail`, expect execution to fail
2873         // - create a directory build/foo/bar.incremental
2874         // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass1
2875         //   - because name of revision starts with "rpass", expect success
2876         // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C cfail2
2877         //   - because name of revision starts with "cfail", expect an error
2878         //   - load expected errors as usual, but filter for those that end in `[rfail2]`
2879         // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass3
2880         //   - because name of revision starts with "rpass", expect success
2881         // - execute build/foo/bar.exe and save output
2882         //
2883         // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2884         // to #[rustc_dirty] and clean tests I guess
2885
2886         let revision = self.revision.expect("incremental tests require a list of revisions");
2887
2888         // Incremental workproduct directory should have already been created.
2889         let incremental_dir = self.props.incremental_dir.as_ref().unwrap();
2890         assert!(incremental_dir.exists(), "init_incremental_test failed to create incremental dir");
2891
2892         if self.config.verbose {
2893             print!("revision={:?} props={:#?}", revision, self.props);
2894         }
2895
2896         if revision.starts_with("rpass") {
2897             if self.props.should_ice {
2898                 self.fatal("can only use should-ice in cfail tests");
2899             }
2900             self.run_rpass_test();
2901         } else if revision.starts_with("rfail") {
2902             if self.props.should_ice {
2903                 self.fatal("can only use should-ice in cfail tests");
2904             }
2905             self.run_rfail_test();
2906         } else if revision.starts_with("cfail") {
2907             self.run_cfail_test();
2908         } else {
2909             self.fatal("revision name must begin with rpass, rfail, or cfail");
2910         }
2911     }
2912
2913     fn run_rmake_test(&self) {
2914         let cwd = env::current_dir().unwrap();
2915         let src_root = self.config.src_base.parent().unwrap().parent().unwrap().parent().unwrap();
2916         let src_root = cwd.join(&src_root);
2917
2918         let tmpdir = cwd.join(self.output_base_name());
2919         if tmpdir.exists() {
2920             self.aggressive_rm_rf(&tmpdir).unwrap();
2921         }
2922         create_dir_all(&tmpdir).unwrap();
2923
2924         let host = &self.config.host;
2925         let make = if host.contains("dragonfly")
2926             || host.contains("freebsd")
2927             || host.contains("netbsd")
2928             || host.contains("openbsd")
2929         {
2930             "gmake"
2931         } else {
2932             "make"
2933         };
2934
2935         let mut cmd = Command::new(make);
2936         cmd.current_dir(&self.testpaths.file)
2937             .stdout(Stdio::piped())
2938             .stderr(Stdio::piped())
2939             .env("TARGET", &self.config.target)
2940             .env("PYTHON", &self.config.python)
2941             .env("S", src_root)
2942             .env("RUST_BUILD_STAGE", &self.config.stage_id)
2943             .env("RUSTC", cwd.join(&self.config.rustc_path))
2944             .env("TMPDIR", &tmpdir)
2945             .env("LD_LIB_PATH_ENVVAR", dylib_env_var())
2946             .env("HOST_RPATH_DIR", cwd.join(&self.config.compile_lib_path))
2947             .env("TARGET_RPATH_DIR", cwd.join(&self.config.run_lib_path))
2948             .env("LLVM_COMPONENTS", &self.config.llvm_components)
2949             // We for sure don't want these tests to run in parallel, so make
2950             // sure they don't have access to these vars if we run via `make`
2951             // at the top level
2952             .env_remove("MAKEFLAGS")
2953             .env_remove("MFLAGS")
2954             .env_remove("CARGO_MAKEFLAGS");
2955
2956         if let Some(ref rustdoc) = self.config.rustdoc_path {
2957             cmd.env("RUSTDOC", cwd.join(rustdoc));
2958         }
2959
2960         if let Some(ref rust_demangler) = self.config.rust_demangler_path {
2961             cmd.env("RUST_DEMANGLER", cwd.join(rust_demangler));
2962         }
2963
2964         if let Some(ref node) = self.config.nodejs {
2965             cmd.env("NODE", node);
2966         }
2967
2968         if let Some(ref linker) = self.config.linker {
2969             cmd.env("RUSTC_LINKER", linker);
2970         }
2971
2972         if let Some(ref clang) = self.config.run_clang_based_tests_with {
2973             cmd.env("CLANG", clang);
2974         }
2975
2976         if let Some(ref filecheck) = self.config.llvm_filecheck {
2977             cmd.env("LLVM_FILECHECK", filecheck);
2978         }
2979
2980         if let Some(ref llvm_bin_dir) = self.config.llvm_bin_dir {
2981             cmd.env("LLVM_BIN_DIR", llvm_bin_dir);
2982         }
2983
2984         // We don't want RUSTFLAGS set from the outside to interfere with
2985         // compiler flags set in the test cases:
2986         cmd.env_remove("RUSTFLAGS");
2987
2988         // Use dynamic musl for tests because static doesn't allow creating dylibs
2989         if self.config.host.contains("musl") {
2990             cmd.env("RUSTFLAGS", "-Ctarget-feature=-crt-static").env("IS_MUSL_HOST", "1");
2991         }
2992
2993         if self.config.bless {
2994             cmd.env("RUSTC_BLESS_TEST", "--bless");
2995             // Assume this option is active if the environment variable is "defined", with _any_ value.
2996             // As an example, a `Makefile` can use this option by:
2997             //
2998             //   ifdef RUSTC_BLESS_TEST
2999             //       cp "$(TMPDIR)"/actual_something.ext expected_something.ext
3000             //   else
3001             //       $(DIFF) expected_something.ext "$(TMPDIR)"/actual_something.ext
3002             //   endif
3003         }
3004
3005         if self.config.target.contains("msvc") && self.config.cc != "" {
3006             // We need to pass a path to `lib.exe`, so assume that `cc` is `cl.exe`
3007             // and that `lib.exe` lives next to it.
3008             let lib = Path::new(&self.config.cc).parent().unwrap().join("lib.exe");
3009
3010             // MSYS doesn't like passing flags of the form `/foo` as it thinks it's
3011             // a path and instead passes `C:\msys64\foo`, so convert all
3012             // `/`-arguments to MSVC here to `-` arguments.
3013             let cflags = self
3014                 .config
3015                 .cflags
3016                 .split(' ')
3017                 .map(|s| s.replace("/", "-"))
3018                 .collect::<Vec<_>>()
3019                 .join(" ");
3020             let cxxflags = self
3021                 .config
3022                 .cxxflags
3023                 .split(' ')
3024                 .map(|s| s.replace("/", "-"))
3025                 .collect::<Vec<_>>()
3026                 .join(" ");
3027
3028             cmd.env("IS_MSVC", "1")
3029                 .env("IS_WINDOWS", "1")
3030                 .env("MSVC_LIB", format!("'{}' -nologo", lib.display()))
3031                 .env("CC", format!("'{}' {}", self.config.cc, cflags))
3032                 .env("CXX", format!("'{}' {}", &self.config.cxx, cxxflags));
3033         } else {
3034             cmd.env("CC", format!("{} {}", self.config.cc, self.config.cflags))
3035                 .env("CXX", format!("{} {}", self.config.cxx, self.config.cxxflags))
3036                 .env("AR", &self.config.ar);
3037
3038             if self.config.target.contains("windows") {
3039                 cmd.env("IS_WINDOWS", "1");
3040             }
3041         }
3042
3043         let output = self.read2_abbreviated(cmd.spawn().expect("failed to spawn `make`"));
3044         if !output.status.success() {
3045             let res = ProcRes {
3046                 status: output.status,
3047                 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
3048                 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
3049                 cmdline: format!("{:?}", cmd),
3050             };
3051             self.fatal_proc_rec("make failed", &res);
3052         }
3053     }
3054
3055     fn aggressive_rm_rf(&self, path: &Path) -> io::Result<()> {
3056         for e in path.read_dir()? {
3057             let entry = e?;
3058             let path = entry.path();
3059             if entry.file_type()?.is_dir() {
3060                 self.aggressive_rm_rf(&path)?;
3061             } else {
3062                 // Remove readonly files as well on windows (by default we can't)
3063                 fs::remove_file(&path).or_else(|e| {
3064                     if cfg!(windows) && e.kind() == io::ErrorKind::PermissionDenied {
3065                         let mut meta = entry.metadata()?.permissions();
3066                         meta.set_readonly(false);
3067                         fs::set_permissions(&path, meta)?;
3068                         fs::remove_file(&path)
3069                     } else {
3070                         Err(e)
3071                     }
3072                 })?;
3073             }
3074         }
3075         fs::remove_dir(path)
3076     }
3077
3078     fn run_js_doc_test(&self) {
3079         if let Some(nodejs) = &self.config.nodejs {
3080             let out_dir = self.output_base_dir();
3081
3082             self.document(&out_dir);
3083
3084             let root = self.config.find_rust_src_root().unwrap();
3085             let file_stem =
3086                 self.testpaths.file.file_stem().and_then(|f| f.to_str()).expect("no file stem");
3087             let res = self.cmd2procres(
3088                 Command::new(&nodejs)
3089                     .arg(root.join("src/tools/rustdoc-js/tester.js"))
3090                     .arg("--doc-folder")
3091                     .arg(out_dir)
3092                     .arg("--crate-name")
3093                     .arg(file_stem.replace("-", "_"))
3094                     .arg("--test-file")
3095                     .arg(self.testpaths.file.with_extension("js")),
3096             );
3097             if !res.status.success() {
3098                 self.fatal_proc_rec("rustdoc-js test failed!", &res);
3099             }
3100         } else {
3101             self.fatal("no nodeJS");
3102         }
3103     }
3104
3105     fn load_compare_outputs(
3106         &self,
3107         proc_res: &ProcRes,
3108         output_kind: TestOutput,
3109         explicit_format: bool,
3110     ) -> usize {
3111         let stderr_bits = format!("{}bit.stderr", self.config.get_pointer_width());
3112         let (stderr_kind, stdout_kind) = match output_kind {
3113             TestOutput::Compile => (
3114                 {
3115                     if self.props.stderr_per_bitwidth { &stderr_bits } else { UI_STDERR }
3116                 },
3117                 UI_STDOUT,
3118             ),
3119             TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
3120         };
3121
3122         let expected_stderr = self.load_expected_output(stderr_kind);
3123         let expected_stdout = self.load_expected_output(stdout_kind);
3124
3125         let normalized_stdout = match output_kind {
3126             TestOutput::Run if self.config.remote_test_client.is_some() => {
3127                 // When tests are run using the remote-test-client, the string
3128                 // 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"'
3129                 // is printed to stdout by the client and then captured in the ProcRes,
3130                 // so it needs to be removed when comparing the run-pass test execution output
3131                 lazy_static! {
3132                     static ref REMOTE_TEST_RE: Regex = Regex::new(
3133                         "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-.]+)+\", waiting for result\n"
3134                     )
3135                     .unwrap();
3136                 }
3137                 REMOTE_TEST_RE
3138                     .replace(
3139                         &self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
3140                         "",
3141                     )
3142                     .to_string()
3143             }
3144             _ => self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
3145         };
3146
3147         let stderr = if explicit_format {
3148             proc_res.stderr.clone()
3149         } else {
3150             json::extract_rendered(&proc_res.stderr)
3151         };
3152
3153         let normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
3154         let mut errors = 0;
3155         match output_kind {
3156             TestOutput::Compile => {
3157                 if !self.props.dont_check_compiler_stdout {
3158                     errors +=
3159                         self.compare_output(stdout_kind, &normalized_stdout, &expected_stdout);
3160                 }
3161                 if !self.props.dont_check_compiler_stderr {
3162                     errors +=
3163                         self.compare_output(stderr_kind, &normalized_stderr, &expected_stderr);
3164                 }
3165             }
3166             TestOutput::Run => {
3167                 errors += self.compare_output(stdout_kind, &normalized_stdout, &expected_stdout);
3168                 errors += self.compare_output(stderr_kind, &normalized_stderr, &expected_stderr);
3169             }
3170         }
3171         errors
3172     }
3173
3174     fn run_ui_test(&self) {
3175         if let Some(FailMode::Build) = self.props.fail_mode {
3176             // Make sure a build-fail test cannot fail due to failing analysis (e.g. typeck).
3177             let pm = Some(PassMode::Check);
3178             let proc_res = self.compile_test_general(WillExecute::No, EmitMetadata::Yes, pm);
3179             self.check_if_test_should_compile(&proc_res, pm);
3180         }
3181
3182         let pm = self.pass_mode();
3183         let should_run = self.should_run(pm);
3184         let emit_metadata = self.should_emit_metadata(pm);
3185         let proc_res = self.compile_test(should_run, emit_metadata);
3186         self.check_if_test_should_compile(&proc_res, pm);
3187
3188         // if the user specified a format in the ui test
3189         // print the output to the stderr file, otherwise extract
3190         // the rendered error messages from json and print them
3191         let explicit = self.props.compile_flags.iter().any(|s| s.contains("--error-format"));
3192
3193         let expected_fixed = self.load_expected_output(UI_FIXED);
3194
3195         self.check_and_prune_duplicate_outputs(&proc_res, &[], &[]);
3196
3197         let mut errors = self.load_compare_outputs(&proc_res, TestOutput::Compile, explicit);
3198         let rustfix_input = json::rustfix_diagnostics_only(&proc_res.stderr);
3199
3200         if self.config.compare_mode.is_some() {
3201             // don't test rustfix with nll right now
3202         } else if self.config.rustfix_coverage {
3203             // Find out which tests have `MachineApplicable` suggestions but are missing
3204             // `run-rustfix` or `run-rustfix-only-machine-applicable` headers.
3205             //
3206             // This will return an empty `Vec` in case the executed test file has a
3207             // `compile-flags: --error-format=xxxx` header with a value other than `json`.
3208             let suggestions = get_suggestions_from_json(
3209                 &rustfix_input,
3210                 &HashSet::new(),
3211                 Filter::MachineApplicableOnly,
3212             )
3213             .unwrap_or_default();
3214             if !suggestions.is_empty()
3215                 && !self.props.run_rustfix
3216                 && !self.props.rustfix_only_machine_applicable
3217             {
3218                 let mut coverage_file_path = self.config.build_base.clone();
3219                 coverage_file_path.push("rustfix_missing_coverage.txt");
3220                 debug!("coverage_file_path: {}", coverage_file_path.display());
3221
3222                 let mut file = OpenOptions::new()
3223                     .create(true)
3224                     .append(true)
3225                     .open(coverage_file_path.as_path())
3226                     .expect("could not create or open file");
3227
3228                 if writeln!(file, "{}", self.testpaths.file.display()).is_err() {
3229                     panic!("couldn't write to {}", coverage_file_path.display());
3230                 }
3231             }
3232         } else if self.props.run_rustfix {
3233             // Apply suggestions from rustc to the code itself
3234             let unfixed_code = self.load_expected_output_from_path(&self.testpaths.file).unwrap();
3235             let suggestions = get_suggestions_from_json(
3236                 &rustfix_input,
3237                 &HashSet::new(),
3238                 if self.props.rustfix_only_machine_applicable {
3239                     Filter::MachineApplicableOnly
3240                 } else {
3241                     Filter::Everything
3242                 },
3243             )
3244             .unwrap();
3245             let fixed_code = apply_suggestions(&unfixed_code, &suggestions).unwrap_or_else(|e| {
3246                 panic!(
3247                     "failed to apply suggestions for {:?} with rustfix: {}",
3248                     self.testpaths.file, e
3249                 )
3250             });
3251
3252             errors += self.compare_output("fixed", &fixed_code, &expected_fixed);
3253         } else if !expected_fixed.is_empty() {
3254             panic!(
3255                 "the `// run-rustfix` directive wasn't found but a `*.fixed` \
3256                  file was found"
3257             );
3258         }
3259
3260         if errors > 0 {
3261             println!("To update references, rerun the tests and pass the `--bless` flag");
3262             let relative_path_to_file =
3263                 self.testpaths.relative_dir.join(self.testpaths.file.file_name().unwrap());
3264             println!(
3265                 "To only update this specific test, also pass `--test-args {}`",
3266                 relative_path_to_file.display(),
3267             );
3268             self.fatal_proc_rec(
3269                 &format!("{} errors occurred comparing output.", errors),
3270                 &proc_res,
3271             );
3272         }
3273
3274         let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
3275
3276         if let WillExecute::Yes = should_run {
3277             let proc_res = self.exec_compiled_test();
3278             let run_output_errors = if self.props.check_run_results {
3279                 self.load_compare_outputs(&proc_res, TestOutput::Run, explicit)
3280             } else {
3281                 0
3282             };
3283             if run_output_errors > 0 {
3284                 self.fatal_proc_rec(
3285                     &format!("{} errors occurred comparing run output.", run_output_errors),
3286                     &proc_res,
3287                 );
3288             }
3289             if self.should_run_successfully(pm) {
3290                 if !proc_res.status.success() {
3291                     self.fatal_proc_rec("test run failed!", &proc_res);
3292                 }
3293             } else if proc_res.status.success() {
3294                 self.fatal_proc_rec("test run succeeded!", &proc_res);
3295             }
3296
3297             if !self.props.error_patterns.is_empty() || !self.props.regex_error_patterns.is_empty()
3298             {
3299                 // "// error-pattern" comments
3300                 let output_to_check = self.get_output(&proc_res);
3301                 self.check_all_error_patterns(&output_to_check, &proc_res, pm);
3302             }
3303         }
3304
3305         debug!(
3306             "run_ui_test: explicit={:?} config.compare_mode={:?} expected_errors={:?} \
3307                proc_res.status={:?} props.error_patterns={:?}",
3308             explicit,
3309             self.config.compare_mode,
3310             expected_errors,
3311             proc_res.status,
3312             self.props.error_patterns
3313         );
3314         if !explicit && self.config.compare_mode.is_none() {
3315             let check_patterns = should_run == WillExecute::No
3316                 && (!self.props.error_patterns.is_empty()
3317                     || !self.props.regex_error_patterns.is_empty());
3318
3319             let check_annotations = !check_patterns || !expected_errors.is_empty();
3320
3321             if check_patterns {
3322                 // "// error-pattern" comments
3323                 let output_to_check = self.get_output(&proc_res);
3324                 self.check_all_error_patterns(&output_to_check, &proc_res, pm);
3325             }
3326
3327             if check_annotations {
3328                 // "//~ERROR comments"
3329                 self.check_expected_errors(expected_errors, &proc_res);
3330             }
3331         }
3332
3333         if self.props.run_rustfix && self.config.compare_mode.is_none() {
3334             // And finally, compile the fixed code and make sure it both
3335             // succeeds and has no diagnostics.
3336             let mut rustc = self.make_compile_args(
3337                 &self.testpaths.file.with_extension(UI_FIXED),
3338                 TargetLocation::ThisFile(self.make_exe_name()),
3339                 emit_metadata,
3340                 AllowUnused::No,
3341             );
3342             rustc.arg("-L").arg(&self.aux_output_dir_name());
3343             let res = self.compose_and_run_compiler(rustc, None);
3344             if !res.status.success() {
3345                 self.fatal_proc_rec("failed to compile fixed code", &res);
3346             }
3347             if !res.stderr.is_empty()
3348                 && !self.props.rustfix_only_machine_applicable
3349                 && !json::rustfix_diagnostics_only(&res.stderr).is_empty()
3350             {
3351                 self.fatal_proc_rec("fixed code is still producing diagnostics", &res);
3352             }
3353         }
3354     }
3355
3356     fn run_mir_opt_test(&self) {
3357         let pm = self.pass_mode();
3358         let should_run = self.should_run(pm);
3359         let emit_metadata = self.should_emit_metadata(pm);
3360         let proc_res = self.compile_test(should_run, emit_metadata);
3361
3362         if !proc_res.status.success() {
3363             self.fatal_proc_rec("compilation failed!", &proc_res);
3364         }
3365
3366         self.check_mir_dump();
3367
3368         if let WillExecute::Yes = should_run {
3369             let proc_res = self.exec_compiled_test();
3370
3371             if !proc_res.status.success() {
3372                 self.fatal_proc_rec("test run failed!", &proc_res);
3373             }
3374         }
3375     }
3376
3377     fn check_mir_dump(&self) {
3378         let test_file_contents = fs::read_to_string(&self.testpaths.file).unwrap();
3379
3380         let test_dir = self.testpaths.file.parent().unwrap();
3381         let test_crate =
3382             self.testpaths.file.file_stem().unwrap().to_str().unwrap().replace("-", "_");
3383
3384         let mut bit_width = String::new();
3385         if test_file_contents.lines().any(|l| l == "// EMIT_MIR_FOR_EACH_BIT_WIDTH") {
3386             bit_width = format!(".{}bit", self.config.get_pointer_width());
3387         }
3388
3389         if self.config.bless {
3390             for e in
3391                 glob(&format!("{}/{}.*{}.mir", test_dir.display(), test_crate, bit_width)).unwrap()
3392             {
3393                 std::fs::remove_file(e.unwrap()).unwrap();
3394             }
3395             for e in
3396                 glob(&format!("{}/{}.*{}.diff", test_dir.display(), test_crate, bit_width)).unwrap()
3397             {
3398                 std::fs::remove_file(e.unwrap()).unwrap();
3399             }
3400         }
3401
3402         for l in test_file_contents.lines() {
3403             if l.starts_with("// EMIT_MIR ") {
3404                 let test_name = l.trim_start_matches("// EMIT_MIR ").trim();
3405                 let mut test_names = test_name.split(' ');
3406                 // sometimes we specify two files so that we get a diff between the two files
3407                 let test_name = test_names.next().unwrap();
3408                 let mut expected_file;
3409                 let from_file;
3410                 let to_file;
3411
3412                 if test_name.ends_with(".diff") {
3413                     let trimmed = test_name.trim_end_matches(".diff");
3414                     let test_against = format!("{}.after.mir", trimmed);
3415                     from_file = format!("{}.before.mir", trimmed);
3416                     expected_file = format!("{}{}.diff", trimmed, bit_width);
3417                     assert!(
3418                         test_names.next().is_none(),
3419                         "two mir pass names specified for MIR diff"
3420                     );
3421                     to_file = Some(test_against);
3422                 } else if let Some(first_pass) = test_names.next() {
3423                     let second_pass = test_names.next().unwrap();
3424                     assert!(
3425                         test_names.next().is_none(),
3426                         "three mir pass names specified for MIR diff"
3427                     );
3428                     expected_file =
3429                         format!("{}{}.{}-{}.diff", test_name, bit_width, first_pass, second_pass);
3430                     let second_file = format!("{}.{}.mir", test_name, second_pass);
3431                     from_file = format!("{}.{}.mir", test_name, first_pass);
3432                     to_file = Some(second_file);
3433                 } else {
3434                     let ext_re = Regex::new(r#"(\.(mir|dot|html))$"#).unwrap();
3435                     let cap = ext_re
3436                         .captures_iter(test_name)
3437                         .next()
3438                         .expect("test_name has an invalid extension");
3439                     let extension = cap.get(1).unwrap().as_str();
3440                     expected_file = format!(
3441                         "{}{}{}",
3442                         test_name.trim_end_matches(extension),
3443                         bit_width,
3444                         extension,
3445                     );
3446                     from_file = test_name.to_string();
3447                     assert!(
3448                         test_names.next().is_none(),
3449                         "two mir pass names specified for MIR dump"
3450                     );
3451                     to_file = None;
3452                 };
3453                 if !expected_file.starts_with(&test_crate) {
3454                     expected_file = format!("{}.{}", test_crate, expected_file);
3455                 }
3456                 let expected_file = test_dir.join(expected_file);
3457
3458                 let dumped_string = if let Some(after) = to_file {
3459                     self.diff_mir_files(from_file.into(), after.into())
3460                 } else {
3461                     let mut output_file = PathBuf::new();
3462                     output_file.push(self.get_mir_dump_dir());
3463                     output_file.push(&from_file);
3464                     debug!(
3465                         "comparing the contents of: {} with {}",
3466                         output_file.display(),
3467                         expected_file.display()
3468                     );
3469                     if !output_file.exists() {
3470                         panic!(
3471                             "Output file `{}` from test does not exist, available files are in `{}`",
3472                             output_file.display(),
3473                             output_file.parent().unwrap().display()
3474                         );
3475                     }
3476                     self.check_mir_test_timestamp(&from_file, &output_file);
3477                     let dumped_string = fs::read_to_string(&output_file).unwrap();
3478                     self.normalize_output(&dumped_string, &[])
3479                 };
3480
3481                 if self.config.bless {
3482                     let _ = std::fs::remove_file(&expected_file);
3483                     std::fs::write(expected_file, dumped_string.as_bytes()).unwrap();
3484                 } else {
3485                     if !expected_file.exists() {
3486                         panic!(
3487                             "Output file `{}` from test does not exist",
3488                             expected_file.display()
3489                         );
3490                     }
3491                     let expected_string = fs::read_to_string(&expected_file).unwrap();
3492                     if dumped_string != expected_string {
3493                         print!("{}", write_diff(&expected_string, &dumped_string, 3));
3494                         panic!(
3495                             "Actual MIR output differs from expected MIR output {}",
3496                             expected_file.display()
3497                         );
3498                     }
3499                 }
3500             }
3501         }
3502     }
3503
3504     fn diff_mir_files(&self, before: PathBuf, after: PathBuf) -> String {
3505         let to_full_path = |path: PathBuf| {
3506             let full = self.get_mir_dump_dir().join(&path);
3507             if !full.exists() {
3508                 panic!(
3509                     "the mir dump file for {} does not exist (requested in {})",
3510                     path.display(),
3511                     self.testpaths.file.display(),
3512                 );
3513             }
3514             full
3515         };
3516         let before = to_full_path(before);
3517         let after = to_full_path(after);
3518         debug!("comparing the contents of: {} with {}", before.display(), after.display());
3519         let before = fs::read_to_string(before).unwrap();
3520         let after = fs::read_to_string(after).unwrap();
3521         let before = self.normalize_output(&before, &[]);
3522         let after = self.normalize_output(&after, &[]);
3523         let mut dumped_string = String::new();
3524         for result in diff::lines(&before, &after) {
3525             use std::fmt::Write;
3526             match result {
3527                 diff::Result::Left(s) => writeln!(dumped_string, "- {}", s).unwrap(),
3528                 diff::Result::Right(s) => writeln!(dumped_string, "+ {}", s).unwrap(),
3529                 diff::Result::Both(s, _) => writeln!(dumped_string, "  {}", s).unwrap(),
3530             }
3531         }
3532         dumped_string
3533     }
3534
3535     fn check_mir_test_timestamp(&self, test_name: &str, output_file: &Path) {
3536         let t = |file| fs::metadata(file).unwrap().modified().unwrap();
3537         let source_file = &self.testpaths.file;
3538         let output_time = t(output_file);
3539         let source_time = t(source_file);
3540         if source_time > output_time {
3541             debug!("source file time: {:?} output file time: {:?}", source_time, output_time);
3542             panic!(
3543                 "test source file `{}` is newer than potentially stale output file `{}`.",
3544                 source_file.display(),
3545                 test_name
3546             );
3547         }
3548     }
3549
3550     fn get_mir_dump_dir(&self) -> PathBuf {
3551         let mut mir_dump_dir = PathBuf::from(self.config.build_base.as_path());
3552         debug!("input_file: {:?}", self.testpaths.file);
3553         mir_dump_dir.push(&self.testpaths.relative_dir);
3554         mir_dump_dir.push(self.testpaths.file.file_stem().unwrap());
3555         mir_dump_dir
3556     }
3557
3558     fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> String {
3559         let cflags = self.props.compile_flags.join(" ");
3560         let json = cflags.contains("--error-format json")
3561             || cflags.contains("--error-format pretty-json")
3562             || cflags.contains("--error-format=json")
3563             || cflags.contains("--error-format=pretty-json")
3564             || cflags.contains("--output-format json")
3565             || cflags.contains("--output-format=json");
3566
3567         let mut normalized = output.to_string();
3568
3569         let mut normalize_path = |from: &Path, to: &str| {
3570             let mut from = from.display().to_string();
3571             if json {
3572                 from = from.replace("\\", "\\\\");
3573             }
3574             normalized = normalized.replace(&from, to);
3575         };
3576
3577         let parent_dir = self.testpaths.file.parent().unwrap();
3578         normalize_path(parent_dir, "$DIR");
3579
3580         // Paths into the libstd/libcore
3581         let base_dir = self.config.src_base.parent().unwrap().parent().unwrap().parent().unwrap();
3582         let src_dir = base_dir.join("library");
3583         normalize_path(&src_dir, "$SRC_DIR");
3584
3585         // `ui-fulldeps` tests can show paths to the compiler source when testing macros from
3586         // `rustc_macros`
3587         // eg. /home/user/rust/compiler
3588         let compiler_src_dir = base_dir.join("compiler");
3589         normalize_path(&compiler_src_dir, "$COMPILER_DIR");
3590
3591         if let Some(virtual_rust_source_base_dir) =
3592             option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR").map(PathBuf::from)
3593         {
3594             normalize_path(&virtual_rust_source_base_dir.join("library"), "$SRC_DIR");
3595             normalize_path(&virtual_rust_source_base_dir.join("compiler"), "$COMPILER_DIR");
3596         }
3597
3598         // Paths into the build directory
3599         let test_build_dir = &self.config.build_base;
3600         let parent_build_dir = test_build_dir.parent().unwrap().parent().unwrap().parent().unwrap();
3601
3602         // eg. /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui
3603         normalize_path(test_build_dir, "$TEST_BUILD_DIR");
3604         // eg. /home/user/rust/build
3605         normalize_path(parent_build_dir, "$BUILD_DIR");
3606
3607         // Paths into lib directory.
3608         normalize_path(&parent_build_dir.parent().unwrap().join("lib"), "$LIB_DIR");
3609
3610         if json {
3611             // escaped newlines in json strings should be readable
3612             // in the stderr files. There's no point int being correct,
3613             // since only humans process the stderr files.
3614             // Thus we just turn escaped newlines back into newlines.
3615             normalized = normalized.replace("\\n", "\n");
3616         }
3617
3618         // If there are `$SRC_DIR` normalizations with line and column numbers, then replace them
3619         // with placeholders as we do not want tests needing updated when compiler source code
3620         // changes.
3621         // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
3622         lazy_static! {
3623             static ref SRC_DIR_RE: Regex =
3624                 Regex::new("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?").unwrap();
3625         }
3626
3627         normalized = SRC_DIR_RE.replace_all(&normalized, "SRC_DIR$1:LL:COL").into_owned();
3628
3629         normalized = Self::normalize_platform_differences(&normalized);
3630         normalized = normalized.replace("\t", "\\t"); // makes tabs visible
3631
3632         // Remove test annotations like `//~ ERROR text` from the output,
3633         // since they duplicate actual errors and make the output hard to read.
3634         // This mirrors the regex in src/tools/tidy/src/style.rs, please update
3635         // both if either are changed.
3636         lazy_static! {
3637             static ref ANNOTATION_RE: Regex = Regex::new("\\s*//(\\[.*\\])?~.*").unwrap();
3638         }
3639
3640         normalized = ANNOTATION_RE.replace_all(&normalized, "").into_owned();
3641
3642         // This code normalizes various hashes in v0 symbol mangling that is
3643         // emitted in the ui and mir-opt tests.
3644         lazy_static! {
3645             static ref V0_CRATE_HASH_PREFIX_RE: Regex =
3646                 Regex::new(r"_R.*?Cs[0-9a-zA-Z]+_").unwrap();
3647             static ref V0_CRATE_HASH_RE: Regex = Regex::new(r"Cs[0-9a-zA-Z]+_").unwrap();
3648         }
3649
3650         const V0_CRATE_HASH_PLACEHOLDER: &str = r"CsCRATE_HASH_";
3651         if V0_CRATE_HASH_PREFIX_RE.is_match(&normalized) {
3652             // Normalize crate hash
3653             normalized =
3654                 V0_CRATE_HASH_RE.replace_all(&normalized, V0_CRATE_HASH_PLACEHOLDER).into_owned();
3655         }
3656
3657         lazy_static! {
3658             static ref V0_BACK_REF_PREFIX_RE: Regex = Regex::new(r"\(_R.*?B[0-9a-zA-Z]_").unwrap();
3659             static ref V0_BACK_REF_RE: Regex = Regex::new(r"B[0-9a-zA-Z]_").unwrap();
3660         }
3661
3662         const V0_BACK_REF_PLACEHOLDER: &str = r"B<REF>_";
3663         if V0_BACK_REF_PREFIX_RE.is_match(&normalized) {
3664             // Normalize back references (see RFC 2603)
3665             normalized =
3666                 V0_BACK_REF_RE.replace_all(&normalized, V0_BACK_REF_PLACEHOLDER).into_owned();
3667         }
3668
3669         // Custom normalization rules
3670         for rule in custom_rules {
3671             let re = Regex::new(&rule.0).expect("bad regex in custom normalization rule");
3672             normalized = re.replace_all(&normalized, &rule.1[..]).into_owned();
3673         }
3674         normalized
3675     }
3676
3677     /// Normalize output differences across platforms. Generally changes Windows output to be more
3678     /// Unix-like.
3679     ///
3680     /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
3681     /// with LF.
3682     fn normalize_platform_differences(output: &str) -> String {
3683         lazy_static! {
3684             /// Used to find Windows paths.
3685             ///
3686             /// It's not possible to detect paths in the error messages generally, but this is a
3687             /// decent enough heuristic.
3688             static ref PATH_BACKSLASH_RE: Regex = Regex::new(r#"(?x)
3689                 (?:
3690                   # Match paths that don't include spaces.
3691                   (?:\\[\pL\pN\.\-_']+)+\.\pL+
3692                 |
3693                   # If the path starts with a well-known root, then allow spaces.
3694                   \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_' ]+)+
3695                 )"#
3696             ).unwrap();
3697         }
3698
3699         let output = output.replace(r"\\", r"\");
3700
3701         PATH_BACKSLASH_RE
3702             .replace_all(&output, |caps: &Captures<'_>| {
3703                 println!("{}", &caps[0]);
3704                 caps[0].replace(r"\", "/")
3705             })
3706             .replace("\r\n", "\n")
3707     }
3708
3709     fn expected_output_path(&self, kind: &str) -> PathBuf {
3710         let mut path =
3711             expected_output_path(&self.testpaths, self.revision, &self.config.compare_mode, kind);
3712
3713         if !path.exists() {
3714             if let Some(CompareMode::Polonius) = self.config.compare_mode {
3715                 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3716             }
3717         }
3718
3719         if !path.exists() {
3720             path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3721         }
3722
3723         path
3724     }
3725
3726     fn load_expected_output(&self, kind: &str) -> String {
3727         let path = self.expected_output_path(kind);
3728         if path.exists() {
3729             match self.load_expected_output_from_path(&path) {
3730                 Ok(x) => x,
3731                 Err(x) => self.fatal(&x),
3732             }
3733         } else {
3734             String::new()
3735         }
3736     }
3737
3738     fn load_expected_output_from_path(&self, path: &Path) -> Result<String, String> {
3739         fs::read_to_string(path).map_err(|err| {
3740             format!("failed to load expected output from `{}`: {}", path.display(), err)
3741         })
3742     }
3743
3744     fn delete_file(&self, file: &PathBuf) {
3745         if !file.exists() {
3746             // Deleting a nonexistent file would error.
3747             return;
3748         }
3749         if let Err(e) = fs::remove_file(file) {
3750             self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,));
3751         }
3752     }
3753
3754     fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize {
3755         if actual == expected {
3756             return 0;
3757         }
3758
3759         if !self.config.bless {
3760             if expected.is_empty() {
3761                 println!("normalized {}:\n{}\n", kind, actual);
3762             } else {
3763                 println!("diff of {}:\n", kind);
3764                 print!("{}", write_diff(expected, actual, 3));
3765             }
3766         }
3767
3768         let mode = self.config.compare_mode.as_ref().map_or("", |m| m.to_str());
3769         let output_file = self
3770             .output_base_name()
3771             .with_extra_extension(self.revision.unwrap_or(""))
3772             .with_extra_extension(mode)
3773             .with_extra_extension(kind);
3774
3775         let mut files = vec![output_file];
3776         if self.config.bless {
3777             // Delete non-revision .stderr/.stdout file if revisions are used.
3778             // Without this, we'd just generate the new files and leave the old files around.
3779             if self.revision.is_some() {
3780                 let old =
3781                     expected_output_path(self.testpaths, None, &self.config.compare_mode, kind);
3782                 self.delete_file(&old);
3783             }
3784             files.push(expected_output_path(
3785                 self.testpaths,
3786                 self.revision,
3787                 &self.config.compare_mode,
3788                 kind,
3789             ));
3790         }
3791
3792         for output_file in &files {
3793             if actual.is_empty() {
3794                 self.delete_file(output_file);
3795             } else if let Err(err) = fs::write(&output_file, &actual) {
3796                 self.fatal(&format!(
3797                     "failed to write {} to `{}`: {}",
3798                     kind,
3799                     output_file.display(),
3800                     err,
3801                 ));
3802             }
3803         }
3804
3805         println!("\nThe actual {0} differed from the expected {0}.", kind);
3806         for output_file in files {
3807             println!("Actual {} saved to {}", kind, output_file.display());
3808         }
3809         if self.config.bless { 0 } else { 1 }
3810     }
3811
3812     fn check_and_prune_duplicate_outputs(
3813         &self,
3814         proc_res: &ProcRes,
3815         modes: &[CompareMode],
3816         require_same_modes: &[CompareMode],
3817     ) {
3818         for kind in UI_EXTENSIONS {
3819             let canon_comparison_path =
3820                 expected_output_path(&self.testpaths, self.revision, &None, kind);
3821
3822             let canon = match self.load_expected_output_from_path(&canon_comparison_path) {
3823                 Ok(canon) => canon,
3824                 _ => continue,
3825             };
3826             let bless = self.config.bless;
3827             let check_and_prune_duplicate_outputs = |mode: &CompareMode, require_same: bool| {
3828                 let examined_path =
3829                     expected_output_path(&self.testpaths, self.revision, &Some(mode.clone()), kind);
3830
3831                 // If there is no output, there is nothing to do
3832                 let examined_content = match self.load_expected_output_from_path(&examined_path) {
3833                     Ok(content) => content,
3834                     _ => return,
3835                 };
3836
3837                 let is_duplicate = canon == examined_content;
3838
3839                 match (bless, require_same, is_duplicate) {
3840                     // If we're blessing and the output is the same, then delete the file.
3841                     (true, _, true) => {
3842                         self.delete_file(&examined_path);
3843                     }
3844                     // If we want them to be the same, but they are different, then error.
3845                     // We do this wether we bless or not
3846                     (_, true, false) => {
3847                         self.fatal_proc_rec(
3848                             &format!("`{}` should not have different output from base test!", kind),
3849                             proc_res,
3850                         );
3851                     }
3852                     _ => {}
3853                 }
3854             };
3855             for mode in modes {
3856                 check_and_prune_duplicate_outputs(mode, false);
3857             }
3858             for mode in require_same_modes {
3859                 check_and_prune_duplicate_outputs(mode, true);
3860             }
3861         }
3862     }
3863
3864     fn create_stamp(&self) {
3865         let stamp = crate::stamp(&self.config, self.testpaths, self.revision);
3866         fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap();
3867     }
3868 }
3869
3870 struct ProcArgs {
3871     prog: String,
3872     args: Vec<String>,
3873 }
3874
3875 pub struct ProcRes {
3876     status: ExitStatus,
3877     stdout: String,
3878     stderr: String,
3879     cmdline: String,
3880 }
3881
3882 impl ProcRes {
3883     pub fn print_info(&self) {
3884         fn render(name: &str, contents: &str) -> String {
3885             let contents = json::extract_rendered(contents);
3886             let contents = contents.trim();
3887             if contents.is_empty() {
3888                 format!("{name}: none")
3889             } else {
3890                 format!(
3891                     "\
3892                      --- {name} -------------------------------\n\
3893                      {contents}\n\
3894                      ------------------------------------------",
3895                 )
3896             }
3897         }
3898
3899         println!(
3900             "status: {}\ncommand: {}\n{}\n{}\n",
3901             self.status,
3902             self.cmdline,
3903             render("stdout", &self.stdout),
3904             render("stderr", &self.stderr),
3905         );
3906     }
3907
3908     pub fn fatal(&self, err: Option<&str>, on_failure: impl FnOnce()) -> ! {
3909         if let Some(e) = err {
3910             println!("\nerror: {}", e);
3911         }
3912         self.print_info();
3913         on_failure();
3914         // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from
3915         // compiletest, which is unnecessary noise.
3916         std::panic::resume_unwind(Box::new(()));
3917     }
3918 }
3919
3920 #[derive(Debug)]
3921 enum TargetLocation {
3922     ThisFile(PathBuf),
3923     ThisDirectory(PathBuf),
3924 }
3925
3926 enum AllowUnused {
3927     Yes,
3928     No,
3929 }