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