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