1 // ignore-tidy-filelength
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;
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};
21 use std::collections::hash_map::DefaultHasher;
22 use std::collections::{HashMap, HashSet};
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};
30 use std::path::{Path, PathBuf};
31 use std::process::{Child, Command, ExitStatus, Output, Stdio};
35 use lazy_static::lazy_static;
38 use crate::extract_gdb_version;
39 use crate::is_android_gdb_target;
42 use debugger::{check_debugger_output, DebuggerCommands};
48 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
50 use winapi::um::errhandlingapi::SetErrorMode;
51 use winapi::um::winbase::SEM_NOGPFAULTERRORBOX;
54 static ref LOCK: Mutex<()> = Mutex::new(());
56 // Error mode is a global variable, so lock it so only one thread will change it
57 let _lock = LOCK.lock().unwrap();
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.
63 let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX); // read inherited flags
64 SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX);
66 SetErrorMode(old_mode);
72 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
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
83 return format!("lib{}.rlib", lib);
87 format!("{}.dll", lib)
88 } else if cfg!(target_os = "macos") {
89 format!("lib{}.dylib", lib)
91 format!("lib{}.so", lib)
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");
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");
115 // We're going to be dumping a lot of info. Start on a new line.
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));
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();
130 if config.mode == Incremental {
131 // Incremental tests are special because they cannot be run in
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 {
139 props: &revision_props,
141 revision: Some(revision),
143 rev_cx.run_revision();
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);
157 match config.debugger {
158 Some(Debugger::Cdb) => {
159 config.cdb.hash(&mut hash);
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);
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);
178 if let Ui = config.mode {
179 config.force_pass_mode.hash(&mut hash);
182 format!("{:x}", hash.finish())
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>,
203 /// Will this test be executed? Should we use `make_exe_name`?
204 #[derive(Copy, Clone, PartialEq)]
211 /// Should `--emit metadata` be used?
212 #[derive(Copy, Clone)]
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");
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(),
242 fn pass_mode(&self) -> Option<PassMode> {
243 self.props.pass_mode(self.config)
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),
253 if test_should_run { self.run_if_enabled() } else { WillExecute::No }
256 fn run_if_enabled(&self) -> WillExecute {
257 if self.config.run_enabled() { WillExecute::Yes } else { WillExecute::Disabled }
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),
267 fn should_compile_successfully(&self, pm: Option<PassMode>) -> bool {
268 match self.config.mode {
270 Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
273 self.revision.expect("incremental tests require a list of revisions");
274 if revision.starts_with("rpass") || revision.starts_with("rfail") {
276 } else if revision.starts_with("cfail") {
277 // FIXME: would be nice if incremental revs could start with "cpass"
280 panic!("revision name must begin with rpass, rfail, or cfail");
283 mode => panic!("unimplemented for mode {:?}", mode),
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);
293 if proc_res.status.success() {
295 &format!("{} test compiled successfully!", self.config.mode)[..],
300 self.check_correct_failure_status(proc_res);
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);
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()
315 self.fatal("both error pattern and expected errors specified");
317 self.check_expected_errors(expected_errors, &proc_res);
319 self.check_all_error_patterns(&output_to_check, &proc_res, pm);
321 if self.props.should_ice {
322 match proc_res.status.code() {
324 _ => self.fatal("expected ICE"),
328 self.check_forbid_output(&output_to_check, &proc_res);
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));
336 if !proc_res.status.success() {
337 self.fatal_proc_rec("compilation failed!", &proc_res);
340 if let WillExecute::Disabled = should_run {
344 let proc_res = self.exec_compiled_test();
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);
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);
357 fn get_output(&self, proc_res: &ProcRes) -> String {
358 if self.props.check_stdout {
359 format!("{}{}", proc_res.stdout, proc_res.stderr)
361 proc_res.stderr.clone()
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();
369 if expected_status != received_status {
372 "Error: expected failure status ({:?}) but received status {:?}.",
373 expected_status, received_status
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);
385 if !proc_res.status.success() {
386 self.fatal_proc_rec("compilation failed!", &proc_res);
389 if let WillExecute::Disabled = should_run {
393 // FIXME(#41968): Move this check to tidy?
394 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
396 expected_errors.is_empty(),
397 "run-pass tests with expected warnings should be moved to ui/"
400 let proc_res = self.exec_compiled_test();
401 if !proc_res.status.success() {
402 self.fatal_proc_rec("test run failed!", &proc_res);
406 fn run_valgrind_test(&self) {
407 assert!(self.revision.is_none(), "revisions not relevant here");
409 if self.config.valgrind_path.is_none() {
410 assert!(!self.config.force_valgrind);
411 return self.run_rpass_test();
414 let should_run = self.run_if_enabled();
415 let mut proc_res = self.compile_test(should_run, EmitMetadata::No);
417 if !proc_res.status.success() {
418 self.fatal_proc_rec("compilation failed!", &proc_res);
421 if let WillExecute::Disabled = should_run {
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();
430 if !proc_res.status.success() {
431 self.fatal_proc_rec("test run failed!", &proc_res);
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());
439 logv(self.config, "testing for converging pretty-printing".to_owned());
442 let rounds = match self.props.pp_exact {
447 let src = fs::read_to_string(&self.testpaths.file).unwrap();
448 let mut srcs = vec![src];
451 while round < rounds {
454 format!("pretty-printing round {} revision {:?}", round, self.revision),
457 if round == 0 { ReadFrom::Path } else { ReadFrom::Stdin(srcs[round].to_owned()) };
459 let proc_res = self.print_source(read_from, &self.props.pretty_mode);
460 if !proc_res.status.success() {
463 "pretty-printing failed in round {} revision {:?}",
470 let ProcRes { stdout, .. } = proc_res;
475 let mut expected = match self.props.pp_exact {
477 let filepath = self.testpaths.file.parent().unwrap().join(file);
478 fs::read_to_string(&filepath).unwrap()
480 None => srcs[srcs.len() - 2].clone(),
482 let mut actual = srcs[srcs.len() - 1].clone();
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, "");
491 if !self.config.bless {
492 self.compare_source(&expected, &actual);
493 } else if expected != actual {
495 let filepath = match &self.props.pp_exact {
497 filepath_buf = self.testpaths.file.parent().unwrap().join(file);
500 None => &self.testpaths.file,
502 fs::write(filepath, &actual).unwrap();
505 // If we're only making sure that the output matches then just stop here
506 if self.props.pretty_compare_only {
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);
516 if !self.props.pretty_expanded {
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);
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);
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(),
540 let mut rustc = Command::new(&self.config.rustc_path);
543 .args(&["-Z", &format!("unpretty={}", pretty_type)])
544 .args(&["--target", &self.config.target])
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);
551 let src = match read_from {
552 ReadFrom::Stdin(src) => Some(src),
553 ReadFrom::Path => None,
556 self.compose_and_run(
558 self.config.compile_lib_path.to_str().unwrap(),
559 Some(aux_dir.to_str().unwrap()),
564 fn compare_source(&self, expected: &str, actual: &str) {
565 if expected != actual {
567 "pretty-printed source does not match expected source\n\
569 ------------------------------------------\n\
571 ------------------------------------------\n\
573 ------------------------------------------\n\
575 ------------------------------------------\n\
577 ------------------------------------------\n\
581 write_diff(expected, actual, 3),
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]);
595 fn typecheck_source(&self, src: String) -> ProcRes {
596 let mut rustc = Command::new(&self.config.rustc_path);
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();
602 let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
604 let aux_dir = self.aux_output_dir_name();
611 .arg(&format!("--target={}", target))
613 .arg(&self.config.build_base)
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);
620 self.compose_and_run_compiler(rustc, Some(src))
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(),
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()
638 let test_cx = TestCx { config: &config, ..*self };
640 test_cx.run_debuginfo_cdb_test_no_opt();
643 fn run_debuginfo_cdb_test_no_opt(&self) {
644 let exe_file = self.make_exe_name();
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
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();
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);
665 if let WillExecute::Disabled = should_run {
670 static PREFIXES: &[&str] = &["cdb", "cdbg"];
671 // No "native rust support" variation for CDB yet.
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,
684 Err(e) => self.fatal(&e),
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
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()));
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));
706 // Append the other `cdb-command:`s
707 for line in &commands {
708 script_str.push_str(line);
709 script_str.push_str("\n");
712 script_str.push_str("\nqq\n"); // Quit the debugger (including remote debugger, if any)
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");
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.
723 .arg(&debugger_script)
726 let debugger_run_result = self.compose_and_run(
728 self.config.run_lib_path.to_str().unwrap(),
733 if !debugger_run_result.status.success() {
734 self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
737 if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
738 self.fatal_proc_rec(&e, &debugger_run_result);
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()
749 let test_cx = TestCx { config: &config, ..*self };
751 test_cx.run_debuginfo_gdb_test_no_opt();
754 fn run_debuginfo_gdb_test_no_opt(&self) {
755 let prefixes = if self.config.gdb_native_rust {
757 static PREFIXES: &[&str] = &["gdb", "gdbr"];
758 println!("NOTE: compiletest thinks it is using GDB with native rust support");
762 static PREFIXES: &[&str] = &["gdb", "gdbg"];
763 println!("NOTE: compiletest thinks it is using GDB without native rust support");
767 let DebuggerCommands { commands, check_lines, breakpoint_lines } =
768 match DebuggerCommands::parse_from(
769 &self.testpaths.file,
775 Err(e) => self.fatal(&e),
777 let mut cmds = commands.join("\n");
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);
785 if let WillExecute::Disabled = should_run {
789 let exe_file = self.make_exe_name();
791 let debugger_run_result;
792 if is_android_gdb_target(&self.config.target) {
793 cmds = cmds.replace("run", "continue");
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"),
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
811 for line in &breakpoint_lines {
815 self.testpaths.file.file_name().unwrap().to_string_lossy(),
820 script_str.push_str(&cmds);
821 script_str.push_str("\nquit\n");
823 debug!("script_str = {}", script_str);
824 self.dump_output_file(&script_str, "debugger.script");
826 let adb_path = &self.config.adb_path;
828 Command::new(adb_path)
831 .arg(&self.config.adb_test_dir)
833 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
835 Command::new(adb_path)
836 .args(&["forward", "tcp:5039", "tcp:5039"])
838 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
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()
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())
855 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
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();
864 stdout.read_line(&mut line).unwrap();
865 if line.starts_with("Listening on port 5039") {
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];
876 let gdb_path = self.config.gdb.as_ref().unwrap();
877 let Output { status, stdout, stderr } = Command::new(&gdb_path)
880 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", gdb_path));
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));
889 debugger_run_result = ProcRes {
891 stdout: String::from_utf8(stdout).unwrap(),
892 stderr: String::from_utf8(stderr).unwrap(),
895 if adb.kill().is_err() {
896 println!("Adb process is already finished.");
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");
909 match self.config.gdb_version {
911 println!("NOTE: compiletest thinks it is using GDB version {}", version);
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"\\")
921 let output_base_dir = self.output_base_dir().to_str().unwrap().to_owned();
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"\\")
934 "NOTE: compiletest does not know which version of \
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");
944 // Add the pretty printer directory to GDB's source-file search path
946 .push_str(&format!("directory {}\n", rust_pp_module_abs_path.replace(r"\", r"\\")));
948 // Load the target executable
950 .push_str(&format!("file {}\n", exe_file.to_str().unwrap().replace(r"\", r"\\")));
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");
957 // Add line breakpoints
958 for line in &breakpoint_lines {
959 script_str.push_str(&format!(
961 self.testpaths.file.file_name().unwrap().to_string_lossy(),
966 script_str.push_str(&cmds);
967 script_str.push_str("\nquit\n");
969 debug!("script_str = {}", script_str);
970 self.dump_output_file(&script_str, "debugger.script");
972 let mut debugger_script = OsString::from("-command=");
973 debugger_script.push(self.make_out_name("debugger.script"));
975 let debugger_opts: &[&OsStr] =
976 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
978 let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
979 gdb.args(debugger_opts).env("PYTHONPATH", rust_pp_module_abs_path);
981 debugger_run_result =
982 self.compose_and_run(gdb, self.config.run_lib_path.to_str().unwrap(), None, None);
985 if !debugger_run_result.status.success() {
986 self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
989 if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
990 self.fatal_proc_rec(&e, &debugger_run_result);
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.");
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()
1005 let test_cx = TestCx { config: &config, ..*self };
1007 test_cx.run_debuginfo_lldb_test_no_opt();
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);
1017 if let WillExecute::Disabled = should_run {
1021 let exe_file = self.make_exe_name();
1023 match self.config.lldb_version {
1024 Some(ref version) => {
1025 println!("NOTE: compiletest thinks it is using LLDB version {}", version);
1029 "NOTE: compiletest does not know which version of \
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");
1040 static PREFIXES: &[&str] = &["lldb", "lldbg"];
1041 println!("NOTE: compiletest thinks it is using LLDB without native rust support");
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,
1054 Err(e) => self.fatal(&e),
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");
1061 // Make LLDB emit its version, so we have it documented in the test output
1062 script_str.push_str("version\n");
1064 // Switch LLDB into "Rust mode"
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();
1071 let rust_type_regexes = vec![
1072 "^(alloc::([a-z_]+::)+)String$",
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.+$",
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");
1100 script_str.push_str("type category enable Rust\n");
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
1111 // Append the other commands
1112 for line in &commands {
1113 script_str.push_str(line);
1114 script_str.push_str("\n");
1117 // Finally, quit the debugger
1118 script_str.push_str("\nquit\n");
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");
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);
1128 if !debugger_run_result.status.success() {
1129 self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
1132 if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
1133 self.fatal_proc_rec(&e, &debugger_run_result);
1139 test_executable: &Path,
1140 debugger_script: &Path,
1141 rust_src_root: &Path,
1143 // Prepare the lldb_batchmode which executes the debugger script
1144 let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
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()),
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())
1160 Err(e) => self.fatal(&format!(
1161 "Failed to setup Python process for \
1167 self.dump_output(&out, &err);
1168 ProcRes { status, stdout: out, stderr: err, cmdline: format!("{:?}", cmd) }
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()];
1175 options.iter().filter(|x| !options_to_remove.contains(x)).map(|x| x.clone()).collect()
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.
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="];
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.
1190 self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
1191 let have_debug_flag = self
1195 .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
1198 if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
1201 if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
1208 fn check_all_error_patterns(
1210 output_to_check: &str,
1212 pm: Option<PassMode>,
1214 if self.props.error_patterns.is_empty() && self.props.regex_error_patterns.is_empty() {
1219 self.fatal(&format!(
1220 "no error pattern specified in {:?}",
1221 self.testpaths.file.display()
1226 let mut missing_patterns: Vec<String> = Vec::new();
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);
1231 if missing_patterns.is_empty() {
1235 if missing_patterns.len() == 1 {
1236 self.fatal_proc_rec(
1237 &format!("error pattern '{}' not found!", missing_patterns[0]),
1241 for pattern in missing_patterns {
1242 self.error(&format!("error pattern '{}' not found!", pattern));
1244 self.fatal_proc_rec("multiple error patterns not found", proc_res);
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);
1254 missing_patterns.push(pattern.to_string());
1259 fn check_regex_error_patterns(
1261 output_to_check: &str,
1263 missing_patterns: &mut Vec<String>,
1265 debug!("check_regex_error_patterns");
1267 for pattern in &self.props.regex_error_patterns {
1268 let pattern = pattern.trim();
1269 let re = match Regex::new(pattern) {
1272 self.fatal_proc_rec(
1273 &format!("invalid regex error pattern '{}': {:?}", pattern, err),
1278 if re.is_match(output_to_check) {
1279 debug!("found regex error pattern {}", pattern);
1281 missing_patterns.push(pattern.to_string());
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)
1291 None => self.fatal_proc_rec("compiler terminated by signal", proc_res),
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);
1304 fn check_expected_errors(&self, expected_errors: Vec<errors::Error>, proc_res: &ProcRes) {
1306 "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
1307 expected_errors, proc_res.status
1309 if proc_res.status.success()
1310 && expected_errors.iter().any(|x| x.kind == Some(ErrorKind::Error))
1312 self.fatal_proc_rec("process did not return an error status", proc_res);
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",
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();
1329 // on windows, translate all '\' path separators to '/'
1330 let file_name = format!("{}", self.testpaths.file.display()).replace(r"\", "/");
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));
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 {
1345 expected_errors.iter().enumerate().position(|(index, expected_error)| {
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)
1355 // found a match, everybody is happy
1356 assert!(!found[index]);
1357 found[index] = true;
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 {}: '{}'",
1366 actual_error.line_num,
1370 .map_or(String::from("message"), |k| k.to_string()),
1373 unexpected.push(actual_error);
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() {
1383 self.error(&format!(
1384 "{}:{}: expected {} not found: {}",
1386 expected_error.line_num,
1387 expected_error.kind.as_ref().map_or("message".into(), |k| k.to_string()),
1390 not_found.push(expected_error);
1394 if !unexpected.is_empty() || !not_found.is_empty() {
1395 self.error(&format!(
1396 "{} unexpected errors found, {} expected errors not found",
1400 println!("status: {}\ncommand: {}", proc_res.status, proc_res.cmdline);
1401 if !unexpected.is_empty() {
1402 println!("unexpected errors (from JSON output): {:#?}\n", unexpected);
1404 if !not_found.is_empty() {
1405 println!("not found errors (from test file): {:#?}\n", not_found);
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(
1417 actual_error: &Error,
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,
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,
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())
1440 fn compile_test_general(
1442 will_execute: WillExecute,
1443 emit_metadata: EmitMetadata,
1444 local_pm: Option<PassMode>,
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())
1454 let allow_unused = match self.config.mode {
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)
1472 _ => AllowUnused::No,
1476 self.make_compile_args(&self.testpaths.file, output_file, emit_metadata, allow_unused);
1478 rustc.arg("-L").arg(&self.aux_output_dir_name());
1480 self.compose_and_run_compiler(rustc, None)
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);
1488 self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1489 let aux_cx = TestCx {
1490 config: self.config,
1492 testpaths: &aux_testpaths,
1493 revision: self.revision,
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() {
1504 let aux_dir = self.aux_output_dir_name();
1506 let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path not passed");
1507 let mut rustdoc = Command::new(rustdoc_path);
1511 .arg(self.config.run_lib_path.to_str().unwrap())
1518 .arg(&self.testpaths.file)
1519 .args(&self.props.compile_flags);
1521 if self.config.mode == RustdocJson {
1522 rustdoc.arg("--output-format").arg("json").arg("-Zunstable-options");
1525 if let Some(ref linker) = self.config.linker {
1526 rustdoc.arg(format!("-Clinker={}", linker));
1529 self.compose_and_run_compiler(rustdoc, None)
1532 fn exec_compiled_test(&self) -> ProcRes {
1533 let env = &self.props.exec_env;
1535 let proc_res = match &*self.config.target {
1536 // This is pretty similar to below, we're transforming:
1538 // program arg1 arg2
1542 // remote-test-client run program 2 support-lib.so support-lib2.so arg1 arg2
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
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() {
1560 support_libs.push(entry.path());
1563 let mut test_client =
1564 Command::new(self.config.remote_test_client.as_ref().unwrap());
1566 .args(&["run", &support_libs.len().to_string(), &prog])
1570 self.compose_and_run(
1572 self.config.run_lib_path.to_str().unwrap(),
1573 Some(aux_dir.to_str().unwrap()),
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(
1584 self.config.run_lib_path.to_str().unwrap(),
1585 Some(aux_dir.to_str().unwrap()),
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(
1596 self.config.run_lib_path.to_str().unwrap(),
1597 Some(aux_dir.to_str().unwrap()),
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());
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 {
1619 .expect("test file path has no parent")
1622 if !test_ab.exists() {
1623 self.fatal(&format!("aux-build `{}` source not found", test_ab.display()))
1631 .join(self.output_testname_unique())
1635 .expect("aux-build path has no parent")
1640 fn is_vxworks_pure_static(&self) -> bool {
1641 if self.config.target.contains("vxworks") {
1642 match env::var("RUST_VXWORKS_TEST_DYLINK") {
1651 fn is_vxworks_pure_dynamic(&self) -> bool {
1652 self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1655 fn build_all_auxiliary(&self, rustc: &mut Command) -> PathBuf {
1656 let aux_dir = self.aux_output_dir_name();
1658 if !self.props.aux_builds.is_empty() {
1659 let _ = fs::remove_dir_all(&aux_dir);
1660 create_dir_all(&aux_dir).unwrap();
1663 for rel_ab in &self.props.aux_builds {
1664 self.build_auxiliary(rel_ab, &aux_dir);
1667 for (aux_name, aux_path) in &self.props.aux_crates {
1668 let is_dylib = self.build_auxiliary(&aux_path, &aux_dir);
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));
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(
1683 self.config.compile_lib_path.to_str().unwrap(),
1684 Some(aux_dir.to_str().unwrap()),
1689 /// Builds an aux dependency.
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,
1699 testpaths: &aux_testpaths,
1700 revision: self.revision,
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;
1706 aux_cx.make_compile_args(input_file, aux_output, EmitMetadata::No, AllowUnused::No);
1708 for key in &aux_props.unset_rustc_env {
1709 aux_rustc.env_remove(key);
1711 aux_rustc.envs(aux_props.rustc_env.clone());
1713 let (dylib, crate_type) = if aux_props.no_prefer_dynamic {
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")
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).
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"))
1736 (true, Some("dylib"))
1739 if let Some(crate_type) = crate_type {
1740 aux_rustc.args(&["--crate-type", crate_type]);
1743 aux_rustc.arg("-L").arg(&aux_dir);
1745 let auxres = aux_cx.compose_and_run(
1747 aux_cx.config.compile_lib_path.to_str().unwrap(),
1748 Some(aux_dir.to_str().unwrap()),
1751 if !auxres.status.success() {
1752 self.fatal_proc_rec(
1754 "auxiliary build of {:?} failed to compile: ",
1755 aux_testpaths.file.display()
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);
1771 filter_paths_from_len.push(path);
1774 // List of paths that will not be measured when determining whether the output is larger
1775 // than the output truncation threshold.
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);
1782 read2_abbreviated(child, &filter_paths_from_len).expect("failed to read output")
1787 mut command: Command,
1789 aux_path: Option<&str>,
1790 input: Option<String>,
1793 let cmdline = self.make_cmdline(&command, lib_path);
1794 logv(self.config, format!("executing {}", cmdline));
1798 command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
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));
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();
1810 let Output { status, stdout, stderr } = self.read2_abbreviated(child);
1812 let result = ProcRes {
1814 stdout: String::from_utf8_lossy(&stdout).into_owned(),
1815 stderr: String::from_utf8_lossy(&stderr).into_owned(),
1819 self.dump_output(&result.stdout, &result.stderr);
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")
1830 fn make_compile_args(
1833 output_file: TargetLocation,
1834 emit_metadata: EmitMetadata,
1835 allow_unused: AllowUnused,
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)
1842 Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1844 rustc.arg(input_file);
1846 // Use a single thread for efficiency and a deterministic error message order
1847 rustc.arg("-Zthreads=1");
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"));
1854 if self.props.force_host { &*self.config.host } else { &*self.config.target };
1856 rustc.arg(&format!("--target={}", target));
1858 self.set_revision_flags(&mut rustc);
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"]);
1866 if self.config.mode == CodegenUnits {
1867 rustc.args(&["-Z", "human_readable_cgu_names"]);
1871 if self.config.optimize_tests && !is_rustdoc {
1872 match self.config.mode {
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)
1884 .any(|arg| arg == "-O" || arg.contains("opt-level"))
1889 DebugInfo => { /* debuginfo tests must be unoptimized */ }
1896 match self.config.mode {
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()
1904 rustc.args(&["--error-format", "json"]);
1905 rustc.args(&["--json", "future-incompat"]);
1907 rustc.arg("-Zui-testing");
1908 rustc.arg("-Zdeduplicate-diagnostics=no");
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"]);
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");
1926 "-Zdump-mir-exclude-pass-number",
1927 "-Zmir-pretty-relative-line-numbers=yes",
1929 if let Some(pass) = &self.props.mir_unit_test {
1930 rustc.args(&["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{}", pass)]);
1932 rustc.arg("-Zmir-opt-level=4");
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);
1944 RunPassValgrind | Pretty | DebugInfo | Codegen | Rustdoc | RustdocJson | RunMake
1945 | CodegenUnits | JsDocTest | Assembly => {
1946 // do not use JSON output
1950 if let (false, EmitMetadata::Yes) = (is_rustdoc, emit_metadata) {
1951 rustc.args(&["--emit", "metadata"]);
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"]);
1963 TargetLocation::ThisFile(path) => {
1964 rustc.arg("-o").arg(path);
1966 TargetLocation::ThisDirectory(path) => {
1968 // `rustdoc` uses `-o` for the output directory.
1969 rustc.arg("-o").arg(path);
1971 rustc.arg("--out-dir").arg(path);
1976 match self.config.compare_mode {
1977 Some(CompareMode::Polonius) => {
1978 rustc.args(&["-Zpolonius"]);
1980 Some(CompareMode::Chalk) => {
1981 rustc.args(&["-Zchalk"]);
1983 Some(CompareMode::SplitDwarf) if self.config.target.contains("windows") => {
1984 rustc.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]);
1986 Some(CompareMode::SplitDwarf) => {
1987 rustc.args(&["-Csplit-debuginfo=unpacked"]);
1989 Some(CompareMode::SplitDwarfSingle) => {
1990 rustc.args(&["-Csplit-debuginfo=packed"]);
1995 // Add `-A unused` before `config` flags and in-test (`props`) flags, so that they can
1997 if let AllowUnused::Yes = allow_unused {
1998 rustc.args(&["-A", "unused"]);
2001 if self.props.force_host {
2002 self.maybe_add_external_args(&mut rustc, &self.config.host_rustcflags);
2004 self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
2006 if let Some(ref linker) = self.config.linker {
2007 rustc.arg(format!("-Clinker={}", linker));
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");
2017 rustc.args(&self.props.compile_flags);
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);
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);
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());
2051 self.fatal("no NodeJS binary found (--nodejs)");
2053 // If this is otherwise wasm, then run tests under nodejs with our
2055 } else if self.config.target.contains("wasm32") {
2056 if let Some(ref p) = self.config.nodejs {
2057 args.push(p.clone());
2059 self.fatal("no NodeJS binary found (--nodejs)");
2066 .unwrap() // chop off `ui`
2068 .unwrap() // chop off `test`
2070 .unwrap(); // chop off `src`
2071 args.push(src.join("src/etc/wasm32-shim.js").display().to_string());
2074 let exe_file = self.make_exe_name();
2076 // FIXME (#9639): This needs to handle non-utf8 paths
2077 args.push(exe_file.to_str().unwrap().to_owned());
2079 // Add the arguments in the run_flags directive
2080 args.extend(self.split_maybe_args(&self.props.run_flags));
2082 let prog = args.remove(0);
2083 ProcArgs { prog, args }
2086 fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<String> {
2091 if s.chars().all(|c| c.is_whitespace()) { None } else { Some(s.to_owned()) }
2098 fn make_cmdline(&self, command: &Command, libpath: &str) -> String {
2101 // Linux and mac don't require adjusting the library search path
2103 format!("{:?}", command)
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))
2111 format!("{} {:?}", lib_path_cmd_prefix(libpath), command)
2115 fn dump_output(&self, out: &str, err: &str) {
2116 let revision = if let Some(r) = self.revision { format!("{}.", r) } else { String::new() };
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);
2123 fn dump_output_file(&self, out: &str, extension: &str) {
2124 let outfile = self.make_out_name(extension);
2125 fs::write(&outfile, out).unwrap();
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)
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()
2139 .with_extra_extension(self.config.mode.disambiguator())
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())
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 }
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())
2160 /// Gets the absolute path to the base filename used as output for the given
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())
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!("------------------------------------------");
2177 fn error(&self, err: &str) {
2178 match self.revision {
2179 Some(rev) => println!("\nerror in revision `{}`: {}", rev, err),
2180 None => println!("\nerror: {}", err),
2184 fn fatal(&self, err: &str) -> ! {
2186 error!("fatal error, panic: {:?}", err);
2187 panic!("fatal error");
2190 fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2192 proc_res.fatal(None, || ());
2195 fn fatal_proc_rec_with_ctx(
2199 on_failure: impl FnOnce(Self),
2202 proc_res.fatal(None, || on_failure(*self));
2205 // codegen tests (using FileCheck)
2207 fn compile_test_and_save_ir(&self) -> ProcRes {
2208 let aux_dir = self.aux_output_dir_name();
2210 let output_file = TargetLocation::ThisDirectory(self.output_base_dir());
2211 let input_file = &self.testpaths.file;
2213 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2214 rustc.arg("-L").arg(aux_dir).arg("--emit=llvm-ir");
2216 self.compose_and_run_compiler(rustc, None)
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");
2224 let output_file = TargetLocation::ThisFile(output_path.clone());
2225 let input_file = &self.testpaths.file;
2227 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2229 rustc.arg("-L").arg(self.aux_output_dir_name());
2231 match self.props.assembly_output.as_ref().map(AsRef::as_ref) {
2232 Some("emit-asm") => {
2233 rustc.arg("--emit=asm");
2236 Some("ptx-linker") => {
2237 // No extra flags needed.
2240 Some(_) => self.fatal("unknown 'assembly-output' header"),
2241 None => self.fatal("missing 'assembly-output' header"),
2244 (self.compose_and_run_compiler(rustc, None), output_path)
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
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)
2260 format!("CHECK,{}", prefix_for_target)
2262 if self.config.llvm_version.unwrap_or(0) >= 130000 {
2263 filecheck.args(&["--allow-unused-prefixes", "--check-prefixes", &prefixes]);
2265 filecheck.args(&["--check-prefixes", &prefixes]);
2267 self.compose_and_run(filecheck, "", None, None)
2270 fn run_codegen_test(&self) {
2271 if self.config.llvm_filecheck.is_none() {
2272 self.fatal("missing --llvm-filecheck");
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);
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);
2287 fn run_assembly_test(&self) {
2288 if self.config.llvm_filecheck.is_none() {
2289 self.fatal("missing --llvm-filecheck");
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);
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);
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" }
2308 fn run_rustdoc_test(&self) {
2309 assert!(self.revision.is_none(), "revisions not relevant here");
2311 let out_dir = self.output_base_dir();
2312 let _ = fs::remove_dir_all(&out_dir);
2313 create_dir_all(&out_dir).unwrap();
2315 let proc_res = self.document(&out_dir);
2316 if !proc_res.status.success() {
2317 self.fatal_proc_rec("rustdoc failed!", &proc_res);
2320 if self.props.check_test_line_numbers_match {
2321 self.check_rustdoc_test_option(proc_res);
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 {
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)
2338 fn compare_to_default_rustdoc(&mut self, out_dir: &Path) {
2339 if !self.config.has_tidy {
2342 println!("info: generating a diff against nightly rustdoc");
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();
2351 // We need to create a new struct for the lifetimes on `config` to work.
2352 let new_rustdoc = TestCx {
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()
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,
2371 rustc.arg("-L").arg(&new_rustdoc.aux_output_dir_name());
2372 new_rustdoc.build_all_auxiliary(&mut rustc);
2374 let proc_res = new_rustdoc.document(&compare_dir);
2375 if !proc_res.status.success() {
2376 eprintln!("failed to run nightly rustdoc");
2383 "--indent-spaces", "2",
2385 "--show-warnings", "no",
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())
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));
2404 tidy_dir(&compare_dir);
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"))
2417 let diff_filename = format!("build/tmp/rustdoc-compare-{}.diff", std::process::id());
2419 if !write_filtered_diff(
2423 self.config.verbose,
2424 |file_type, extension| {
2426 && (extension == Some("html".into()) || extension == Some("js".into()))
2432 match self.config.color {
2433 ColorConfig::AlwaysColor => colored::control::set_override(true),
2434 ColorConfig::NeverColor => colored::control::set_override(false),
2438 if let Some(pager) = pager {
2439 let pager = pager.trim();
2440 if self.config.verbose {
2441 eprintln!("using pager {}", pager);
2443 let output = Command::new(pager)
2444 // disable paging; we want this to be non-interactive
2446 .stdin(File::open(&diff_filename).unwrap())
2447 // Capture output and print it explicitly so it will in turn be
2448 // captured by libtest.
2451 assert!(output.status.success());
2452 println!("{}", String::from_utf8_lossy(&output.stdout));
2453 eprintln!("{}", String::from_utf8_lossy(&output.stderr));
2455 use colored::Colorize;
2456 eprintln!("warning: no pager configured, falling back to unified diff");
2458 "help: try configuring a git pager (e.g. `delta`) with `git config --global core.pager delta`"
2460 let mut out = io::stdout();
2461 let mut diff = BufReader::new(File::open(&diff_filename).unwrap());
2462 let mut line = Vec::new();
2465 match diff.read_until(b'\n', &mut line) {
2468 Err(e) => eprintln!("ERROR: {:?}", e),
2470 match String::from_utf8(line.clone()) {
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();
2479 out.write_all(line.as_bytes()).unwrap();
2483 write!(&mut out, "{}", String::from_utf8_lossy(&line).reversed()).unwrap();
2490 fn run_rustdoc_json_test(&self) {
2491 //FIXME: Add bless option.
2493 assert!(self.revision.is_none(), "revisions not relevant here");
2495 let out_dir = self.output_base_dir();
2496 let _ = fs::remove_dir_all(&out_dir);
2497 create_dir_all(&out_dir).unwrap();
2499 let proc_res = self.document(&out_dir);
2500 if !proc_res.status.success() {
2501 self.fatal_proc_rec("rustdoc failed!", &proc_res);
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())
2510 .arg(root.join(&out_dir))
2512 .arg(&self.testpaths.file),
2515 if !res.status.success() {
2516 self.fatal_proc_rec_with_ctx("jsondocck failed!", &res, |_| {
2517 println!("Rustdoc Output:");
2518 proc_res.print_info();
2522 let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap());
2523 json_out.set_extension("json");
2525 let res = self.cmd2procres(
2526 Command::new(self.config.jsondoclint_path.as_ref().unwrap()).arg(&json_out),
2529 if !res.status.success() {
2530 self.fatal_proc_rec("jsondoclint failed!", &res);
2534 fn get_lines<P: AsRef<Path>>(
2537 mut other_files: Option<&mut Vec<String>>,
2539 let content = fs::read_to_string(&path).unwrap();
2540 let mut ignore = false;
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(';')
2549 if let Some(ref mut other_files) = other_files {
2550 other_files.push(line.rsplit("mod ").next().unwrap().replace(";", ""));
2554 let sline = line.rsplit("///").next().unwrap();
2555 let line = sline.trim_start();
2556 if line.starts_with("```") {
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();
2580 .unwrap_or(&self.testpaths.file)
2583 .replace('\\', "/"),
2584 self.get_lines(&self.testpaths.file, Some(&mut other_files)),
2586 for other_file in other_files {
2587 let mut path = self.testpaths.file.clone();
2588 path.set_file_name(&format!("{}.rs", other_file));
2590 path.strip_prefix(&cwd).unwrap_or(&path).to_str().unwrap().replace('\\', "/"),
2591 self.get_lines(&path, None),
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('\\', "/")) {
2601 let mut iter = right.split("(line ");
2611 if let Ok(pos) = v.binary_search(&line) {
2614 self.fatal_proc_rec(
2615 &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2623 self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2625 for (entry, v) in &files {
2627 self.fatal_proc_rec(
2629 "Not found test at line{} \"{}\":{:?}",
2630 if v.len() > 1 { "s" } else { "" },
2641 fn run_codegen_units_test(&self) {
2642 assert!(self.revision.is_none(), "revisions not relevant here");
2644 let proc_res = self.compile_test(WillExecute::No, EmitMetadata::No);
2646 if !proc_res.status.success() {
2647 self.fatal_proc_rec("compilation failed!", &proc_res);
2650 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
2652 const PREFIX: &str = "MONO_ITEM ";
2653 const CGU_MARKER: &str = "@@";
2655 let actual: Vec<MonoItem> = proc_res
2658 .filter(|line| line.starts_with(PREFIX))
2659 .map(|line| str_to_mono_item(line, true))
2662 let expected: Vec<MonoItem> = errors::load_errors(&self.testpaths.file, None)
2664 .map(|e| str_to_mono_item(&e.msg[..], false))
2667 let mut missing = Vec::new();
2668 let mut wrong_cgus = Vec::new();
2670 for expected_item in &expected {
2671 let actual_item_with_same_name = actual.iter().find(|ti| ti.name == expected_item.name);
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
2678 wrong_cgus.push((expected_item.clone(), actual_item.clone()));
2681 missing.push(expected_item.string.clone());
2685 let unexpected: Vec<_> = actual
2687 .filter(|acgu| !expected.iter().any(|ecgu| acgu.name == ecgu.name))
2688 .map(|acgu| acgu.string.clone())
2691 if !missing.is_empty() {
2694 println!("\nThese items should have been contained but were not:\n");
2696 for item in &missing {
2697 println!("{}", item);
2703 if !unexpected.is_empty() {
2705 let mut sorted = unexpected.clone();
2710 println!("\nThese items were contained but should not have been:\n");
2712 for item in sorted {
2713 println!("{}", item);
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");
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));
2731 if !(missing.is_empty() && unexpected.is_empty() && wrong_cgus.is_empty()) {
2735 #[derive(Clone, Eq, PartialEq)]
2738 codegen_units: HashSet<String>,
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() };
2746 let full_string = format!("{}{}", PREFIX, s);
2748 let parts: Vec<&str> =
2749 s.split(CGU_MARKER).map(str::trim).filter(|s| !s.is_empty()).collect();
2751 let name = parts[0].trim();
2753 let cgus = if parts.len() > 1 {
2754 let cgus_str = parts[1];
2759 .filter(|s| !s.is_empty())
2761 if cgu_has_crate_disambiguator {
2762 remove_crate_disambiguators_from_set_of_cgu_names(s)
2772 MonoItem { name: name.to_owned(), codegen_units: cgus, string: full_string }
2775 fn codegen_units_to_str(cgus: &HashSet<String>) -> String {
2776 let mut cgus: Vec<_> = cgus.iter().collect();
2779 let mut string = String::new();
2781 string.push_str(&cgu[..]);
2782 string.push_str(" ");
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 {
2793 static ref RE: Regex =
2794 Regex::new(r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?")
2799 RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {}", cgu));
2801 let mut new_name = cgu.to_owned();
2803 if let Some(d2) = captures.name("d2") {
2804 new_name.replace_range(d2.start()..d2.end(), "");
2807 let d1 = captures.name("d1").unwrap();
2808 new_name.replace_range(d1.start()..d1.end(), "");
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 {
2818 .map(|cgu| remove_crate_disambiguator_from_cgu(cgu))
2819 .collect::<Vec<_>>()
2824 fn init_incremental_test(&self) {
2825 // (See `run_incremental_test` for an overview of how incremental tests work.)
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
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();
2838 fs::create_dir_all(&incremental_dir).unwrap();
2840 if self.config.verbose {
2841 println!("init_incremental_test: incremental_dir={}", incremental_dir.display());
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
2862 // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2863 // to #[rustc_dirty] and clean tests I guess
2865 let revision = self.revision.expect("incremental tests require a list of revisions");
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");
2871 if self.config.verbose {
2872 print!("revision={:?} props={:#?}", revision, self.props);
2875 if revision.starts_with("rpass") {
2876 if self.props.should_ice {
2877 self.fatal("can only use should-ice in cfail tests");
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");
2884 self.run_rfail_test();
2885 } else if revision.starts_with("cfail") {
2886 self.run_cfail_test();
2888 self.fatal("revision name must begin with rpass, rfail, or cfail");
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);
2897 let tmpdir = cwd.join(self.output_base_name());
2898 if tmpdir.exists() {
2899 self.aggressive_rm_rf(&tmpdir).unwrap();
2901 create_dir_all(&tmpdir).unwrap();
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")
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)
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`
2931 .env_remove("MAKEFLAGS")
2932 .env_remove("MFLAGS")
2933 .env_remove("CARGO_MAKEFLAGS");
2935 if let Some(ref rustdoc) = self.config.rustdoc_path {
2936 cmd.env("RUSTDOC", cwd.join(rustdoc));
2939 if let Some(ref rust_demangler) = self.config.rust_demangler_path {
2940 cmd.env("RUST_DEMANGLER", cwd.join(rust_demangler));
2943 if let Some(ref node) = self.config.nodejs {
2944 cmd.env("NODE", node);
2947 if let Some(ref linker) = self.config.linker {
2948 cmd.env("RUSTC_LINKER", linker);
2951 if let Some(ref clang) = self.config.run_clang_based_tests_with {
2952 cmd.env("CLANG", clang);
2955 if let Some(ref filecheck) = self.config.llvm_filecheck {
2956 cmd.env("LLVM_FILECHECK", filecheck);
2959 if let Some(ref llvm_bin_dir) = self.config.llvm_bin_dir {
2960 cmd.env("LLVM_BIN_DIR", llvm_bin_dir);
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");
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");
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:
2977 // ifdef RUSTC_BLESS_TEST
2978 // cp "$(TMPDIR)"/actual_something.ext expected_something.ext
2980 // $(DIFF) expected_something.ext "$(TMPDIR)"/actual_something.ext
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");
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.
2996 .map(|s| s.replace("/", "-"))
2997 .collect::<Vec<_>>()
3003 .map(|s| s.replace("/", "-"))
3004 .collect::<Vec<_>>()
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));
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);
3017 if self.config.target.contains("windows") {
3018 cmd.env("IS_WINDOWS", "1");
3022 let output = self.read2_abbreviated(cmd.spawn().expect("failed to spawn `make`"));
3023 if !output.status.success() {
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),
3030 self.fatal_proc_rec("make failed", &res);
3034 fn aggressive_rm_rf(&self, path: &Path) -> io::Result<()> {
3035 for e in path.read_dir()? {
3037 let path = entry.path();
3038 if entry.file_type()?.is_dir() {
3039 self.aggressive_rm_rf(&path)?;
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)
3054 fs::remove_dir(path)
3057 fn run_js_doc_test(&self) {
3058 if let Some(nodejs) = &self.config.nodejs {
3059 let out_dir = self.output_base_dir();
3061 self.document(&out_dir);
3063 let root = self.config.find_rust_src_root().unwrap();
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")
3071 .arg("--crate-name")
3072 .arg(file_stem.replace("-", "_"))
3074 .arg(self.testpaths.file.with_extension("js")),
3076 if !res.status.success() {
3077 self.fatal_proc_rec("rustdoc-js test failed!", &res);
3080 self.fatal("no nodeJS");
3084 fn load_compare_outputs(
3087 output_kind: TestOutput,
3088 explicit_format: bool,
3090 let stderr_bits = format!("{}bit.stderr", self.config.get_pointer_width());
3091 let (stderr_kind, stdout_kind) = match output_kind {
3092 TestOutput::Compile => (
3094 if self.props.stderr_per_bitwidth { &stderr_bits } else { UI_STDERR }
3098 TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
3101 let expected_stderr = self.load_expected_output(stderr_kind);
3102 let expected_stdout = self.load_expected_output(stdout_kind);
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
3111 static ref REMOTE_TEST_RE: Regex = Regex::new(
3112 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-.]+)+\", waiting for result\n"
3118 &self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
3123 _ => self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
3126 let stderr = if explicit_format {
3127 proc_res.stderr.clone()
3129 json::extract_rendered(&proc_res.stderr)
3132 let normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
3135 TestOutput::Compile => {
3136 if !self.props.dont_check_compiler_stdout {
3138 self.compare_output(stdout_kind, &normalized_stdout, &expected_stdout);
3140 if !self.props.dont_check_compiler_stderr {
3142 self.compare_output(stderr_kind, &normalized_stderr, &expected_stderr);
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);
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);
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);
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"));
3172 let expected_fixed = self.load_expected_output(UI_FIXED);
3174 self.check_and_prune_duplicate_outputs(&proc_res, &[], &[]);
3176 let mut errors = self.load_compare_outputs(&proc_res, TestOutput::Compile, explicit);
3177 let rustfix_input = json::rustfix_diagnostics_only(&proc_res.stderr);
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.
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(
3190 Filter::MachineApplicableOnly,
3192 .unwrap_or_default();
3193 if !suggestions.is_empty()
3194 && !self.props.run_rustfix
3195 && !self.props.rustfix_only_machine_applicable
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());
3201 let mut file = OpenOptions::new()
3204 .open(coverage_file_path.as_path())
3205 .expect("could not create or open file");
3207 if writeln!(file, "{}", self.testpaths.file.display()).is_err() {
3208 panic!("couldn't write to {}", coverage_file_path.display());
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(
3217 if self.props.rustfix_only_machine_applicable {
3218 Filter::MachineApplicableOnly
3224 let fixed_code = apply_suggestions(&unfixed_code, &suggestions).unwrap_or_else(|e| {
3226 "failed to apply suggestions for {:?} with rustfix: {}",
3227 self.testpaths.file, e
3231 errors += self.compare_output("fixed", &fixed_code, &expected_fixed);
3232 } else if !expected_fixed.is_empty() {
3234 "the `// run-rustfix` directive wasn't found but a `*.fixed` \
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());
3244 "To only update this specific test, also pass `--test-args {}`",
3245 relative_path_to_file.display(),
3247 self.fatal_proc_rec(
3248 &format!("{} errors occurred comparing output.", errors),
3253 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
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)
3262 if run_output_errors > 0 {
3263 self.fatal_proc_rec(
3264 &format!("{} errors occurred comparing run output.", run_output_errors),
3268 if self.should_run_successfully(pm) {
3269 if !proc_res.status.success() {
3270 self.fatal_proc_rec("test run failed!", &proc_res);
3272 } else if proc_res.status.success() {
3273 self.fatal_proc_rec("test run succeeded!", &proc_res);
3276 if !self.props.error_patterns.is_empty() || !self.props.regex_error_patterns.is_empty()
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);
3285 "run_ui_test: explicit={:?} config.compare_mode={:?} expected_errors={:?} \
3286 proc_res.status={:?} props.error_patterns={:?}",
3288 self.config.compare_mode,
3291 self.props.error_patterns
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());
3298 let check_annotations = !check_patterns || !expected_errors.is_empty();
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);
3306 if check_annotations {
3307 // "//~ERROR comments"
3308 self.check_expected_errors(expected_errors, &proc_res);
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()),
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);
3326 if !res.stderr.is_empty()
3327 && !self.props.rustfix_only_machine_applicable
3328 && !json::rustfix_diagnostics_only(&res.stderr).is_empty()
3330 self.fatal_proc_rec("fixed code is still producing diagnostics", &res);
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);
3341 if !proc_res.status.success() {
3342 self.fatal_proc_rec("compilation failed!", &proc_res);
3345 self.check_mir_dump();
3347 if let WillExecute::Yes = should_run {
3348 let proc_res = self.exec_compiled_test();
3350 if !proc_res.status.success() {
3351 self.fatal_proc_rec("test run failed!", &proc_res);
3356 fn check_mir_dump(&self) {
3357 let test_file_contents = fs::read_to_string(&self.testpaths.file).unwrap();
3359 let test_dir = self.testpaths.file.parent().unwrap();
3361 self.testpaths.file.file_stem().unwrap().to_str().unwrap().replace("-", "_");
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());
3368 if self.config.bless {
3370 glob(&format!("{}/{}.*{}.mir", test_dir.display(), test_crate, bit_width)).unwrap()
3372 std::fs::remove_file(e.unwrap()).unwrap();
3375 glob(&format!("{}/{}.*{}.diff", test_dir.display(), test_crate, bit_width)).unwrap()
3377 std::fs::remove_file(e.unwrap()).unwrap();
3381 let files = miropt_test_tools::files_for_miropt_test(
3382 &self.testpaths.file,
3383 self.config.get_pointer_width(),
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())
3390 let mut output_file = PathBuf::new();
3391 output_file.push(self.get_mir_dump_dir());
3392 output_file.push(&from_file);
3394 "comparing the contents of: {} with {}",
3395 output_file.display(),
3396 expected_file.display()
3398 if !output_file.exists() {
3400 "Output file `{}` from test does not exist, available files are in `{}`",
3401 output_file.display(),
3402 output_file.parent().unwrap().display()
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, &[])
3410 if self.config.bless {
3411 let _ = std::fs::remove_file(&expected_file);
3412 std::fs::write(expected_file, dumped_string.as_bytes()).unwrap();
3414 if !expected_file.exists() {
3415 panic!("Output file `{}` from test does not exist", expected_file.display());
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));
3421 "Actual MIR output differs from expected MIR output {}",
3422 expected_file.display()
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);
3434 "the mir dump file for {} does not exist (requested in {})",
3436 self.testpaths.file.display(),
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;
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(),
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);
3468 "test source file `{}` is newer than potentially stale output file `{}`.",
3469 source_file.display(),
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());
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");
3492 let mut normalized = output.to_string();
3494 let mut normalize_path = |from: &Path, to: &str| {
3495 let mut from = from.display().to_string();
3497 from = from.replace("\\", "\\\\");
3499 normalized = normalized.replace(&from, to);
3502 let parent_dir = self.testpaths.file.parent().unwrap();
3503 normalize_path(parent_dir, "$DIR");
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");
3510 // `ui-fulldeps` tests can show paths to the compiler source when testing macros from
3512 // eg. /home/user/rust/compiler
3513 let compiler_src_dir = base_dir.join("compiler");
3514 normalize_path(&compiler_src_dir, "$COMPILER_DIR");
3516 if let Some(virtual_rust_source_base_dir) =
3517 option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR").map(PathBuf::from)
3519 normalize_path(&virtual_rust_source_base_dir.join("library"), "$SRC_DIR");
3520 normalize_path(&virtual_rust_source_base_dir.join("compiler"), "$COMPILER_DIR");
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();
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");
3532 // Paths into lib directory.
3533 normalize_path(&parent_build_dir.parent().unwrap().join("lib"), "$LIB_DIR");
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");
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
3546 // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
3548 static ref SRC_DIR_RE: Regex =
3549 Regex::new("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?").unwrap();
3552 normalized = SRC_DIR_RE.replace_all(&normalized, "SRC_DIR$1:LL:COL").into_owned();
3554 normalized = Self::normalize_platform_differences(&normalized);
3555 normalized = normalized.replace("\t", "\\t"); // makes tabs visible
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.
3562 static ref ANNOTATION_RE: Regex = Regex::new("\\s*//(\\[.*\\])?~.*").unwrap();
3565 normalized = ANNOTATION_RE.replace_all(&normalized, "").into_owned();
3567 // This code normalizes various hashes in v0 symbol mangling that is
3568 // emitted in the ui and mir-opt tests.
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();
3575 const V0_CRATE_HASH_PLACEHOLDER: &str = r"CsCRATE_HASH_";
3576 if V0_CRATE_HASH_PREFIX_RE.is_match(&normalized) {
3577 // Normalize crate hash
3579 V0_CRATE_HASH_RE.replace_all(&normalized, V0_CRATE_HASH_PLACEHOLDER).into_owned();
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();
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)
3591 V0_BACK_REF_RE.replace_all(&normalized, V0_BACK_REF_PLACEHOLDER).into_owned();
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();
3602 /// Normalize output differences across platforms. Generally changes Windows output to be more
3605 /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
3607 fn normalize_platform_differences(output: &str) -> String {
3609 /// Used to find Windows paths.
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)
3615 # Match paths that don't include spaces.
3616 (?:\\[\pL\pN\.\-_']+)+\.\pL+
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\.\-_' ]+)+
3624 let output = output.replace(r"\\", r"\");
3627 .replace_all(&output, |caps: &Captures<'_>| {
3628 println!("{}", &caps[0]);
3629 caps[0].replace(r"\", "/")
3631 .replace("\r\n", "\n")
3634 fn expected_output_path(&self, kind: &str) -> PathBuf {
3636 expected_output_path(&self.testpaths, self.revision, &self.config.compare_mode, kind);
3639 if let Some(CompareMode::Polonius) = self.config.compare_mode {
3640 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3645 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3651 fn load_expected_output(&self, kind: &str) -> String {
3652 let path = self.expected_output_path(kind);
3654 match self.load_expected_output_from_path(&path) {
3656 Err(x) => self.fatal(&x),
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)
3669 fn delete_file(&self, file: &PathBuf) {
3671 // Deleting a nonexistent file would error.
3674 if let Err(e) = fs::remove_file(file) {
3675 self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,));
3679 fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize {
3680 if actual == expected {
3684 if !self.config.bless {
3685 if expected.is_empty() {
3686 println!("normalized {}:\n{}\n", kind, actual);
3688 println!("diff of {}:\n", kind);
3689 print!("{}", write_diff(expected, actual, 3));
3693 let mode = self.config.compare_mode.as_ref().map_or("", |m| m.to_str());
3694 let output_file = self
3696 .with_extra_extension(self.revision.unwrap_or(""))
3697 .with_extra_extension(mode)
3698 .with_extra_extension(kind);
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() {
3706 expected_output_path(self.testpaths, None, &self.config.compare_mode, kind);
3707 self.delete_file(&old);
3709 files.push(expected_output_path(
3712 &self.config.compare_mode,
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 `{}`: {}",
3724 output_file.display(),
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());
3734 if self.config.bless { 0 } else { 1 }
3737 fn check_and_prune_duplicate_outputs(
3740 modes: &[CompareMode],
3741 require_same_modes: &[CompareMode],
3743 for kind in UI_EXTENSIONS {
3744 let canon_comparison_path =
3745 expected_output_path(&self.testpaths, self.revision, &None, kind);
3747 let canon = match self.load_expected_output_from_path(&canon_comparison_path) {
3751 let bless = self.config.bless;
3752 let check_and_prune_duplicate_outputs = |mode: &CompareMode, require_same: bool| {
3754 expected_output_path(&self.testpaths, self.revision, &Some(mode.clone()), kind);
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,
3762 let is_duplicate = canon == examined_content;
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);
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),
3781 check_and_prune_duplicate_outputs(mode, false);
3783 for mode in require_same_modes {
3784 check_and_prune_duplicate_outputs(mode, true);
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();
3800 pub struct 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")
3817 --- {name} -------------------------------\n\
3819 ------------------------------------------",
3825 "status: {}\ncommand: {}\n{}\n{}\n",
3828 render("stdout", &self.stdout),
3829 render("stderr", &self.stderr),
3833 pub fn fatal(&self, err: Option<&str>, on_failure: impl FnOnce()) -> ! {
3834 if let Some(e) = err {
3835 println!("\nerror: {}", e);
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(()));
3846 enum TargetLocation {
3848 ThisDirectory(PathBuf),