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