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