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