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