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