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