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