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