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::get_pointer_width;
17 use crate::util::{logv, PathBufExt};
18 use crate::ColorConfig;
19 use regex::{Captures, Regex};
20 use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
22 use std::collections::hash_map::DefaultHasher;
23 use std::collections::{HashMap, HashSet};
25 use std::ffi::{OsStr, OsString};
26 use std::fs::{self, create_dir_all, File, OpenOptions};
27 use std::hash::{Hash, Hasher};
28 use std::io::prelude::*;
29 use std::io::{self, BufReader};
30 use std::path::{Path, PathBuf};
31 use std::process::{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 name of the environment variable that holds dynamic library locations.
77 pub fn dylib_env_var() -> &'static str {
80 } else if cfg!(target_os = "macos") {
82 } else if cfg!(target_os = "haiku") {
89 /// The platform-specific library name
90 pub fn get_lib_name(lib: &str, dylib: bool) -> String {
91 // In some casess (e.g. MUSL), we build a static
92 // library, rather than a dynamic library.
93 // In this case, the only path we can pass
94 // with '--extern-meta' is the '.lib' file
96 return format!("lib{}.rlib", lib);
100 format!("{}.dll", lib)
101 } else if cfg!(target_os = "macos") {
102 format!("lib{}.dylib", lib)
104 format!("lib{}.so", lib)
108 pub fn run(config: Config, testpaths: &TestPaths, revision: Option<&str>) {
109 match &*config.target {
110 "arm-linux-androideabi"
111 | "armv7-linux-androideabi"
112 | "thumbv7neon-linux-androideabi"
113 | "aarch64-linux-android" => {
114 if !config.adb_device_status {
115 panic!("android device not available");
120 // android has its own gdb handling
121 if config.debugger == Some(Debugger::Gdb) && config.gdb.is_none() {
122 panic!("gdb not available but debuginfo gdb debuginfo test requested");
128 // We're going to be dumping a lot of info. Start on a new line.
131 debug!("running {:?}", testpaths.file.display());
132 let mut props = TestProps::from_file(&testpaths.file, revision, &config);
133 if props.incremental {
134 props.incremental_dir = Some(incremental_dir(&config, testpaths));
137 let cx = TestCx { config: &config, props: &props, testpaths, revision };
138 create_dir_all(&cx.output_base_dir()).unwrap();
139 if props.incremental {
140 cx.init_incremental_test();
143 if config.mode == Incremental {
144 // Incremental tests are special because they cannot be run in
146 assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
147 for revision in &props.revisions {
148 let mut revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
149 revision_props.incremental_dir = props.incremental_dir.clone();
150 let rev_cx = TestCx {
152 props: &revision_props,
154 revision: Some(revision),
156 rev_cx.run_revision();
165 pub fn compute_stamp_hash(config: &Config) -> String {
166 let mut hash = DefaultHasher::new();
167 config.stage_id.hash(&mut hash);
168 config.run.hash(&mut hash);
170 match config.debugger {
171 Some(Debugger::Cdb) => {
172 config.cdb.hash(&mut hash);
175 Some(Debugger::Gdb) => {
176 config.gdb.hash(&mut hash);
177 env::var_os("PATH").hash(&mut hash);
178 env::var_os("PYTHONPATH").hash(&mut hash);
181 Some(Debugger::Lldb) => {
182 config.lldb_python.hash(&mut hash);
183 config.lldb_python_dir.hash(&mut hash);
184 env::var_os("PATH").hash(&mut hash);
185 env::var_os("PYTHONPATH").hash(&mut hash);
191 if let Ui = config.mode {
192 config.force_pass_mode.hash(&mut hash);
195 format!("{:x}", hash.finish())
198 #[derive(Copy, Clone)]
199 struct TestCx<'test> {
200 config: &'test Config,
201 props: &'test TestProps,
202 testpaths: &'test TestPaths,
203 revision: Option<&'test str>,
216 /// Will this test be executed? Should we use `make_exe_name`?
217 #[derive(Copy, Clone, PartialEq)]
224 /// Should `--emit metadata` be used?
225 #[derive(Copy, Clone)]
231 impl<'test> TestCx<'test> {
232 /// Code executed for each revision in turn (or, if there are no
233 /// revisions, exactly once, with revision == None).
234 fn run_revision(&self) {
235 if self.props.should_ice && self.config.mode != Incremental {
236 self.fatal("cannot use should-ice in a test that is not cfail");
238 match self.config.mode {
239 RunPassValgrind => self.run_valgrind_test(),
240 Pretty => self.run_pretty_test(),
241 DebugInfo => self.run_debuginfo_test(),
242 Codegen => self.run_codegen_test(),
243 Rustdoc => self.run_rustdoc_test(),
244 RustdocJson => self.run_rustdoc_json_test(),
245 CodegenUnits => self.run_codegen_units_test(),
246 Incremental => self.run_incremental_test(),
247 RunMake => self.run_rmake_test(),
248 Ui => self.run_ui_test(),
249 MirOpt => self.run_mir_opt_test(),
250 Assembly => self.run_assembly_test(),
251 JsDocTest => self.run_js_doc_test(),
255 fn pass_mode(&self) -> Option<PassMode> {
256 self.props.pass_mode(self.config)
259 fn should_run(&self, pm: Option<PassMode>) -> WillExecute {
260 let test_should_run = match self.config.mode {
261 Ui if pm == Some(PassMode::Run) || self.props.fail_mode == Some(FailMode::Run) => true,
262 MirOpt if pm == Some(PassMode::Run) => true,
263 Ui | MirOpt => false,
264 mode => panic!("unimplemented for mode {:?}", mode),
266 if test_should_run { self.run_if_enabled() } else { WillExecute::No }
269 fn run_if_enabled(&self) -> WillExecute {
270 if self.config.run_enabled() { WillExecute::Yes } else { WillExecute::Disabled }
273 fn should_run_successfully(&self, pm: Option<PassMode>) -> bool {
274 match self.config.mode {
275 Ui | MirOpt => pm == Some(PassMode::Run),
276 mode => panic!("unimplemented for mode {:?}", mode),
280 fn should_compile_successfully(&self, pm: Option<PassMode>) -> bool {
281 match self.config.mode {
283 Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
286 self.revision.expect("incremental tests require a list of revisions");
287 if revision.starts_with("rpass") || revision.starts_with("rfail") {
289 } else if revision.starts_with("cfail") {
290 // FIXME: would be nice if incremental revs could start with "cpass"
293 panic!("revision name must begin with rpass, rfail, or cfail");
296 mode => panic!("unimplemented for mode {:?}", mode),
300 fn check_if_test_should_compile(&self, proc_res: &ProcRes, pm: Option<PassMode>) {
301 if self.should_compile_successfully(pm) {
302 if !proc_res.status.success() {
303 self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res);
306 if proc_res.status.success() {
308 &format!("{} test compiled successfully!", self.config.mode)[..],
313 self.check_correct_failure_status(proc_res);
317 fn run_cfail_test(&self) {
318 let pm = self.pass_mode();
319 let proc_res = self.compile_test(WillExecute::No, self.should_emit_metadata(pm));
320 self.check_if_test_should_compile(&proc_res, pm);
321 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
323 let output_to_check = self.get_output(&proc_res);
324 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
325 if !expected_errors.is_empty() {
326 if !self.props.error_patterns.is_empty() {
327 self.fatal("both error pattern and expected errors specified");
329 self.check_expected_errors(expected_errors, &proc_res);
331 self.check_error_patterns(&output_to_check, &proc_res, pm);
333 if self.props.should_ice {
334 match proc_res.status.code() {
336 _ => self.fatal("expected ICE"),
340 self.check_forbid_output(&output_to_check, &proc_res);
343 fn run_rfail_test(&self) {
344 let pm = self.pass_mode();
345 let should_run = self.run_if_enabled();
346 let proc_res = self.compile_test(should_run, self.should_emit_metadata(pm));
348 if !proc_res.status.success() {
349 self.fatal_proc_rec("compilation failed!", &proc_res);
352 if let WillExecute::Disabled = should_run {
356 let proc_res = self.exec_compiled_test();
358 // The value our Makefile configures valgrind to return on failure
359 const VALGRIND_ERR: i32 = 100;
360 if proc_res.status.code() == Some(VALGRIND_ERR) {
361 self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
364 let output_to_check = self.get_output(&proc_res);
365 self.check_correct_failure_status(&proc_res);
366 self.check_error_patterns(&output_to_check, &proc_res, pm);
369 fn get_output(&self, proc_res: &ProcRes) -> String {
370 if self.props.check_stdout {
371 format!("{}{}", proc_res.stdout, proc_res.stderr)
373 proc_res.stderr.clone()
377 fn check_correct_failure_status(&self, proc_res: &ProcRes) {
378 let expected_status = Some(self.props.failure_status);
379 let received_status = proc_res.status.code();
381 if expected_status != received_status {
384 "Error: expected failure status ({:?}) but received status {:?}.",
385 expected_status, received_status
392 fn run_rpass_test(&self) {
393 let emit_metadata = self.should_emit_metadata(self.pass_mode());
394 let should_run = self.run_if_enabled();
395 let proc_res = self.compile_test(should_run, emit_metadata);
397 if !proc_res.status.success() {
398 self.fatal_proc_rec("compilation failed!", &proc_res);
401 if let WillExecute::Disabled = should_run {
405 // FIXME(#41968): Move this check to tidy?
406 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
408 expected_errors.is_empty(),
409 "run-pass tests with expected warnings should be moved to ui/"
412 let proc_res = self.exec_compiled_test();
413 if !proc_res.status.success() {
414 self.fatal_proc_rec("test run failed!", &proc_res);
418 fn run_valgrind_test(&self) {
419 assert!(self.revision.is_none(), "revisions not relevant here");
421 if self.config.valgrind_path.is_none() {
422 assert!(!self.config.force_valgrind);
423 return self.run_rpass_test();
426 let should_run = self.run_if_enabled();
427 let mut proc_res = self.compile_test(should_run, EmitMetadata::No);
429 if !proc_res.status.success() {
430 self.fatal_proc_rec("compilation failed!", &proc_res);
433 if let WillExecute::Disabled = should_run {
437 let mut new_config = self.config.clone();
438 new_config.runtool = new_config.valgrind_path.clone();
439 let new_cx = TestCx { config: &new_config, ..*self };
440 proc_res = new_cx.exec_compiled_test();
442 if !proc_res.status.success() {
443 self.fatal_proc_rec("test run failed!", &proc_res);
447 fn run_pretty_test(&self) {
448 if self.props.pp_exact.is_some() {
449 logv(self.config, "testing for exact pretty-printing".to_owned());
451 logv(self.config, "testing for converging pretty-printing".to_owned());
454 let rounds = match self.props.pp_exact {
459 let src = fs::read_to_string(&self.testpaths.file).unwrap();
460 let mut srcs = vec![src];
463 while round < rounds {
466 format!("pretty-printing round {} revision {:?}", round, self.revision),
469 if round == 0 { ReadFrom::Path } else { ReadFrom::Stdin(srcs[round].to_owned()) };
471 let proc_res = self.print_source(read_from, &self.props.pretty_mode);
472 if !proc_res.status.success() {
475 "pretty-printing failed in round {} revision {:?}",
482 let ProcRes { stdout, .. } = proc_res;
487 let mut expected = match self.props.pp_exact {
489 let filepath = self.testpaths.file.parent().unwrap().join(file);
490 fs::read_to_string(&filepath).unwrap()
492 None => srcs[srcs.len() - 2].clone(),
494 let mut actual = srcs[srcs.len() - 1].clone();
496 if self.props.pp_exact.is_some() {
497 // Now we have to care about line endings
498 let cr = "\r".to_owned();
499 actual = actual.replace(&cr, "");
500 expected = expected.replace(&cr, "");
503 self.compare_source(&expected, &actual);
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(
551 self.split_maybe_args(&self.config.target_rustcflags),
554 let src = match read_from {
555 ReadFrom::Stdin(src) => Some(src),
556 ReadFrom::Path => None,
559 self.compose_and_run(
561 self.config.compile_lib_path.to_str().unwrap(),
562 Some(aux_dir.to_str().unwrap()),
567 fn compare_source(&self, expected: &str, actual: &str) {
568 if expected != actual {
570 "pretty-printed source does not match expected source\n\
572 ------------------------------------------\n\
574 ------------------------------------------\n\
576 ------------------------------------------\n\
578 ------------------------------------------\n\
580 ------------------------------------------\n\
584 write_diff(expected, actual, 3),
589 fn set_revision_flags(&self, cmd: &mut Command) {
590 if let Some(revision) = self.revision {
591 // Normalize revisions to be lowercase and replace `-`s with `_`s.
592 // Otherwise the `--cfg` flag is not valid.
593 let normalized_revision = revision.to_lowercase().replace("-", "_");
594 cmd.args(&["--cfg", &normalized_revision]);
598 fn typecheck_source(&self, src: String) -> ProcRes {
599 let mut rustc = Command::new(&self.config.rustc_path);
601 let out_dir = self.output_base_name().with_extension("pretty-out");
602 let _ = fs::remove_dir_all(&out_dir);
603 create_dir_all(&out_dir).unwrap();
605 let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
607 let aux_dir = self.aux_output_dir_name();
614 .arg(&format!("--target={}", target))
616 .arg(&self.config.build_base)
619 self.set_revision_flags(&mut rustc);
620 self.maybe_add_external_args(
622 self.split_maybe_args(&self.config.target_rustcflags),
624 rustc.args(&self.props.compile_flags);
626 self.compose_and_run_compiler(rustc, Some(src))
629 fn run_debuginfo_test(&self) {
630 match self.config.debugger.unwrap() {
631 Debugger::Cdb => self.run_debuginfo_cdb_test(),
632 Debugger::Gdb => self.run_debuginfo_gdb_test(),
633 Debugger::Lldb => self.run_debuginfo_lldb_test(),
637 fn run_debuginfo_cdb_test(&self) {
638 assert!(self.revision.is_none(), "revisions not relevant here");
640 let config = Config {
641 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
642 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
643 ..self.config.clone()
646 let test_cx = TestCx { config: &config, ..*self };
648 test_cx.run_debuginfo_cdb_test_no_opt();
651 fn run_debuginfo_cdb_test_no_opt(&self) {
652 // compile test file (it should have 'compile-flags:-g' in the header)
653 let should_run = self.run_if_enabled();
654 let compile_result = self.compile_test(should_run, EmitMetadata::No);
655 if !compile_result.status.success() {
656 self.fatal_proc_rec("compilation failed!", &compile_result);
658 if let WillExecute::Disabled = should_run {
662 let exe_file = self.make_exe_name();
665 static PREFIXES: &[&str] = &["cdb", "cdbg"];
666 // No "native rust support" variation for CDB yet.
670 // Parse debugger commands etc from test files
671 let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
672 match DebuggerCommands::parse_from(&self.testpaths.file, self.config, prefixes) {
674 Err(e) => self.fatal(&e),
677 // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-commands
678 let mut script_str = String::with_capacity(2048);
679 script_str.push_str("version\n"); // List CDB (and more) version info in test output
680 script_str.push_str(".nvlist\n"); // List loaded `*.natvis` files, bulk of custom MSVC debug
682 // If a .js file exists next to the source file being tested, then this is a JavaScript
683 // debugging extension that needs to be loaded.
684 let mut js_extension = self.testpaths.file.clone();
685 js_extension.set_extension("cdb.js");
686 if js_extension.exists() {
687 script_str.push_str(&format!(".scriptload \"{}\"\n", js_extension.to_string_lossy()));
690 // Set breakpoints on every line that contains the string "#break"
691 let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
692 for line in &breakpoint_lines {
693 script_str.push_str(&format!("bp `{}:{}`\n", source_file_name, line));
696 // Append the other `cdb-command:`s
697 for line in &commands {
698 script_str.push_str(line);
699 script_str.push_str("\n");
702 script_str.push_str("\nqq\n"); // Quit the debugger (including remote debugger, if any)
704 // Write the script into a file
705 debug!("script_str = {}", script_str);
706 self.dump_output_file(&script_str, "debugger.script");
707 let debugger_script = self.make_out_name("debugger.script");
709 let cdb_path = &self.config.cdb.as_ref().unwrap();
710 let mut cdb = Command::new(cdb_path);
711 cdb.arg("-lines") // Enable source line debugging.
713 .arg(&debugger_script)
716 let debugger_run_result = self.compose_and_run(
718 self.config.run_lib_path.to_str().unwrap(),
723 if !debugger_run_result.status.success() {
724 self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
727 if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
728 self.fatal_proc_rec(&e, &debugger_run_result);
732 fn run_debuginfo_gdb_test(&self) {
733 assert!(self.revision.is_none(), "revisions not relevant here");
735 let config = Config {
736 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
737 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
738 ..self.config.clone()
741 let test_cx = TestCx { config: &config, ..*self };
743 test_cx.run_debuginfo_gdb_test_no_opt();
746 fn run_debuginfo_gdb_test_no_opt(&self) {
747 let prefixes = if self.config.gdb_native_rust {
749 static PREFIXES: &[&str] = &["gdb", "gdbr"];
750 println!("NOTE: compiletest thinks it is using GDB with native rust support");
754 static PREFIXES: &[&str] = &["gdb", "gdbg"];
755 println!("NOTE: compiletest thinks it is using GDB without native rust support");
759 let DebuggerCommands { commands, check_lines, breakpoint_lines } =
760 match DebuggerCommands::parse_from(&self.testpaths.file, self.config, prefixes) {
762 Err(e) => self.fatal(&e),
764 let mut cmds = commands.join("\n");
766 // compile test file (it should have 'compile-flags:-g' in the header)
767 let should_run = self.run_if_enabled();
768 let compiler_run_result = self.compile_test(should_run, EmitMetadata::No);
769 if !compiler_run_result.status.success() {
770 self.fatal_proc_rec("compilation failed!", &compiler_run_result);
772 if let WillExecute::Disabled = should_run {
776 let exe_file = self.make_exe_name();
778 let debugger_run_result;
779 if is_android_gdb_target(&self.config.target) {
780 cmds = cmds.replace("run", "continue");
782 let tool_path = match self.config.android_cross_path.to_str() {
783 Some(x) => x.to_owned(),
784 None => self.fatal("cannot find android cross path"),
787 // write debugger script
788 let mut script_str = String::with_capacity(2048);
789 script_str.push_str(&format!("set charset {}\n", Self::charset()));
790 script_str.push_str(&format!("set sysroot {}\n", tool_path));
791 script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
792 script_str.push_str("target remote :5039\n");
793 script_str.push_str(&format!(
794 "set solib-search-path \
795 ./{}/stage2/lib/rustlib/{}/lib/\n",
796 self.config.host, self.config.target
798 for line in &breakpoint_lines {
802 self.testpaths.file.file_name().unwrap().to_string_lossy(),
807 script_str.push_str(&cmds);
808 script_str.push_str("\nquit\n");
810 debug!("script_str = {}", script_str);
811 self.dump_output_file(&script_str, "debugger.script");
813 let adb_path = &self.config.adb_path;
815 Command::new(adb_path)
818 .arg(&self.config.adb_test_dir)
820 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
822 Command::new(adb_path)
823 .args(&["forward", "tcp:5039", "tcp:5039"])
825 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
827 let adb_arg = format!(
828 "export LD_LIBRARY_PATH={}; \
829 gdbserver{} :5039 {}/{}",
830 self.config.adb_test_dir.clone(),
831 if self.config.target.contains("aarch64") { "64" } else { "" },
832 self.config.adb_test_dir.clone(),
833 exe_file.file_name().unwrap().to_str().unwrap()
836 debug!("adb arg: {}", adb_arg);
837 let mut adb = Command::new(adb_path)
838 .args(&["shell", &adb_arg])
839 .stdout(Stdio::piped())
840 .stderr(Stdio::inherit())
842 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
844 // Wait for the gdbserver to print out "Listening on port ..."
845 // at which point we know that it's started and then we can
846 // execute the debugger below.
847 let mut stdout = BufReader::new(adb.stdout.take().unwrap());
848 let mut line = String::new();
851 stdout.read_line(&mut line).unwrap();
852 if line.starts_with("Listening on port 5039") {
858 let mut debugger_script = OsString::from("-command=");
859 debugger_script.push(self.make_out_name("debugger.script"));
860 let debugger_opts: &[&OsStr] =
861 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
863 let gdb_path = self.config.gdb.as_ref().unwrap();
864 let Output { status, stdout, stderr } = Command::new(&gdb_path)
867 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", gdb_path));
869 let mut gdb = Command::new(&format!("{}-gdb", self.config.target));
870 gdb.args(debugger_opts);
871 let cmdline = self.make_cmdline(&gdb, "");
872 logv(self.config, format!("executing {}", cmdline));
876 debugger_run_result = ProcRes {
878 stdout: String::from_utf8(stdout).unwrap(),
879 stderr: String::from_utf8(stderr).unwrap(),
882 if adb.kill().is_err() {
883 println!("Adb process is already finished.");
887 self.config.find_rust_src_root().expect("Could not find Rust source root");
888 let rust_pp_module_rel_path = Path::new("./src/etc");
889 let rust_pp_module_abs_path =
890 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
891 // write debugger script
892 let mut script_str = String::with_capacity(2048);
893 script_str.push_str(&format!("set charset {}\n", Self::charset()));
894 script_str.push_str("show version\n");
896 match self.config.gdb_version {
898 println!("NOTE: compiletest thinks it is using GDB version {}", version);
900 if version > extract_gdb_version("7.4").unwrap() {
901 // Add the directory containing the pretty printers to
902 // GDB's script auto loading safe path
903 script_str.push_str(&format!(
904 "add-auto-load-safe-path {}\n",
905 rust_pp_module_abs_path.replace(r"\", r"\\")
911 "NOTE: compiletest does not know which version of \
917 // The following line actually doesn't have to do anything with
918 // pretty printing, it just tells GDB to print values on one line:
919 script_str.push_str("set print pretty off\n");
921 // Add the pretty printer directory to GDB's source-file search path
923 .push_str(&format!("directory {}\n", rust_pp_module_abs_path.replace(r"\", r"\\")));
925 // Load the target executable
927 .push_str(&format!("file {}\n", exe_file.to_str().unwrap().replace(r"\", r"\\")));
929 // Force GDB to print values in the Rust format.
930 if self.config.gdb_native_rust {
931 script_str.push_str("set language rust\n");
934 // Add line breakpoints
935 for line in &breakpoint_lines {
936 script_str.push_str(&format!(
938 self.testpaths.file.file_name().unwrap().to_string_lossy(),
943 script_str.push_str(&cmds);
944 script_str.push_str("\nquit\n");
946 debug!("script_str = {}", script_str);
947 self.dump_output_file(&script_str, "debugger.script");
949 let mut debugger_script = OsString::from("-command=");
950 debugger_script.push(self.make_out_name("debugger.script"));
952 let debugger_opts: &[&OsStr] =
953 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
955 let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
956 gdb.args(debugger_opts).env("PYTHONPATH", rust_pp_module_abs_path);
958 debugger_run_result =
959 self.compose_and_run(gdb, self.config.run_lib_path.to_str().unwrap(), None, None);
962 if !debugger_run_result.status.success() {
963 self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
966 if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
967 self.fatal_proc_rec(&e, &debugger_run_result);
971 fn run_debuginfo_lldb_test(&self) {
972 assert!(self.revision.is_none(), "revisions not relevant here");
974 if self.config.lldb_python_dir.is_none() {
975 self.fatal("Can't run LLDB test because LLDB's python path is not set.");
978 let config = Config {
979 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
980 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
981 ..self.config.clone()
984 let test_cx = TestCx { config: &config, ..*self };
986 test_cx.run_debuginfo_lldb_test_no_opt();
989 fn run_debuginfo_lldb_test_no_opt(&self) {
990 // compile test file (it should have 'compile-flags:-g' in the header)
991 let should_run = self.run_if_enabled();
992 let compile_result = self.compile_test(should_run, EmitMetadata::No);
993 if !compile_result.status.success() {
994 self.fatal_proc_rec("compilation failed!", &compile_result);
996 if let WillExecute::Disabled = should_run {
1000 let exe_file = self.make_exe_name();
1002 match self.config.lldb_version {
1003 Some(ref version) => {
1004 println!("NOTE: compiletest thinks it is using LLDB version {}", version);
1008 "NOTE: compiletest does not know which version of \
1014 let prefixes = if self.config.lldb_native_rust {
1015 static PREFIXES: &[&str] = &["lldb", "lldbr"];
1016 println!("NOTE: compiletest thinks it is using LLDB with native rust support");
1019 static PREFIXES: &[&str] = &["lldb", "lldbg"];
1020 println!("NOTE: compiletest thinks it is using LLDB without native rust support");
1024 // Parse debugger commands etc from test files
1025 let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
1026 match DebuggerCommands::parse_from(&self.testpaths.file, self.config, prefixes) {
1028 Err(e) => self.fatal(&e),
1031 // Write debugger script:
1032 // We don't want to hang when calling `quit` while the process is still running
1033 let mut script_str = String::from("settings set auto-confirm true\n");
1035 // Make LLDB emit its version, so we have it documented in the test output
1036 script_str.push_str("version\n");
1038 // Switch LLDB into "Rust mode"
1040 self.config.find_rust_src_root().expect("Could not find Rust source root");
1041 let rust_pp_module_rel_path = Path::new("./src/etc/lldb_lookup.py");
1042 let rust_pp_module_abs_path =
1043 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
1045 let rust_type_regexes = vec![
1046 "^(alloc::([a-z_]+::)+)String$",
1048 "^&(mut )?\\[.+\\]$",
1049 "^(std::ffi::([a-z_]+::)+)OsString$",
1050 "^(alloc::([a-z_]+::)+)Vec<.+>$",
1051 "^(alloc::([a-z_]+::)+)VecDeque<.+>$",
1052 "^(alloc::([a-z_]+::)+)BTreeSet<.+>$",
1053 "^(alloc::([a-z_]+::)+)BTreeMap<.+>$",
1054 "^(std::collections::([a-z_]+::)+)HashMap<.+>$",
1055 "^(std::collections::([a-z_]+::)+)HashSet<.+>$",
1056 "^(alloc::([a-z_]+::)+)Rc<.+>$",
1057 "^(alloc::([a-z_]+::)+)Arc<.+>$",
1058 "^(core::([a-z_]+::)+)Cell<.+>$",
1059 "^(core::([a-z_]+::)+)Ref<.+>$",
1060 "^(core::([a-z_]+::)+)RefMut<.+>$",
1061 "^(core::([a-z_]+::)+)RefCell<.+>$",
1065 .push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[..])[..]);
1066 script_str.push_str("type synthetic add -l lldb_lookup.synthetic_lookup -x '.*' ");
1067 script_str.push_str("--category Rust\n");
1068 for type_regex in rust_type_regexes {
1069 script_str.push_str("type summary add -F lldb_lookup.summary_lookup -e -x -h ");
1070 script_str.push_str(&format!("'{}' ", type_regex));
1071 script_str.push_str("--category Rust\n");
1073 script_str.push_str("type category enable Rust\n");
1075 // Set breakpoints on every line that contains the string "#break"
1076 let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
1077 for line in &breakpoint_lines {
1078 script_str.push_str(&format!(
1079 "breakpoint set --file '{}' --line {}\n",
1080 source_file_name, line
1084 // Append the other commands
1085 for line in &commands {
1086 script_str.push_str(line);
1087 script_str.push_str("\n");
1090 // Finally, quit the debugger
1091 script_str.push_str("\nquit\n");
1093 // Write the script into a file
1094 debug!("script_str = {}", script_str);
1095 self.dump_output_file(&script_str, "debugger.script");
1096 let debugger_script = self.make_out_name("debugger.script");
1098 // Let LLDB execute the script via lldb_batchmode.py
1099 let debugger_run_result = self.run_lldb(&exe_file, &debugger_script, &rust_src_root);
1101 if !debugger_run_result.status.success() {
1102 self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
1105 if let Err(e) = check_debugger_output(&debugger_run_result, &check_lines) {
1106 self.fatal_proc_rec(&e, &debugger_run_result);
1112 test_executable: &Path,
1113 debugger_script: &Path,
1114 rust_src_root: &Path,
1116 // Prepare the lldb_batchmode which executes the debugger script
1117 let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
1119 Command::new(&self.config.lldb_python)
1120 .arg(&lldb_script_path)
1121 .arg(test_executable)
1122 .arg(debugger_script)
1123 .env("PYTHONUNBUFFERED", "1") // Help debugging #78665
1124 .env("PYTHONPATH", self.config.lldb_python_dir.as_ref().unwrap()),
1128 fn cmd2procres(&self, cmd: &mut Command) -> ProcRes {
1129 let (status, out, err) = match cmd.output() {
1130 Ok(Output { status, stdout, stderr }) => {
1131 (status, String::from_utf8(stdout).unwrap(), String::from_utf8(stderr).unwrap())
1133 Err(e) => self.fatal(&format!(
1134 "Failed to setup Python process for \
1140 self.dump_output(&out, &err);
1141 ProcRes { status, stdout: out, stderr: err, cmdline: format!("{:?}", cmd) }
1144 fn cleanup_debug_info_options(&self, options: &Option<String>) -> Option<String> {
1145 if options.is_none() {
1149 // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
1150 let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
1151 let new_options = self
1152 .split_maybe_args(options)
1154 .filter(|x| !options_to_remove.contains(x))
1155 .collect::<Vec<String>>();
1157 Some(new_options.join(" "))
1160 fn maybe_add_external_args(&self, cmd: &mut Command, args: Vec<String>) {
1161 // Filter out the arguments that should not be added by runtest here.
1163 // Notable use-cases are: do not add our optimisation flag if
1164 // `compile-flags: -Copt-level=x` and similar for debug-info level as well.
1165 const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", /*-C<space>*/ "opt-level="];
1166 const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", /*-C<space>*/ "debuginfo="];
1168 // FIXME: ideally we would "just" check the `cmd` itself, but it does not allow inspecting
1169 // its arguments. They need to be collected separately. For now I cannot be bothered to
1170 // implement this the "right" way.
1172 self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
1173 let have_debug_flag = self
1177 .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
1180 if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
1183 if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
1190 fn check_error_patterns(
1192 output_to_check: &str,
1194 pm: Option<PassMode>,
1196 debug!("check_error_patterns");
1197 if self.props.error_patterns.is_empty() {
1202 self.fatal(&format!(
1203 "no error pattern specified in {:?}",
1204 self.testpaths.file.display()
1209 let mut missing_patterns: Vec<String> = Vec::new();
1211 for pattern in &self.props.error_patterns {
1212 if output_to_check.contains(pattern.trim()) {
1213 debug!("found error pattern {}", pattern);
1215 missing_patterns.push(pattern.to_string());
1219 if missing_patterns.is_empty() {
1223 if missing_patterns.len() == 1 {
1224 self.fatal_proc_rec(
1225 &format!("error pattern '{}' not found!", missing_patterns[0]),
1229 for pattern in missing_patterns {
1230 self.error(&format!("error pattern '{}' not found!", pattern));
1232 self.fatal_proc_rec("multiple error patterns not found", proc_res);
1236 fn check_no_compiler_crash(&self, proc_res: &ProcRes, should_ice: bool) {
1237 match proc_res.status.code() {
1238 Some(101) if !should_ice => {
1239 self.fatal_proc_rec("compiler encountered internal error", proc_res)
1241 None => self.fatal_proc_rec("compiler terminated by signal", proc_res),
1246 fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
1247 for pat in &self.props.forbid_output {
1248 if output_to_check.contains(pat) {
1249 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
1254 fn check_expected_errors(&self, expected_errors: Vec<errors::Error>, proc_res: &ProcRes) {
1256 "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
1257 expected_errors, proc_res.status
1259 if proc_res.status.success()
1260 && expected_errors.iter().any(|x| x.kind == Some(ErrorKind::Error))
1262 self.fatal_proc_rec("process did not return an error status", proc_res);
1265 // On Windows, keep all '\' path separators to match the paths reported in the JSON output
1266 // from the compiler
1267 let os_file_name = self.testpaths.file.display().to_string();
1269 // on windows, translate all '\' path separators to '/'
1270 let file_name = format!("{}", self.testpaths.file.display()).replace(r"\", "/");
1272 // If the testcase being checked contains at least one expected "help"
1273 // message, then we'll ensure that all "help" messages are expected.
1274 // Otherwise, all "help" messages reported by the compiler will be ignored.
1275 // This logic also applies to "note" messages.
1276 let expect_help = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Help));
1277 let expect_note = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Note));
1279 // Parse the JSON output from the compiler and extract out the messages.
1280 let actual_errors = json::parse_output(&os_file_name, &proc_res.stderr, proc_res);
1281 let mut unexpected = Vec::new();
1282 let mut found = vec![false; expected_errors.len()];
1283 for actual_error in &actual_errors {
1285 expected_errors.iter().enumerate().position(|(index, expected_error)| {
1287 && actual_error.line_num == expected_error.line_num
1288 && (expected_error.kind.is_none()
1289 || actual_error.kind == expected_error.kind)
1290 && actual_error.msg.contains(&expected_error.msg)
1295 // found a match, everybody is happy
1296 assert!(!found[index]);
1297 found[index] = true;
1301 if self.is_unexpected_compiler_message(actual_error, expect_help, expect_note) {
1302 self.error(&format!(
1303 "{}:{}: unexpected {}: '{}'",
1305 actual_error.line_num,
1309 .map_or(String::from("message"), |k| k.to_string()),
1312 unexpected.push(actual_error);
1318 let mut not_found = Vec::new();
1319 // anything not yet found is a problem
1320 for (index, expected_error) in expected_errors.iter().enumerate() {
1322 self.error(&format!(
1323 "{}:{}: expected {} not found: {}",
1325 expected_error.line_num,
1326 expected_error.kind.as_ref().map_or("message".into(), |k| k.to_string()),
1329 not_found.push(expected_error);
1333 if !unexpected.is_empty() || !not_found.is_empty() {
1334 self.error(&format!(
1335 "{} unexpected errors found, {} expected errors not found",
1339 println!("status: {}\ncommand: {}", proc_res.status, proc_res.cmdline);
1340 if !unexpected.is_empty() {
1341 println!("unexpected errors (from JSON output): {:#?}\n", unexpected);
1343 if !not_found.is_empty() {
1344 println!("not found errors (from test file): {:#?}\n", not_found);
1350 /// Returns `true` if we should report an error about `actual_error`,
1351 /// which did not match any of the expected error. We always require
1352 /// errors/warnings to be explicitly listed, but only require
1353 /// helps/notes if there are explicit helps/notes given.
1354 fn is_unexpected_compiler_message(
1356 actual_error: &Error,
1360 match actual_error.kind {
1361 Some(ErrorKind::Help) => expect_help,
1362 Some(ErrorKind::Note) => expect_note,
1363 Some(ErrorKind::Error) | Some(ErrorKind::Warning) => true,
1364 Some(ErrorKind::Suggestion) | None => false,
1368 fn should_emit_metadata(&self, pm: Option<PassMode>) -> EmitMetadata {
1369 match (pm, self.props.fail_mode, self.config.mode) {
1370 (Some(PassMode::Check), ..) | (_, Some(FailMode::Check), Ui) => EmitMetadata::Yes,
1371 _ => EmitMetadata::No,
1375 fn compile_test(&self, will_execute: WillExecute, emit_metadata: EmitMetadata) -> ProcRes {
1376 self.compile_test_general(will_execute, emit_metadata, self.props.local_pass_mode())
1379 fn compile_test_general(
1381 will_execute: WillExecute,
1382 emit_metadata: EmitMetadata,
1383 local_pm: Option<PassMode>,
1385 // Only use `make_exe_name` when the test ends up being executed.
1386 let output_file = match will_execute {
1387 WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
1388 WillExecute::No | WillExecute::Disabled => {
1389 TargetLocation::ThisDirectory(self.output_base_dir())
1393 let allow_unused = match self.config.mode {
1395 // UI tests tend to have tons of unused code as
1396 // it's just testing various pieces of the compile, but we don't
1397 // want to actually assert warnings about all this code. Instead
1398 // let's just ignore unused code warnings by defaults and tests
1399 // can turn it back on if needed.
1400 if !self.is_rustdoc()
1401 // Note that we use the local pass mode here as we don't want
1402 // to set unused to allow if we've overridden the pass mode
1403 // via command line flags.
1404 && local_pm != Some(PassMode::Run)
1411 _ => AllowUnused::No,
1415 self.make_compile_args(&self.testpaths.file, output_file, emit_metadata, allow_unused);
1417 rustc.arg("-L").arg(&self.aux_output_dir_name());
1419 self.compose_and_run_compiler(rustc, None)
1422 fn document(&self, out_dir: &Path) -> ProcRes {
1423 if self.props.build_aux_docs {
1424 for rel_ab in &self.props.aux_builds {
1425 let aux_testpaths = self.compute_aux_test_paths(rel_ab);
1427 self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1428 let aux_cx = TestCx {
1429 config: self.config,
1431 testpaths: &aux_testpaths,
1432 revision: self.revision,
1434 // Create the directory for the stdout/stderr files.
1435 create_dir_all(aux_cx.output_base_dir()).unwrap();
1436 let auxres = aux_cx.document(out_dir);
1437 if !auxres.status.success() {
1443 let aux_dir = self.aux_output_dir_name();
1445 let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path not passed");
1446 let mut rustdoc = Command::new(rustdoc_path);
1450 .arg(self.config.run_lib_path.to_str().unwrap())
1457 .arg(&self.testpaths.file)
1458 .args(&self.props.compile_flags);
1460 if self.config.mode == RustdocJson {
1461 rustdoc.arg("--output-format").arg("json").arg("-Zunstable-options");
1464 if let Some(ref linker) = self.config.linker {
1465 rustdoc.arg(format!("-Clinker={}", linker));
1468 self.compose_and_run_compiler(rustdoc, None)
1471 fn exec_compiled_test(&self) -> ProcRes {
1472 let env = &self.props.exec_env;
1474 let proc_res = match &*self.config.target {
1475 // This is pretty similar to below, we're transforming:
1477 // program arg1 arg2
1481 // remote-test-client run program 2 support-lib.so support-lib2.so arg1 arg2
1483 // The test-client program will upload `program` to the emulator
1484 // along with all other support libraries listed (in this case
1485 // `support-lib.so` and `support-lib2.so`. It will then execute
1486 // the program on the emulator with the arguments specified
1487 // (in the environment we give the process) and then report back
1489 _ if self.config.remote_test_client.is_some() => {
1490 let aux_dir = self.aux_output_dir_name();
1491 let ProcArgs { prog, args } = self.make_run_args();
1492 let mut support_libs = Vec::new();
1493 if let Ok(entries) = aux_dir.read_dir() {
1494 for entry in entries {
1495 let entry = entry.unwrap();
1496 if !entry.path().is_file() {
1499 support_libs.push(entry.path());
1502 let mut test_client =
1503 Command::new(self.config.remote_test_client.as_ref().unwrap());
1505 .args(&["run", &support_libs.len().to_string(), &prog])
1509 self.compose_and_run(
1511 self.config.run_lib_path.to_str().unwrap(),
1512 Some(aux_dir.to_str().unwrap()),
1516 _ if self.config.target.contains("vxworks") => {
1517 let aux_dir = self.aux_output_dir_name();
1518 let ProcArgs { prog, args } = self.make_run_args();
1519 let mut wr_run = Command::new("wr-run");
1520 wr_run.args(&[&prog]).args(args).envs(env.clone());
1521 self.compose_and_run(
1523 self.config.run_lib_path.to_str().unwrap(),
1524 Some(aux_dir.to_str().unwrap()),
1529 let aux_dir = self.aux_output_dir_name();
1530 let ProcArgs { prog, args } = self.make_run_args();
1531 let mut program = Command::new(&prog);
1532 program.args(args).current_dir(&self.output_base_dir()).envs(env.clone());
1533 self.compose_and_run(
1535 self.config.run_lib_path.to_str().unwrap(),
1536 Some(aux_dir.to_str().unwrap()),
1542 if proc_res.status.success() {
1543 // delete the executable after running it to save space.
1544 // it is ok if the deletion failed.
1545 let _ = fs::remove_file(self.make_exe_name());
1551 /// For each `aux-build: foo/bar` annotation, we check to find the
1552 /// file in an `auxiliary` directory relative to the test itself.
1553 fn compute_aux_test_paths(&self, rel_ab: &str) -> TestPaths {
1558 .expect("test file path has no parent")
1561 if !test_ab.exists() {
1562 self.fatal(&format!("aux-build `{}` source not found", test_ab.display()))
1570 .join(self.output_testname_unique())
1574 .expect("aux-build path has no parent")
1579 fn is_vxworks_pure_static(&self) -> bool {
1580 if self.config.target.contains("vxworks") {
1581 match env::var("RUST_VXWORKS_TEST_DYLINK") {
1590 fn is_vxworks_pure_dynamic(&self) -> bool {
1591 self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1594 fn build_all_auxiliary(&self, rustc: &mut Command) -> PathBuf {
1595 let aux_dir = self.aux_output_dir_name();
1597 if !self.props.aux_builds.is_empty() {
1598 let _ = fs::remove_dir_all(&aux_dir);
1599 create_dir_all(&aux_dir).unwrap();
1602 for rel_ab in &self.props.aux_builds {
1603 self.build_auxiliary(rel_ab, &aux_dir);
1606 for (aux_name, aux_path) in &self.props.aux_crates {
1607 let is_dylib = self.build_auxiliary(&aux_path, &aux_dir);
1609 get_lib_name(&aux_path.trim_end_matches(".rs").replace('-', "_"), is_dylib);
1610 rustc.arg("--extern").arg(format!("{}={}/{}", aux_name, aux_dir.display(), lib_name));
1616 fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1617 let aux_dir = self.build_all_auxiliary(&mut rustc);
1618 self.props.unset_rustc_env.clone().iter().fold(&mut rustc, |rustc, v| rustc.env_remove(v));
1619 rustc.envs(self.props.rustc_env.clone());
1620 self.compose_and_run(
1622 self.config.compile_lib_path.to_str().unwrap(),
1623 Some(aux_dir.to_str().unwrap()),
1628 /// Builds an aux dependency.
1630 /// Returns whether or not it is a dylib.
1631 fn build_auxiliary(&self, source_path: &str, aux_dir: &Path) -> bool {
1632 let aux_testpaths = self.compute_aux_test_paths(source_path);
1633 let aux_props = self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1634 let aux_output = TargetLocation::ThisDirectory(self.aux_output_dir_name());
1635 let aux_cx = TestCx {
1636 config: self.config,
1638 testpaths: &aux_testpaths,
1639 revision: self.revision,
1641 // Create the directory for the stdout/stderr files.
1642 create_dir_all(aux_cx.output_base_dir()).unwrap();
1643 let input_file = &aux_testpaths.file;
1645 aux_cx.make_compile_args(input_file, aux_output, EmitMetadata::No, AllowUnused::No);
1647 for key in &aux_props.unset_rustc_env {
1648 aux_rustc.env_remove(key);
1650 aux_rustc.envs(aux_props.rustc_env.clone());
1652 let (dylib, crate_type) = if aux_props.no_prefer_dynamic {
1654 } else if self.config.target.contains("emscripten")
1655 || (self.config.target.contains("musl")
1656 && !aux_props.force_host
1657 && !self.config.host.contains("musl"))
1658 || self.config.target.contains("wasm32")
1659 || self.config.target.contains("nvptx")
1660 || self.is_vxworks_pure_static()
1661 || self.config.target.contains("sgx")
1662 || self.config.target.contains("bpf")
1664 // We primarily compile all auxiliary libraries as dynamic libraries
1665 // to avoid code size bloat and large binaries as much as possible
1666 // for the test suite (otherwise including libstd statically in all
1667 // executables takes up quite a bit of space).
1669 // For targets like MUSL or Emscripten, however, there is no support for
1670 // dynamic libraries so we just go back to building a normal library. Note,
1671 // however, that for MUSL if the library is built with `force_host` then
1672 // it's ok to be a dylib as the host should always support dylibs.
1673 (false, Some("lib"))
1675 (true, Some("dylib"))
1678 if let Some(crate_type) = crate_type {
1679 aux_rustc.args(&["--crate-type", crate_type]);
1682 aux_rustc.arg("-L").arg(&aux_dir);
1684 let auxres = aux_cx.compose_and_run(
1686 aux_cx.config.compile_lib_path.to_str().unwrap(),
1687 Some(aux_dir.to_str().unwrap()),
1690 if !auxres.status.success() {
1691 self.fatal_proc_rec(
1693 "auxiliary build of {:?} failed to compile: ",
1694 aux_testpaths.file.display()
1704 mut command: Command,
1706 aux_path: Option<&str>,
1707 input: Option<String>,
1710 let cmdline = self.make_cmdline(&command, lib_path);
1711 logv(self.config, format!("executing {}", cmdline));
1715 command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
1717 // Need to be sure to put both the lib_path and the aux path in the dylib
1718 // search path for the child.
1720 env::split_paths(&env::var_os(dylib_env_var()).unwrap_or_default()).collect::<Vec<_>>();
1721 if let Some(p) = aux_path {
1722 path.insert(0, PathBuf::from(p))
1724 path.insert(0, PathBuf::from(lib_path));
1726 // Add the new dylib search path var
1727 let newpath = env::join_paths(&path).unwrap();
1728 command.env(dylib_env_var(), newpath);
1730 let mut child = disable_error_reporting(|| command.spawn())
1731 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", &command));
1732 if let Some(input) = input {
1733 child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
1736 let Output { status, stdout, stderr } =
1737 read2_abbreviated(child).expect("failed to read output");
1739 let result = ProcRes {
1741 stdout: String::from_utf8_lossy(&stdout).into_owned(),
1742 stderr: String::from_utf8_lossy(&stderr).into_owned(),
1746 self.dump_output(&result.stdout, &result.stderr);
1751 fn is_rustdoc(&self) -> bool {
1752 self.config.src_base.ends_with("rustdoc-ui")
1753 || self.config.src_base.ends_with("rustdoc-js")
1754 || self.config.src_base.ends_with("rustdoc-json")
1757 fn make_compile_args(
1760 output_file: TargetLocation,
1761 emit_metadata: EmitMetadata,
1762 allow_unused: AllowUnused,
1764 let is_aux = input_file.components().map(|c| c.as_os_str()).any(|c| c == "auxiliary");
1765 let is_rustdoc = self.is_rustdoc() && !is_aux;
1766 let mut rustc = if !is_rustdoc {
1767 Command::new(&self.config.rustc_path)
1769 Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1771 rustc.arg(input_file);
1773 // Use a single thread for efficiency and a deterministic error message order
1774 rustc.arg("-Zthreads=1");
1776 // Optionally prevent default --target if specified in test compile-flags.
1777 let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target"));
1781 if self.props.force_host { &*self.config.host } else { &*self.config.target };
1783 rustc.arg(&format!("--target={}", target));
1785 self.set_revision_flags(&mut rustc);
1788 if let Some(ref incremental_dir) = self.props.incremental_dir {
1789 rustc.args(&["-C", &format!("incremental={}", incremental_dir.display())]);
1790 rustc.args(&["-Z", "incremental-verify-ich"]);
1793 if self.config.mode == CodegenUnits {
1794 rustc.args(&["-Z", "human_readable_cgu_names"]);
1798 match self.config.mode {
1800 // If we are extracting and matching errors in the new
1801 // fashion, then you want JSON mode. Old-skool error
1802 // patterns still match the raw compiler output.
1803 if self.props.error_patterns.is_empty() {
1804 rustc.args(&["--error-format", "json"]);
1806 rustc.arg("-Zui-testing");
1807 rustc.arg("-Zdeduplicate-diagnostics=no");
1810 if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) {
1811 rustc.args(&["--error-format", "json"]);
1813 rustc.arg("-Ccodegen-units=1");
1814 rustc.arg("-Zui-testing");
1815 rustc.arg("-Zdeduplicate-diagnostics=no");
1816 rustc.arg("-Zemit-future-incompat-report");
1822 "-Zmir-opt-level=4",
1824 "-Zdump-mir-exclude-pass-number",
1827 let mir_dump_dir = self.get_mir_dump_dir();
1828 let _ = fs::remove_dir_all(&mir_dump_dir);
1829 create_dir_all(mir_dump_dir.as_path()).unwrap();
1830 let mut dir_opt = "-Zdump-mir-dir=".to_string();
1831 dir_opt.push_str(mir_dump_dir.to_str().unwrap());
1832 debug!("dir_opt: {:?}", dir_opt);
1836 RunPassValgrind | Pretty | DebugInfo | Codegen | Rustdoc | RustdocJson | RunMake
1837 | CodegenUnits | JsDocTest | Assembly => {
1838 // do not use JSON output
1842 if let (false, EmitMetadata::Yes) = (is_rustdoc, emit_metadata) {
1843 rustc.args(&["--emit", "metadata"]);
1847 if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() {
1848 // rustc.arg("-g"); // get any backtrace at all on errors
1849 } else if !self.props.no_prefer_dynamic {
1850 rustc.args(&["-C", "prefer-dynamic"]);
1855 TargetLocation::ThisFile(path) => {
1856 rustc.arg("-o").arg(path);
1858 TargetLocation::ThisDirectory(path) => {
1860 // `rustdoc` uses `-o` for the output directory.
1861 rustc.arg("-o").arg(path);
1863 rustc.arg("--out-dir").arg(path);
1868 match self.config.compare_mode {
1869 Some(CompareMode::Nll) => {
1870 rustc.args(&["-Zborrowck=mir"]);
1872 Some(CompareMode::Polonius) => {
1873 rustc.args(&["-Zpolonius", "-Zborrowck=mir"]);
1875 Some(CompareMode::Chalk) => {
1876 rustc.args(&["-Zchalk"]);
1878 Some(CompareMode::SplitDwarf) => {
1879 rustc.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]);
1881 Some(CompareMode::SplitDwarfSingle) => {
1882 rustc.args(&["-Csplit-debuginfo=packed", "-Zunstable-options"]);
1887 // Add `-A unused` before `config` flags and in-test (`props`) flags, so that they can
1889 if let AllowUnused::Yes = allow_unused {
1890 rustc.args(&["-A", "unused"]);
1893 if self.props.force_host {
1894 self.maybe_add_external_args(
1896 self.split_maybe_args(&self.config.host_rustcflags),
1899 self.maybe_add_external_args(
1901 self.split_maybe_args(&self.config.target_rustcflags),
1904 if let Some(ref linker) = self.config.linker {
1905 rustc.arg(format!("-Clinker={}", linker));
1910 // Use dynamic musl for tests because static doesn't allow creating dylibs
1911 if self.config.host.contains("musl") || self.is_vxworks_pure_dynamic() {
1912 rustc.arg("-Ctarget-feature=-crt-static");
1915 rustc.args(&self.props.compile_flags);
1920 fn make_exe_name(&self) -> PathBuf {
1921 // Using a single letter here to keep the path length down for
1922 // Windows. Some test names get very long. rustc creates `rcgu`
1923 // files with the module name appended to it which can more than
1924 // double the length.
1925 let mut f = self.output_base_dir().join("a");
1926 // FIXME: This is using the host architecture exe suffix, not target!
1927 if self.config.target.contains("emscripten") {
1928 f = f.with_extra_extension("js");
1929 } else if self.config.target.contains("wasm32") {
1930 f = f.with_extra_extension("wasm");
1931 } else if self.config.target.contains("spirv") {
1932 f = f.with_extra_extension("spv");
1933 } else if !env::consts::EXE_SUFFIX.is_empty() {
1934 f = f.with_extra_extension(env::consts::EXE_SUFFIX);
1939 fn make_run_args(&self) -> ProcArgs {
1940 // If we've got another tool to run under (valgrind),
1941 // then split apart its command
1942 let mut args = self.split_maybe_args(&self.config.runtool);
1944 // If this is emscripten, then run tests under nodejs
1945 if self.config.target.contains("emscripten") {
1946 if let Some(ref p) = self.config.nodejs {
1947 args.push(p.clone());
1949 self.fatal("no NodeJS binary found (--nodejs)");
1951 // If this is otherwise wasm, then run tests under nodejs with our
1953 } else if self.config.target.contains("wasm32") {
1954 if let Some(ref p) = self.config.nodejs {
1955 args.push(p.clone());
1957 self.fatal("no NodeJS binary found (--nodejs)");
1964 .unwrap() // chop off `ui`
1966 .unwrap() // chop off `test`
1968 .unwrap(); // chop off `src`
1969 args.push(src.join("src/etc/wasm32-shim.js").display().to_string());
1972 let exe_file = self.make_exe_name();
1974 // FIXME (#9639): This needs to handle non-utf8 paths
1975 args.push(exe_file.to_str().unwrap().to_owned());
1977 // Add the arguments in the run_flags directive
1978 args.extend(self.split_maybe_args(&self.props.run_flags));
1980 let prog = args.remove(0);
1981 ProcArgs { prog, args }
1984 fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<String> {
1989 if s.chars().all(|c| c.is_whitespace()) { None } else { Some(s.to_owned()) }
1996 fn make_cmdline(&self, command: &Command, libpath: &str) -> String {
1999 // Linux and mac don't require adjusting the library search path
2001 format!("{:?}", command)
2003 // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
2004 // for diagnostic purposes
2005 fn lib_path_cmd_prefix(path: &str) -> String {
2006 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
2009 format!("{} {:?}", lib_path_cmd_prefix(libpath), command)
2013 fn dump_output(&self, out: &str, err: &str) {
2014 let revision = if let Some(r) = self.revision { format!("{}.", r) } else { String::new() };
2016 self.dump_output_file(out, &format!("{}out", revision));
2017 self.dump_output_file(err, &format!("{}err", revision));
2018 self.maybe_dump_to_stdout(out, err);
2021 fn dump_output_file(&self, out: &str, extension: &str) {
2022 let outfile = self.make_out_name(extension);
2023 fs::write(&outfile, out).unwrap();
2026 /// Creates a filename for output with the given extension.
2027 /// E.g., `/.../testname.revision.mode/testname.extension`.
2028 fn make_out_name(&self, extension: &str) -> PathBuf {
2029 self.output_base_name().with_extension(extension)
2032 /// Gets the directory where auxiliary files are written.
2033 /// E.g., `/.../testname.revision.mode/auxiliary/`.
2034 fn aux_output_dir_name(&self) -> PathBuf {
2035 self.output_base_dir()
2037 .with_extra_extension(self.config.mode.disambiguator())
2040 /// Generates a unique name for the test, such as `testname.revision.mode`.
2041 fn output_testname_unique(&self) -> PathBuf {
2042 output_testname_unique(self.config, self.testpaths, self.safe_revision())
2045 /// The revision, ignored for incremental compilation since it wants all revisions in
2046 /// the same directory.
2047 fn safe_revision(&self) -> Option<&str> {
2048 if self.config.mode == Incremental { None } else { self.revision }
2051 /// Gets the absolute path to the directory where all output for the given
2052 /// test/revision should reside.
2053 /// E.g., `/path/to/build/host-triple/test/ui/relative/testname.revision.mode/`.
2054 fn output_base_dir(&self) -> PathBuf {
2055 output_base_dir(self.config, self.testpaths, self.safe_revision())
2058 /// Gets the absolute path to the base filename used as output for the given
2060 /// E.g., `/.../relative/testname.revision.mode/testname`.
2061 fn output_base_name(&self) -> PathBuf {
2062 output_base_name(self.config, self.testpaths, self.safe_revision())
2065 fn maybe_dump_to_stdout(&self, out: &str, err: &str) {
2066 if self.config.verbose {
2067 println!("------stdout------------------------------");
2068 println!("{}", out);
2069 println!("------stderr------------------------------");
2070 println!("{}", err);
2071 println!("------------------------------------------");
2075 fn error(&self, err: &str) {
2076 match self.revision {
2077 Some(rev) => println!("\nerror in revision `{}`: {}", rev, err),
2078 None => println!("\nerror: {}", err),
2082 fn fatal(&self, err: &str) -> ! {
2084 error!("fatal error, panic: {:?}", err);
2085 panic!("fatal error");
2088 fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2090 proc_res.fatal(None, || ());
2093 fn fatal_proc_rec_with_ctx(
2097 on_failure: impl FnOnce(Self),
2100 proc_res.fatal(None, || on_failure(*self));
2103 // codegen tests (using FileCheck)
2105 fn compile_test_and_save_ir(&self) -> ProcRes {
2106 let aux_dir = self.aux_output_dir_name();
2108 let output_file = TargetLocation::ThisDirectory(self.output_base_dir());
2109 let input_file = &self.testpaths.file;
2111 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2112 rustc.arg("-L").arg(aux_dir).arg("--emit=llvm-ir");
2114 self.compose_and_run_compiler(rustc, None)
2117 fn compile_test_and_save_assembly(&self) -> (ProcRes, PathBuf) {
2118 // This works with both `--emit asm` (as default output name for the assembly)
2119 // and `ptx-linker` because the latter can write output at requested location.
2120 let output_path = self.output_base_name().with_extension("s");
2122 let output_file = TargetLocation::ThisFile(output_path.clone());
2123 let input_file = &self.testpaths.file;
2125 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2127 rustc.arg("-L").arg(self.aux_output_dir_name());
2129 match self.props.assembly_output.as_ref().map(AsRef::as_ref) {
2130 Some("emit-asm") => {
2131 rustc.arg("--emit=asm");
2134 Some("ptx-linker") => {
2135 // No extra flags needed.
2138 Some(_) => self.fatal("unknown 'assembly-output' header"),
2139 None => self.fatal("missing 'assembly-output' header"),
2142 (self.compose_and_run_compiler(rustc, None), output_path)
2145 fn verify_with_filecheck(&self, output: &Path) -> ProcRes {
2146 let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2147 filecheck.arg("--input-file").arg(output).arg(&self.testpaths.file);
2148 // It would be more appropriate to make most of the arguments configurable through
2149 // a comment-attribute similar to `compile-flags`. For example, --check-prefixes is a very
2152 // For now, though…
2153 let prefix_for_target =
2154 if self.config.target.contains("msvc") { "MSVC" } else { "NONMSVC" };
2155 let prefixes = if let Some(rev) = self.revision {
2156 format!("CHECK,{},{}", prefix_for_target, rev)
2158 format!("CHECK,{}", prefix_for_target)
2160 if self.config.llvm_version.unwrap_or(0) >= 130000 {
2161 filecheck.args(&["--allow-unused-prefixes", "--check-prefixes", &prefixes]);
2163 filecheck.args(&["--check-prefixes", &prefixes]);
2165 self.compose_and_run(filecheck, "", None, None)
2168 fn run_codegen_test(&self) {
2169 if self.config.llvm_filecheck.is_none() {
2170 self.fatal("missing --llvm-filecheck");
2173 let proc_res = self.compile_test_and_save_ir();
2174 if !proc_res.status.success() {
2175 self.fatal_proc_rec("compilation failed!", &proc_res);
2178 let output_path = self.output_base_name().with_extension("ll");
2179 let proc_res = self.verify_with_filecheck(&output_path);
2180 if !proc_res.status.success() {
2181 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2185 fn run_assembly_test(&self) {
2186 if self.config.llvm_filecheck.is_none() {
2187 self.fatal("missing --llvm-filecheck");
2190 let (proc_res, output_path) = self.compile_test_and_save_assembly();
2191 if !proc_res.status.success() {
2192 self.fatal_proc_rec("compilation failed!", &proc_res);
2195 let proc_res = self.verify_with_filecheck(&output_path);
2196 if !proc_res.status.success() {
2197 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2201 fn charset() -> &'static str {
2202 // FreeBSD 10.1 defaults to GDB 6.1.1 which doesn't support "auto" charset
2203 if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" }
2206 fn run_rustdoc_test(&self) {
2207 assert!(self.revision.is_none(), "revisions not relevant here");
2209 let out_dir = self.output_base_dir();
2210 let _ = fs::remove_dir_all(&out_dir);
2211 create_dir_all(&out_dir).unwrap();
2213 let proc_res = self.document(&out_dir);
2214 if !proc_res.status.success() {
2215 self.fatal_proc_rec("rustdoc failed!", &proc_res);
2218 if self.props.check_test_line_numbers_match {
2219 self.check_rustdoc_test_option(proc_res);
2221 let root = self.config.find_rust_src_root().unwrap();
2222 let mut cmd = Command::new(&self.config.docck_python);
2223 cmd.arg(root.join("src/etc/htmldocck.py")).arg(&out_dir).arg(&self.testpaths.file);
2224 if self.config.bless {
2227 let res = self.cmd2procres(&mut cmd);
2228 if !res.status.success() {
2229 self.fatal_proc_rec_with_ctx("htmldocck failed!", &res, |mut this| {
2230 this.compare_to_default_rustdoc(&out_dir)
2236 fn compare_to_default_rustdoc(&mut self, out_dir: &Path) {
2237 if !self.config.has_tidy {
2240 println!("info: generating a diff against nightly rustdoc");
2243 self.safe_revision().map_or("nightly".into(), |path| path.to_owned() + "-nightly");
2244 let compare_dir = output_base_dir(self.config, self.testpaths, Some(&suffix));
2245 // Don't give an error if the directory didn't already exist
2246 let _ = fs::remove_dir_all(&compare_dir);
2247 create_dir_all(&compare_dir).unwrap();
2249 // We need to create a new struct for the lifetimes on `config` to work.
2250 let new_rustdoc = TestCx {
2252 // FIXME: use beta or a user-specified rustdoc instead of
2253 // hardcoding the default toolchain
2254 rustdoc_path: Some("rustdoc".into()),
2255 // Needed for building auxiliary docs below
2256 rustc_path: "rustc".into(),
2257 ..self.config.clone()
2262 let output_file = TargetLocation::ThisDirectory(new_rustdoc.aux_output_dir_name());
2263 let mut rustc = new_rustdoc.make_compile_args(
2264 &new_rustdoc.testpaths.file,
2269 rustc.arg("-L").arg(&new_rustdoc.aux_output_dir_name());
2270 new_rustdoc.build_all_auxiliary(&mut rustc);
2272 let proc_res = new_rustdoc.document(&compare_dir);
2273 if !proc_res.status.success() {
2274 eprintln!("failed to run nightly rustdoc");
2281 "--indent-spaces", "2",
2283 "--show-warnings", "no",
2288 let tidy_dir = |dir| {
2289 for entry in walkdir::WalkDir::new(dir) {
2290 let entry = entry.expect("failed to read file");
2291 if entry.file_type().is_file()
2292 && entry.path().extension().and_then(|p| p.to_str()) == Some("html".into())
2295 Command::new("tidy").args(&tidy_args).arg(entry.path()).status().unwrap();
2296 // `tidy` returns 1 if it modified the file.
2297 assert!(status.success() || status.code() == Some(1));
2302 tidy_dir(&compare_dir);
2305 let output = Command::new("git").args(&["config", "--get", "core.pager"]).output().ok();
2306 output.and_then(|out| {
2307 if out.status.success() {
2308 Some(String::from_utf8(out.stdout).expect("invalid UTF8 in git pager"))
2315 let diff_filename = format!("build/tmp/rustdoc-compare-{}.diff", std::process::id());
2317 if !write_filtered_diff(
2321 self.config.verbose,
2322 |file_type, extension| {
2324 && (extension == Some("html".into()) || extension == Some("js".into()))
2330 match self.config.color {
2331 ColorConfig::AlwaysColor => colored::control::set_override(true),
2332 ColorConfig::NeverColor => colored::control::set_override(false),
2336 if let Some(pager) = pager {
2337 let pager = pager.trim();
2338 if self.config.verbose {
2339 eprintln!("using pager {}", pager);
2341 let output = Command::new(pager)
2342 // disable paging; we want this to be non-interactive
2344 .stdin(File::open(&diff_filename).unwrap())
2345 // Capture output and print it explicitly so it will in turn be
2346 // captured by libtest.
2349 assert!(output.status.success());
2350 println!("{}", String::from_utf8_lossy(&output.stdout));
2351 eprintln!("{}", String::from_utf8_lossy(&output.stderr));
2353 use colored::Colorize;
2354 eprintln!("warning: no pager configured, falling back to unified diff");
2356 "help: try configuring a git pager (e.g. `delta`) with `git config --global core.pager delta`"
2358 let mut out = io::stdout();
2359 let mut diff = BufReader::new(File::open(&diff_filename).unwrap());
2360 let mut line = Vec::new();
2363 match diff.read_until(b'\n', &mut line) {
2366 Err(e) => eprintln!("ERROR: {:?}", e),
2368 match String::from_utf8(line.clone()) {
2370 if line.starts_with("+") {
2371 write!(&mut out, "{}", line.green()).unwrap();
2372 } else if line.starts_with("-") {
2373 write!(&mut out, "{}", line.red()).unwrap();
2374 } else if line.starts_with("@") {
2375 write!(&mut out, "{}", line.blue()).unwrap();
2377 out.write_all(line.as_bytes()).unwrap();
2381 write!(&mut out, "{}", String::from_utf8_lossy(&line).reversed()).unwrap();
2388 fn run_rustdoc_json_test(&self) {
2389 //FIXME: Add bless option.
2391 assert!(self.revision.is_none(), "revisions not relevant here");
2393 let out_dir = self.output_base_dir();
2394 let _ = fs::remove_dir_all(&out_dir);
2395 create_dir_all(&out_dir).unwrap();
2397 let proc_res = self.document(&out_dir);
2398 if !proc_res.status.success() {
2399 self.fatal_proc_rec("rustdoc failed!", &proc_res);
2402 let root = self.config.find_rust_src_root().unwrap();
2403 let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap());
2404 json_out.set_extension("json");
2405 let res = self.cmd2procres(
2406 Command::new(self.config.jsondocck_path.as_ref().unwrap())
2408 .arg(root.join(&out_dir))
2410 .arg(&self.testpaths.file),
2413 if !res.status.success() {
2414 self.fatal_proc_rec("jsondocck failed!", &res)
2417 let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap());
2418 json_out.set_extension("json");
2419 let res = self.cmd2procres(
2420 Command::new(&self.config.docck_python)
2421 .arg(root.join("src/etc/check_missing_items.py"))
2425 if !res.status.success() {
2426 self.fatal_proc_rec("check_missing_items failed!", &res);
2430 fn get_lines<P: AsRef<Path>>(
2433 mut other_files: Option<&mut Vec<String>>,
2435 let content = fs::read_to_string(&path).unwrap();
2436 let mut ignore = false;
2440 .filter_map(|(line_nb, line)| {
2441 if (line.trim_start().starts_with("pub mod ")
2442 || line.trim_start().starts_with("mod "))
2443 && line.ends_with(';')
2445 if let Some(ref mut other_files) = other_files {
2446 other_files.push(line.rsplit("mod ").next().unwrap().replace(";", ""));
2450 let sline = line.split("///").last().unwrap_or("");
2451 let line = sline.trim_start();
2452 if line.starts_with("```") {
2468 fn check_rustdoc_test_option(&self, res: ProcRes) {
2469 let mut other_files = Vec::new();
2470 let mut files: HashMap<String, Vec<usize>> = HashMap::new();
2471 let cwd = env::current_dir().unwrap();
2476 .unwrap_or(&self.testpaths.file)
2479 .replace('\\', "/"),
2480 self.get_lines(&self.testpaths.file, Some(&mut other_files)),
2482 for other_file in other_files {
2483 let mut path = self.testpaths.file.clone();
2484 path.set_file_name(&format!("{}.rs", other_file));
2486 path.strip_prefix(&cwd).unwrap_or(&path).to_str().unwrap().replace('\\', "/"),
2487 self.get_lines(&path, None),
2492 for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| {
2493 if let Some((left, right)) = s.split_once(" - ") {
2494 let path = left.rsplit("test ").next().unwrap();
2495 if let Some(ref mut v) = files.get_mut(&path.replace('\\', "/")) {
2497 let mut iter = right.split("(line ");
2507 if let Ok(pos) = v.binary_search(&line) {
2510 self.fatal_proc_rec(
2511 &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2519 self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2521 for (entry, v) in &files {
2523 self.fatal_proc_rec(
2525 "Not found test at line{} \"{}\":{:?}",
2526 if v.len() > 1 { "s" } else { "" },
2537 fn run_codegen_units_test(&self) {
2538 assert!(self.revision.is_none(), "revisions not relevant here");
2540 let proc_res = self.compile_test(WillExecute::No, EmitMetadata::No);
2542 if !proc_res.status.success() {
2543 self.fatal_proc_rec("compilation failed!", &proc_res);
2546 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
2548 const PREFIX: &str = "MONO_ITEM ";
2549 const CGU_MARKER: &str = "@@";
2551 let actual: Vec<MonoItem> = proc_res
2554 .filter(|line| line.starts_with(PREFIX))
2555 .map(|line| str_to_mono_item(line, true))
2558 let expected: Vec<MonoItem> = errors::load_errors(&self.testpaths.file, None)
2560 .map(|e| str_to_mono_item(&e.msg[..], false))
2563 let mut missing = Vec::new();
2564 let mut wrong_cgus = Vec::new();
2566 for expected_item in &expected {
2567 let actual_item_with_same_name = actual.iter().find(|ti| ti.name == expected_item.name);
2569 if let Some(actual_item) = actual_item_with_same_name {
2570 if !expected_item.codegen_units.is_empty() &&
2571 // Also check for codegen units
2572 expected_item.codegen_units != actual_item.codegen_units
2574 wrong_cgus.push((expected_item.clone(), actual_item.clone()));
2577 missing.push(expected_item.string.clone());
2581 let unexpected: Vec<_> = actual
2583 .filter(|acgu| !expected.iter().any(|ecgu| acgu.name == ecgu.name))
2584 .map(|acgu| acgu.string.clone())
2587 if !missing.is_empty() {
2590 println!("\nThese items should have been contained but were not:\n");
2592 for item in &missing {
2593 println!("{}", item);
2599 if !unexpected.is_empty() {
2601 let mut sorted = unexpected.clone();
2606 println!("\nThese items were contained but should not have been:\n");
2608 for item in sorted {
2609 println!("{}", item);
2615 if !wrong_cgus.is_empty() {
2616 wrong_cgus.sort_by_key(|pair| pair.0.name.clone());
2617 println!("\nThe following items were assigned to wrong codegen units:\n");
2619 for &(ref expected_item, ref actual_item) in &wrong_cgus {
2620 println!("{}", expected_item.name);
2621 println!(" expected: {}", codegen_units_to_str(&expected_item.codegen_units));
2622 println!(" actual: {}", codegen_units_to_str(&actual_item.codegen_units));
2627 if !(missing.is_empty() && unexpected.is_empty() && wrong_cgus.is_empty()) {
2631 #[derive(Clone, Eq, PartialEq)]
2634 codegen_units: HashSet<String>,
2638 // [MONO_ITEM] name [@@ (cgu)+]
2639 fn str_to_mono_item(s: &str, cgu_has_crate_disambiguator: bool) -> MonoItem {
2640 let s = if s.starts_with(PREFIX) { (&s[PREFIX.len()..]).trim() } else { s.trim() };
2642 let full_string = format!("{}{}", PREFIX, s);
2644 let parts: Vec<&str> =
2645 s.split(CGU_MARKER).map(str::trim).filter(|s| !s.is_empty()).collect();
2647 let name = parts[0].trim();
2649 let cgus = if parts.len() > 1 {
2650 let cgus_str = parts[1];
2655 .filter(|s| !s.is_empty())
2657 if cgu_has_crate_disambiguator {
2658 remove_crate_disambiguators_from_set_of_cgu_names(s)
2668 MonoItem { name: name.to_owned(), codegen_units: cgus, string: full_string }
2671 fn codegen_units_to_str(cgus: &HashSet<String>) -> String {
2672 let mut cgus: Vec<_> = cgus.iter().collect();
2675 let mut string = String::new();
2677 string.push_str(&cgu[..]);
2678 string.push_str(" ");
2684 // Given a cgu-name-prefix of the form <crate-name>.<crate-disambiguator> or
2685 // the form <crate-name1>.<crate-disambiguator1>-in-<crate-name2>.<crate-disambiguator2>,
2686 // remove all crate-disambiguators.
2687 fn remove_crate_disambiguator_from_cgu(cgu: &str) -> String {
2689 static ref RE: Regex =
2690 Regex::new(r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?")
2695 RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {}", cgu));
2697 let mut new_name = cgu.to_owned();
2699 if let Some(d2) = captures.name("d2") {
2700 new_name.replace_range(d2.start()..d2.end(), "");
2703 let d1 = captures.name("d1").unwrap();
2704 new_name.replace_range(d1.start()..d1.end(), "");
2709 // The name of merged CGUs is constructed as the names of the original
2710 // CGUs joined with "--". This function splits such composite CGU names
2711 // and handles each component individually.
2712 fn remove_crate_disambiguators_from_set_of_cgu_names(cgus: &str) -> String {
2714 .map(|cgu| remove_crate_disambiguator_from_cgu(cgu))
2715 .collect::<Vec<_>>()
2720 fn init_incremental_test(&self) {
2721 // (See `run_incremental_test` for an overview of how incremental tests work.)
2723 // Before any of the revisions have executed, create the
2724 // incremental workproduct directory. Delete any old
2725 // incremental work products that may be there from prior
2727 let incremental_dir = self.props.incremental_dir.as_ref().unwrap();
2728 if incremental_dir.exists() {
2729 // Canonicalizing the path will convert it to the //?/ format
2730 // on Windows, which enables paths longer than 260 character
2731 let canonicalized = incremental_dir.canonicalize().unwrap();
2732 fs::remove_dir_all(canonicalized).unwrap();
2734 fs::create_dir_all(&incremental_dir).unwrap();
2736 if self.config.verbose {
2737 println!("init_incremental_test: incremental_dir={}", incremental_dir.display());
2741 fn run_incremental_test(&self) {
2742 // Basic plan for a test incremental/foo/bar.rs:
2743 // - load list of revisions rpass1, cfail2, rpass3
2744 // - each should begin with `rpass`, `cfail`, or `rfail`
2745 // - if `rpass`, expect compile and execution to succeed
2746 // - if `cfail`, expect compilation to fail
2747 // - if `rfail`, expect execution to fail
2748 // - create a directory build/foo/bar.incremental
2749 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass1
2750 // - because name of revision starts with "rpass", expect success
2751 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C cfail2
2752 // - because name of revision starts with "cfail", expect an error
2753 // - load expected errors as usual, but filter for those that end in `[rfail2]`
2754 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass3
2755 // - because name of revision starts with "rpass", expect success
2756 // - execute build/foo/bar.exe and save output
2758 // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2759 // to #[rustc_dirty] and clean tests I guess
2761 let revision = self.revision.expect("incremental tests require a list of revisions");
2763 // Incremental workproduct directory should have already been created.
2764 let incremental_dir = self.props.incremental_dir.as_ref().unwrap();
2765 assert!(incremental_dir.exists(), "init_incremental_test failed to create incremental dir");
2767 if self.config.verbose {
2768 print!("revision={:?} props={:#?}", revision, self.props);
2771 if revision.starts_with("rpass") {
2772 if self.props.should_ice {
2773 self.fatal("can only use should-ice in cfail tests");
2775 self.run_rpass_test();
2776 } else if revision.starts_with("rfail") {
2777 if self.props.should_ice {
2778 self.fatal("can only use should-ice in cfail tests");
2780 self.run_rfail_test();
2781 } else if revision.starts_with("cfail") {
2782 self.run_cfail_test();
2784 self.fatal("revision name must begin with rpass, rfail, or cfail");
2788 fn run_rmake_test(&self) {
2789 let cwd = env::current_dir().unwrap();
2790 let src_root = self.config.src_base.parent().unwrap().parent().unwrap().parent().unwrap();
2791 let src_root = cwd.join(&src_root);
2793 let tmpdir = cwd.join(self.output_base_name());
2794 if tmpdir.exists() {
2795 self.aggressive_rm_rf(&tmpdir).unwrap();
2797 create_dir_all(&tmpdir).unwrap();
2799 let host = &self.config.host;
2800 let make = if host.contains("dragonfly")
2801 || host.contains("freebsd")
2802 || host.contains("netbsd")
2803 || host.contains("openbsd")
2810 let mut cmd = Command::new(make);
2811 cmd.current_dir(&self.testpaths.file)
2812 .stdout(Stdio::piped())
2813 .stderr(Stdio::piped())
2814 .env("TARGET", &self.config.target)
2815 .env("PYTHON", &self.config.docck_python)
2817 .env("RUST_BUILD_STAGE", &self.config.stage_id)
2818 .env("RUSTC", cwd.join(&self.config.rustc_path))
2819 .env("TMPDIR", &tmpdir)
2820 .env("LD_LIB_PATH_ENVVAR", dylib_env_var())
2821 .env("HOST_RPATH_DIR", cwd.join(&self.config.compile_lib_path))
2822 .env("TARGET_RPATH_DIR", cwd.join(&self.config.run_lib_path))
2823 .env("LLVM_COMPONENTS", &self.config.llvm_components)
2824 // We for sure don't want these tests to run in parallel, so make
2825 // sure they don't have access to these vars if we run via `make`
2827 .env_remove("MAKEFLAGS")
2828 .env_remove("MFLAGS")
2829 .env_remove("CARGO_MAKEFLAGS");
2831 if let Some(ref rustdoc) = self.config.rustdoc_path {
2832 cmd.env("RUSTDOC", cwd.join(rustdoc));
2835 if let Some(ref rust_demangler) = self.config.rust_demangler_path {
2836 cmd.env("RUST_DEMANGLER", cwd.join(rust_demangler));
2839 if let Some(ref node) = self.config.nodejs {
2840 cmd.env("NODE", node);
2843 if let Some(ref linker) = self.config.linker {
2844 cmd.env("RUSTC_LINKER", linker);
2847 if let Some(ref clang) = self.config.run_clang_based_tests_with {
2848 cmd.env("CLANG", clang);
2851 if let Some(ref filecheck) = self.config.llvm_filecheck {
2852 cmd.env("LLVM_FILECHECK", filecheck);
2855 if let Some(ref llvm_bin_dir) = self.config.llvm_bin_dir {
2856 cmd.env("LLVM_BIN_DIR", llvm_bin_dir);
2859 // We don't want RUSTFLAGS set from the outside to interfere with
2860 // compiler flags set in the test cases:
2861 cmd.env_remove("RUSTFLAGS");
2863 // Use dynamic musl for tests because static doesn't allow creating dylibs
2864 if self.config.host.contains("musl") {
2865 cmd.env("RUSTFLAGS", "-Ctarget-feature=-crt-static").env("IS_MUSL_HOST", "1");
2868 if self.config.bless {
2869 cmd.env("RUSTC_BLESS_TEST", "--bless");
2870 // Assume this option is active if the environment variable is "defined", with _any_ value.
2871 // As an example, a `Makefile` can use this option by:
2873 // ifdef RUSTC_BLESS_TEST
2874 // cp "$(TMPDIR)"/actual_something.ext expected_something.ext
2876 // $(DIFF) expected_something.ext "$(TMPDIR)"/actual_something.ext
2880 if self.config.target.contains("msvc") && self.config.cc != "" {
2881 // We need to pass a path to `lib.exe`, so assume that `cc` is `cl.exe`
2882 // and that `lib.exe` lives next to it.
2883 let lib = Path::new(&self.config.cc).parent().unwrap().join("lib.exe");
2885 // MSYS doesn't like passing flags of the form `/foo` as it thinks it's
2886 // a path and instead passes `C:\msys64\foo`, so convert all
2887 // `/`-arguments to MSVC here to `-` arguments.
2892 .map(|s| s.replace("/", "-"))
2893 .collect::<Vec<_>>()
2896 cmd.env("IS_MSVC", "1")
2897 .env("IS_WINDOWS", "1")
2898 .env("MSVC_LIB", format!("'{}' -nologo", lib.display()))
2899 .env("CC", format!("'{}' {}", self.config.cc, cflags))
2900 .env("CXX", format!("'{}'", &self.config.cxx));
2902 cmd.env("CC", format!("{} {}", self.config.cc, self.config.cflags))
2903 .env("CXX", format!("{} {}", self.config.cxx, self.config.cflags))
2904 .env("AR", &self.config.ar);
2906 if self.config.target.contains("windows") {
2907 cmd.env("IS_WINDOWS", "1");
2911 let output = cmd.spawn().and_then(read2_abbreviated).expect("failed to spawn `make`");
2912 if !output.status.success() {
2914 status: output.status,
2915 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
2916 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
2917 cmdline: format!("{:?}", cmd),
2919 self.fatal_proc_rec("make failed", &res);
2923 fn aggressive_rm_rf(&self, path: &Path) -> io::Result<()> {
2924 for e in path.read_dir()? {
2926 let path = entry.path();
2927 if entry.file_type()?.is_dir() {
2928 self.aggressive_rm_rf(&path)?;
2930 // Remove readonly files as well on windows (by default we can't)
2931 fs::remove_file(&path).or_else(|e| {
2932 if cfg!(windows) && e.kind() == io::ErrorKind::PermissionDenied {
2933 let mut meta = entry.metadata()?.permissions();
2934 meta.set_readonly(false);
2935 fs::set_permissions(&path, meta)?;
2936 fs::remove_file(&path)
2943 fs::remove_dir(path)
2946 fn run_js_doc_test(&self) {
2947 if let Some(nodejs) = &self.config.nodejs {
2948 let out_dir = self.output_base_dir();
2950 self.document(&out_dir);
2952 let root = self.config.find_rust_src_root().unwrap();
2954 self.testpaths.file.file_stem().and_then(|f| f.to_str()).expect("no file stem");
2955 let res = self.cmd2procres(
2956 Command::new(&nodejs)
2957 .arg(root.join("src/tools/rustdoc-js/tester.js"))
2958 .arg("--doc-folder")
2960 .arg("--crate-name")
2961 .arg(file_stem.replace("-", "_"))
2963 .arg(self.testpaths.file.with_extension("js")),
2965 if !res.status.success() {
2966 self.fatal_proc_rec("rustdoc-js test failed!", &res);
2969 self.fatal("no nodeJS");
2973 fn load_compare_outputs(
2976 output_kind: TestOutput,
2977 explicit_format: bool,
2979 let stderr_bits = format!("{}.stderr", get_pointer_width(&self.config.target));
2980 let (stderr_kind, stdout_kind) = match output_kind {
2981 TestOutput::Compile => (
2983 if self.props.stderr_per_bitwidth { &stderr_bits } else { UI_STDERR }
2987 TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
2990 let expected_stderr = self.load_expected_output(stderr_kind);
2991 let expected_stdout = self.load_expected_output(stdout_kind);
2993 let normalized_stdout = match output_kind {
2994 TestOutput::Run if self.config.remote_test_client.is_some() => {
2995 // When tests are run using the remote-test-client, the string
2996 // 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"'
2997 // is printed to stdout by the client and then captured in the ProcRes,
2998 // so it needs to be removed when comparing the run-pass test execution output
3000 static ref REMOTE_TEST_RE: Regex = Regex::new(
3001 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-.]+)+\", waiting for result\n"
3007 &self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
3012 _ => self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
3015 let stderr = if explicit_format {
3016 proc_res.stderr.clone()
3018 json::extract_rendered(&proc_res.stderr)
3021 let normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
3024 TestOutput::Compile => {
3025 if !self.props.dont_check_compiler_stdout {
3027 self.compare_output(stdout_kind, &normalized_stdout, &expected_stdout);
3029 if !self.props.dont_check_compiler_stderr {
3031 self.compare_output(stderr_kind, &normalized_stderr, &expected_stderr);
3034 TestOutput::Run => {
3035 errors += self.compare_output(stdout_kind, &normalized_stdout, &expected_stdout);
3036 errors += self.compare_output(stderr_kind, &normalized_stderr, &expected_stderr);
3042 fn run_ui_test(&self) {
3043 if let Some(FailMode::Build) = self.props.fail_mode {
3044 // Make sure a build-fail test cannot fail due to failing analysis (e.g. typeck).
3045 let pm = Some(PassMode::Check);
3046 let proc_res = self.compile_test_general(WillExecute::No, EmitMetadata::Yes, pm);
3047 self.check_if_test_should_compile(&proc_res, pm);
3050 let pm = self.pass_mode();
3051 let should_run = self.should_run(pm);
3052 let emit_metadata = self.should_emit_metadata(pm);
3053 let proc_res = self.compile_test(should_run, emit_metadata);
3054 self.check_if_test_should_compile(&proc_res, pm);
3056 // if the user specified a format in the ui test
3057 // print the output to the stderr file, otherwise extract
3058 // the rendered error messages from json and print them
3059 let explicit = self.props.compile_flags.iter().any(|s| s.contains("--error-format"));
3061 let expected_fixed = self.load_expected_output(UI_FIXED);
3063 let modes_to_prune = vec![CompareMode::Nll];
3064 self.prune_duplicate_outputs(&modes_to_prune);
3066 let mut errors = self.load_compare_outputs(&proc_res, TestOutput::Compile, explicit);
3067 let rustfix_input = json::rustfix_diagnostics_only(&proc_res.stderr);
3069 if self.config.compare_mode.is_some() {
3070 // don't test rustfix with nll right now
3071 } else if self.config.rustfix_coverage {
3072 // Find out which tests have `MachineApplicable` suggestions but are missing
3073 // `run-rustfix` or `run-rustfix-only-machine-applicable` headers.
3075 // This will return an empty `Vec` in case the executed test file has a
3076 // `compile-flags: --error-format=xxxx` header with a value other than `json`.
3077 let suggestions = get_suggestions_from_json(
3080 Filter::MachineApplicableOnly,
3082 .unwrap_or_default();
3083 if !suggestions.is_empty()
3084 && !self.props.run_rustfix
3085 && !self.props.rustfix_only_machine_applicable
3087 let mut coverage_file_path = self.config.build_base.clone();
3088 coverage_file_path.push("rustfix_missing_coverage.txt");
3089 debug!("coverage_file_path: {}", coverage_file_path.display());
3091 let mut file = OpenOptions::new()
3094 .open(coverage_file_path.as_path())
3095 .expect("could not create or open file");
3097 if writeln!(file, "{}", self.testpaths.file.display()).is_err() {
3098 panic!("couldn't write to {}", coverage_file_path.display());
3101 } else if self.props.run_rustfix {
3102 // Apply suggestions from rustc to the code itself
3103 let unfixed_code = self.load_expected_output_from_path(&self.testpaths.file).unwrap();
3104 let suggestions = get_suggestions_from_json(
3107 if self.props.rustfix_only_machine_applicable {
3108 Filter::MachineApplicableOnly
3114 let fixed_code = apply_suggestions(&unfixed_code, &suggestions).unwrap_or_else(|e| {
3116 "failed to apply suggestions for {:?} with rustfix: {}",
3117 self.testpaths.file, e
3121 errors += self.compare_output("fixed", &fixed_code, &expected_fixed);
3122 } else if !expected_fixed.is_empty() {
3124 "the `// run-rustfix` directive wasn't found but a `*.fixed` \
3130 println!("To update references, rerun the tests and pass the `--bless` flag");
3131 let relative_path_to_file =
3132 self.testpaths.relative_dir.join(self.testpaths.file.file_name().unwrap());
3134 "To only update this specific test, also pass `--test-args {}`",
3135 relative_path_to_file.display(),
3137 self.fatal_proc_rec(
3138 &format!("{} errors occurred comparing output.", errors),
3143 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
3145 if let WillExecute::Yes = should_run {
3146 let proc_res = self.exec_compiled_test();
3147 let run_output_errors = if self.props.check_run_results {
3148 self.load_compare_outputs(&proc_res, TestOutput::Run, explicit)
3152 if run_output_errors > 0 {
3153 self.fatal_proc_rec(
3154 &format!("{} errors occurred comparing run output.", run_output_errors),
3158 if self.should_run_successfully(pm) {
3159 if !proc_res.status.success() {
3160 self.fatal_proc_rec("test run failed!", &proc_res);
3162 } else if proc_res.status.success() {
3163 self.fatal_proc_rec("test run succeeded!", &proc_res);
3166 if !self.props.error_patterns.is_empty() {
3167 // "// error-pattern" comments
3168 self.check_error_patterns(&proc_res.stderr, &proc_res, pm);
3173 "run_ui_test: explicit={:?} config.compare_mode={:?} expected_errors={:?} \
3174 proc_res.status={:?} props.error_patterns={:?}",
3176 self.config.compare_mode,
3179 self.props.error_patterns
3181 if !explicit && self.config.compare_mode.is_none() {
3182 let check_patterns =
3183 should_run == WillExecute::No && !self.props.error_patterns.is_empty();
3185 let check_annotations = !check_patterns || !expected_errors.is_empty();
3188 // "// error-pattern" comments
3189 self.check_error_patterns(&proc_res.stderr, &proc_res, pm);
3192 if check_annotations {
3193 // "//~ERROR comments"
3194 self.check_expected_errors(expected_errors, &proc_res);
3198 if self.props.run_rustfix && self.config.compare_mode.is_none() {
3199 // And finally, compile the fixed code and make sure it both
3200 // succeeds and has no diagnostics.
3201 let mut rustc = self.make_compile_args(
3202 &self.testpaths.file.with_extension(UI_FIXED),
3203 TargetLocation::ThisFile(self.make_exe_name()),
3207 rustc.arg("-L").arg(&self.aux_output_dir_name());
3208 let res = self.compose_and_run_compiler(rustc, None);
3209 if !res.status.success() {
3210 self.fatal_proc_rec("failed to compile fixed code", &res);
3212 if !res.stderr.is_empty()
3213 && !self.props.rustfix_only_machine_applicable
3214 && !json::rustfix_diagnostics_only(&res.stderr).is_empty()
3216 self.fatal_proc_rec("fixed code is still producing diagnostics", &res);
3221 fn run_mir_opt_test(&self) {
3222 let pm = self.pass_mode();
3223 let should_run = self.should_run(pm);
3224 let emit_metadata = self.should_emit_metadata(pm);
3225 let proc_res = self.compile_test(should_run, emit_metadata);
3227 if !proc_res.status.success() {
3228 self.fatal_proc_rec("compilation failed!", &proc_res);
3231 self.check_mir_dump();
3233 if let WillExecute::Yes = should_run {
3234 let proc_res = self.exec_compiled_test();
3236 if !proc_res.status.success() {
3237 self.fatal_proc_rec("test run failed!", &proc_res);
3242 fn check_mir_dump(&self) {
3243 let test_file_contents = fs::read_to_string(&self.testpaths.file).unwrap();
3245 let test_dir = self.testpaths.file.parent().unwrap();
3247 self.testpaths.file.file_stem().unwrap().to_str().unwrap().replace("-", "_");
3249 let mut bit_width = String::new();
3250 if test_file_contents.lines().any(|l| l == "// EMIT_MIR_FOR_EACH_BIT_WIDTH") {
3251 bit_width = format!(".{}", get_pointer_width(&self.config.target));
3254 if self.config.bless {
3256 glob(&format!("{}/{}.*{}.mir", test_dir.display(), test_crate, bit_width)).unwrap()
3258 std::fs::remove_file(e.unwrap()).unwrap();
3261 glob(&format!("{}/{}.*{}.diff", test_dir.display(), test_crate, bit_width)).unwrap()
3263 std::fs::remove_file(e.unwrap()).unwrap();
3267 for l in test_file_contents.lines() {
3268 if l.starts_with("// EMIT_MIR ") {
3269 let test_name = l.trim_start_matches("// EMIT_MIR ").trim();
3270 let mut test_names = test_name.split(' ');
3271 // sometimes we specify two files so that we get a diff between the two files
3272 let test_name = test_names.next().unwrap();
3273 let mut expected_file;
3277 if test_name.ends_with(".diff") {
3278 let trimmed = test_name.trim_end_matches(".diff");
3279 let test_against = format!("{}.after.mir", trimmed);
3280 from_file = format!("{}.before.mir", trimmed);
3281 expected_file = format!("{}{}.diff", trimmed, bit_width);
3283 test_names.next().is_none(),
3284 "two mir pass names specified for MIR diff"
3286 to_file = Some(test_against);
3287 } else if let Some(first_pass) = test_names.next() {
3288 let second_pass = test_names.next().unwrap();
3290 test_names.next().is_none(),
3291 "three mir pass names specified for MIR diff"
3294 format!("{}{}.{}-{}.diff", test_name, bit_width, first_pass, second_pass);
3295 let second_file = format!("{}.{}.mir", test_name, second_pass);
3296 from_file = format!("{}.{}.mir", test_name, first_pass);
3297 to_file = Some(second_file);
3299 let ext_re = Regex::new(r#"(\.(mir|dot|html))$"#).unwrap();
3301 .captures_iter(test_name)
3303 .expect("test_name has an invalid extension");
3304 let extension = cap.get(1).unwrap().as_str();
3305 expected_file = format!(
3307 test_name.trim_end_matches(extension),
3311 from_file = test_name.to_string();
3313 test_names.next().is_none(),
3314 "two mir pass names specified for MIR dump"
3318 if !expected_file.starts_with(&test_crate) {
3319 expected_file = format!("{}.{}", test_crate, expected_file);
3321 let expected_file = test_dir.join(expected_file);
3323 let dumped_string = if let Some(after) = to_file {
3324 self.diff_mir_files(from_file.into(), after.into())
3326 let mut output_file = PathBuf::new();
3327 output_file.push(self.get_mir_dump_dir());
3328 output_file.push(&from_file);
3330 "comparing the contents of: {} with {}",
3331 output_file.display(),
3332 expected_file.display()
3334 if !output_file.exists() {
3336 "Output file `{}` from test does not exist, available files are in `{}`",
3337 output_file.display(),
3338 output_file.parent().unwrap().display()
3341 self.check_mir_test_timestamp(&from_file, &output_file);
3342 let dumped_string = fs::read_to_string(&output_file).unwrap();
3343 self.normalize_output(&dumped_string, &[])
3346 if self.config.bless {
3347 let _ = std::fs::remove_file(&expected_file);
3348 std::fs::write(expected_file, dumped_string.as_bytes()).unwrap();
3350 if !expected_file.exists() {
3352 "Output file `{}` from test does not exist",
3353 expected_file.display()
3356 let expected_string = fs::read_to_string(&expected_file).unwrap();
3357 if dumped_string != expected_string {
3358 print!("{}", write_diff(&expected_string, &dumped_string, 3));
3360 "Actual MIR output differs from expected MIR output {}",
3361 expected_file.display()
3369 fn diff_mir_files(&self, before: PathBuf, after: PathBuf) -> String {
3370 let to_full_path = |path: PathBuf| {
3371 let full = self.get_mir_dump_dir().join(&path);
3374 "the mir dump file for {} does not exist (requested in {})",
3376 self.testpaths.file.display(),
3381 let before = to_full_path(before);
3382 let after = to_full_path(after);
3383 debug!("comparing the contents of: {} with {}", before.display(), after.display());
3384 let before = fs::read_to_string(before).unwrap();
3385 let after = fs::read_to_string(after).unwrap();
3386 let before = self.normalize_output(&before, &[]);
3387 let after = self.normalize_output(&after, &[]);
3388 let mut dumped_string = String::new();
3389 for result in diff::lines(&before, &after) {
3390 use std::fmt::Write;
3392 diff::Result::Left(s) => writeln!(dumped_string, "- {}", s).unwrap(),
3393 diff::Result::Right(s) => writeln!(dumped_string, "+ {}", s).unwrap(),
3394 diff::Result::Both(s, _) => writeln!(dumped_string, " {}", s).unwrap(),
3400 fn check_mir_test_timestamp(&self, test_name: &str, output_file: &Path) {
3401 let t = |file| fs::metadata(file).unwrap().modified().unwrap();
3402 let source_file = &self.testpaths.file;
3403 let output_time = t(output_file);
3404 let source_time = t(source_file);
3405 if source_time > output_time {
3406 debug!("source file time: {:?} output file time: {:?}", source_time, output_time);
3408 "test source file `{}` is newer than potentially stale output file `{}`.",
3409 source_file.display(),
3415 fn get_mir_dump_dir(&self) -> PathBuf {
3416 let mut mir_dump_dir = PathBuf::from(self.config.build_base.as_path());
3417 debug!("input_file: {:?}", self.testpaths.file);
3418 mir_dump_dir.push(&self.testpaths.relative_dir);
3419 mir_dump_dir.push(self.testpaths.file.file_stem().unwrap());
3423 fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> String {
3424 let cflags = self.props.compile_flags.join(" ");
3425 let json = cflags.contains("--error-format json")
3426 || cflags.contains("--error-format pretty-json")
3427 || cflags.contains("--error-format=json")
3428 || cflags.contains("--error-format=pretty-json")
3429 || cflags.contains("--output-format json")
3430 || cflags.contains("--output-format=json");
3432 let mut normalized = output.to_string();
3434 let mut normalize_path = |from: &Path, to: &str| {
3435 let mut from = from.display().to_string();
3437 from = from.replace("\\", "\\\\");
3439 normalized = normalized.replace(&from, to);
3442 let parent_dir = self.testpaths.file.parent().unwrap();
3443 normalize_path(parent_dir, "$DIR");
3445 // Paths into the libstd/libcore
3456 normalize_path(&src_dir, "$SRC_DIR");
3458 if let Some(virtual_rust_source_base_dir) =
3459 option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR").map(PathBuf::from)
3461 normalize_path(&virtual_rust_source_base_dir.join("library"), "$SRC_DIR");
3464 // Paths into the build directory
3465 let test_build_dir = &self.config.build_base;
3466 let parent_build_dir = test_build_dir.parent().unwrap().parent().unwrap().parent().unwrap();
3468 // eg. /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui
3469 normalize_path(test_build_dir, "$TEST_BUILD_DIR");
3470 // eg. /home/user/rust/build
3471 normalize_path(parent_build_dir, "$BUILD_DIR");
3473 // Paths into lib directory.
3474 normalize_path(&parent_build_dir.parent().unwrap().join("lib"), "$LIB_DIR");
3477 // escaped newlines in json strings should be readable
3478 // in the stderr files. There's no point int being correct,
3479 // since only humans process the stderr files.
3480 // Thus we just turn escaped newlines back into newlines.
3481 normalized = normalized.replace("\\n", "\n");
3484 // If there are `$SRC_DIR` normalizations with line and column numbers, then replace them
3485 // with placeholders as we do not want tests needing updated when compiler source code
3487 // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
3488 normalized = Regex::new("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?")
3490 .replace_all(&normalized, "SRC_DIR$1:LL:COL")
3493 normalized = Self::normalize_platform_differences(&normalized);
3494 normalized = normalized.replace("\t", "\\t"); // makes tabs visible
3496 // Remove test annotations like `//~ ERROR text` from the output,
3497 // since they duplicate actual errors and make the output hard to read.
3498 // This mirrors the regex in src/tools/tidy/src/style.rs, please update
3499 // both if either are changed.
3501 Regex::new("\\s*//(\\[.*\\])?~.*").unwrap().replace_all(&normalized, "").into_owned();
3503 for rule in custom_rules {
3504 let re = Regex::new(&rule.0).expect("bad regex in custom normalization rule");
3505 normalized = re.replace_all(&normalized, &rule.1[..]).into_owned();
3510 /// Normalize output differences across platforms. Generally changes Windows output to be more
3513 /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
3515 fn normalize_platform_differences(output: &str) -> String {
3517 /// Used to find Windows paths.
3519 /// It's not possible to detect paths in the error messages generally, but this is a
3520 /// decent enough heuristic.
3521 static ref PATH_BACKSLASH_RE: Regex = Regex::new(r#"(?x)
3523 # Match paths that don't include spaces.
3524 (?:\\[\pL\pN\.\-_']+)+\.\pL+
3526 # If the path starts with a well-known root, then allow spaces.
3527 \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_' ]+)+
3532 let output = output.replace(r"\\", r"\");
3535 .replace_all(&output, |caps: &Captures<'_>| {
3536 println!("{}", &caps[0]);
3537 caps[0].replace(r"\", "/")
3539 .replace("\r\n", "\n")
3542 fn expected_output_path(&self, kind: &str) -> PathBuf {
3544 expected_output_path(&self.testpaths, self.revision, &self.config.compare_mode, kind);
3547 if let Some(CompareMode::Polonius) = self.config.compare_mode {
3548 path = expected_output_path(
3551 &Some(CompareMode::Nll),
3558 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3564 fn load_expected_output(&self, kind: &str) -> String {
3565 let path = self.expected_output_path(kind);
3567 match self.load_expected_output_from_path(&path) {
3569 Err(x) => self.fatal(&x),
3576 fn load_expected_output_from_path(&self, path: &Path) -> Result<String, String> {
3577 fs::read_to_string(path).map_err(|err| {
3578 format!("failed to load expected output from `{}`: {}", path.display(), err)
3582 fn delete_file(&self, file: &PathBuf) {
3584 // Deleting a nonexistant file would error.
3587 if let Err(e) = fs::remove_file(file) {
3588 self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,));
3592 fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize {
3593 if actual == expected {
3597 if !self.config.bless {
3598 if expected.is_empty() {
3599 println!("normalized {}:\n{}\n", kind, actual);
3601 println!("diff of {}:\n", kind);
3602 print!("{}", write_diff(expected, actual, 3));
3606 let mode = self.config.compare_mode.as_ref().map_or("", |m| m.to_str());
3607 let output_file = self
3609 .with_extra_extension(self.revision.unwrap_or(""))
3610 .with_extra_extension(mode)
3611 .with_extra_extension(kind);
3613 let mut files = vec![output_file];
3614 if self.config.bless {
3615 // Delete non-revision .stderr/.stdout file if revisions are used.
3616 // Without this, we'd just generate the new files and leave the old files around.
3617 if self.revision.is_some() {
3619 expected_output_path(self.testpaths, None, &self.config.compare_mode, kind);
3620 self.delete_file(&old);
3622 files.push(expected_output_path(
3625 &self.config.compare_mode,
3630 for output_file in &files {
3631 if actual.is_empty() {
3632 self.delete_file(output_file);
3633 } else if let Err(err) = fs::write(&output_file, &actual) {
3634 self.fatal(&format!(
3635 "failed to write {} to `{}`: {}",
3637 output_file.display(),
3643 println!("\nThe actual {0} differed from the expected {0}.", kind);
3644 for output_file in files {
3645 println!("Actual {} saved to {}", kind, output_file.display());
3647 if self.config.bless { 0 } else { 1 }
3650 fn prune_duplicate_output(&self, mode: CompareMode, kind: &str, canon_content: &str) {
3651 let examined_path = expected_output_path(&self.testpaths, self.revision, &Some(mode), kind);
3653 let examined_content =
3654 self.load_expected_output_from_path(&examined_path).unwrap_or_else(|_| String::new());
3656 if canon_content == examined_content {
3657 self.delete_file(&examined_path);
3661 fn prune_duplicate_outputs(&self, modes: &[CompareMode]) {
3662 if self.config.bless {
3663 for kind in UI_EXTENSIONS {
3664 let canon_comparison_path =
3665 expected_output_path(&self.testpaths, self.revision, &None, kind);
3667 if let Ok(canon) = self.load_expected_output_from_path(&canon_comparison_path) {
3669 self.prune_duplicate_output(mode.clone(), kind, &canon);
3676 fn create_stamp(&self) {
3677 let stamp = crate::stamp(&self.config, self.testpaths, self.revision);
3678 fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap();
3687 pub struct ProcRes {
3695 pub fn fatal(&self, err: Option<&str>, on_failure: impl FnOnce()) -> ! {
3696 if let Some(e) = err {
3697 println!("\nerror: {}", e);
3704 ------------------------------------------\n\
3706 ------------------------------------------\n\
3708 ------------------------------------------\n\
3710 ------------------------------------------\n\
3714 json::extract_rendered(&self.stdout),
3715 json::extract_rendered(&self.stderr),
3718 // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from
3719 // compiletest, which is unnecessary noise.
3720 std::panic::resume_unwind(Box::new(()));
3725 enum TargetLocation {
3727 ThisDirectory(PathBuf),