1 // ignore-tidy-filelength
3 use crate::common::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT};
4 use crate::common::{output_base_dir, output_base_name, output_testname_unique};
5 use crate::common::{Assembly, Incremental, JsDocTest, MirOpt, RunMake, Ui};
6 use crate::common::{Codegen, CodegenUnits, DebugInfo, Debugger, Rustdoc};
7 use crate::common::{CompareMode, FailMode, PassMode};
8 use crate::common::{CompileFail, Pretty, RunFail, RunPassValgrind};
9 use crate::common::{Config, TestPaths};
10 use crate::common::{UI_RUN_STDERR, UI_RUN_STDOUT};
11 use crate::errors::{self, Error, ErrorKind};
12 use crate::header::TestProps;
14 use crate::util::get_pointer_width;
15 use crate::util::{logv, PathBufExt};
16 use regex::{Captures, Regex};
17 use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
19 use std::collections::hash_map::DefaultHasher;
20 use std::collections::{HashMap, HashSet, VecDeque};
22 use std::ffi::{OsStr, OsString};
23 use std::fs::{self, create_dir_all, File, OpenOptions};
24 use std::hash::{Hash, Hasher};
25 use std::io::prelude::*;
26 use std::io::{self, BufReader};
27 use std::path::{Path, PathBuf};
28 use std::process::{Child, Command, ExitStatus, Output, Stdio};
32 use lazy_static::lazy_static;
35 use crate::extract_gdb_version;
36 use crate::is_android_gdb_target;
42 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
44 use winapi::um::errhandlingapi::SetErrorMode;
45 use winapi::um::winbase::SEM_NOGPFAULTERRORBOX;
48 static ref LOCK: Mutex<()> = Mutex::new(());
50 // Error mode is a global variable, so lock it so only one thread will change it
51 let _lock = LOCK.lock().unwrap();
53 // Tell Windows to not show any UI on errors (such as terminating abnormally).
54 // This is important for running tests, since some of them use abnormal
55 // termination by design. This mode is inherited by all child processes.
57 let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX); // read inherited flags
58 SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX);
60 SetErrorMode(old_mode);
66 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
70 /// The name of the environment variable that holds dynamic library locations.
71 pub fn dylib_env_var() -> &'static str {
74 } else if cfg!(target_os = "macos") {
76 } else if cfg!(target_os = "haiku") {
83 /// The platform-specific library name
84 pub fn get_lib_name(lib: &str, dylib: bool) -> String {
85 // In some casess (e.g. MUSL), we build a static
86 // library, rather than a dynamic library.
87 // In this case, the only path we can pass
88 // with '--extern-meta' is the '.lib' file
90 return format!("lib{}.rlib", lib);
94 format!("{}.dll", lib)
95 } else if cfg!(target_os = "macos") {
96 format!("lib{}.dylib", lib)
98 format!("lib{}.so", lib)
102 #[derive(Debug, PartialEq)]
109 #[derive(Debug, PartialEq)]
110 pub struct Mismatch {
111 pub line_number: u32,
112 pub lines: Vec<DiffLine>,
116 fn new(line_number: u32) -> Mismatch {
117 Mismatch { line_number, lines: Vec::new() }
121 // Produces a diff between the expected output and actual output.
122 pub fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec<Mismatch> {
123 let mut line_number = 1;
124 let mut context_queue: VecDeque<&str> = VecDeque::with_capacity(context_size);
125 let mut lines_since_mismatch = context_size + 1;
126 let mut results = Vec::new();
127 let mut mismatch = Mismatch::new(0);
129 for result in diff::lines(expected, actual) {
131 diff::Result::Left(str) => {
132 if lines_since_mismatch >= context_size && lines_since_mismatch > 0 {
133 results.push(mismatch);
134 mismatch = Mismatch::new(line_number - context_queue.len() as u32);
137 while let Some(line) = context_queue.pop_front() {
138 mismatch.lines.push(DiffLine::Context(line.to_owned()));
141 mismatch.lines.push(DiffLine::Expected(str.to_owned()));
143 lines_since_mismatch = 0;
145 diff::Result::Right(str) => {
146 if lines_since_mismatch >= context_size && lines_since_mismatch > 0 {
147 results.push(mismatch);
148 mismatch = Mismatch::new(line_number - context_queue.len() as u32);
151 while let Some(line) = context_queue.pop_front() {
152 mismatch.lines.push(DiffLine::Context(line.to_owned()));
155 mismatch.lines.push(DiffLine::Resulting(str.to_owned()));
156 lines_since_mismatch = 0;
158 diff::Result::Both(str, _) => {
159 if context_queue.len() >= context_size {
160 let _ = context_queue.pop_front();
163 if lines_since_mismatch < context_size {
164 mismatch.lines.push(DiffLine::Context(str.to_owned()));
165 } else if context_size > 0 {
166 context_queue.push_back(str);
170 lines_since_mismatch += 1;
175 results.push(mismatch);
181 fn write_diff(expected: &str, actual: &str, context_size: usize) -> String {
183 let mut output = String::new();
184 let diff_results = make_diff(expected, actual, context_size);
185 for result in diff_results {
186 let mut line_number = result.line_number;
187 for line in result.lines {
189 DiffLine::Expected(e) => {
190 writeln!(output, "-\t{}", e).unwrap();
193 DiffLine::Context(c) => {
194 writeln!(output, "{}\t{}", line_number, c).unwrap();
197 DiffLine::Resulting(r) => {
198 writeln!(output, "+\t{}", r).unwrap();
202 writeln!(output).unwrap();
207 pub fn run(config: Config, testpaths: &TestPaths, revision: Option<&str>) {
208 match &*config.target {
209 "arm-linux-androideabi"
210 | "armv7-linux-androideabi"
211 | "thumbv7neon-linux-androideabi"
212 | "aarch64-linux-android" => {
213 if !config.adb_device_status {
214 panic!("android device not available");
219 // android has its own gdb handling
220 if config.debugger == Some(Debugger::Gdb) && config.gdb.is_none() {
221 panic!("gdb not available but debuginfo gdb debuginfo test requested");
227 // We're going to be dumping a lot of info. Start on a new line.
230 debug!("running {:?}", testpaths.file.display());
231 let props = TestProps::from_file(&testpaths.file, revision, &config);
233 let cx = TestCx { config: &config, props: &props, testpaths, revision };
234 create_dir_all(&cx.output_base_dir()).unwrap();
236 if config.mode == Incremental {
237 // Incremental tests are special because they cannot be run in
239 assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
240 cx.init_incremental_test();
241 for revision in &props.revisions {
242 let revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
243 let rev_cx = TestCx {
245 props: &revision_props,
247 revision: Some(revision),
249 rev_cx.run_revision();
258 pub fn compute_stamp_hash(config: &Config) -> String {
259 let mut hash = DefaultHasher::new();
260 config.stage_id.hash(&mut hash);
262 match config.debugger {
263 Some(Debugger::Cdb) => {
264 config.cdb.hash(&mut hash);
267 Some(Debugger::Gdb) => {
268 config.gdb.hash(&mut hash);
269 env::var_os("PATH").hash(&mut hash);
270 env::var_os("PYTHONPATH").hash(&mut hash);
273 Some(Debugger::Lldb) => {
274 config.lldb_python.hash(&mut hash);
275 config.lldb_python_dir.hash(&mut hash);
276 env::var_os("PATH").hash(&mut hash);
277 env::var_os("PYTHONPATH").hash(&mut hash);
283 if let Ui = config.mode {
284 config.force_pass_mode.hash(&mut hash);
287 format!("{:x}", hash.finish())
290 struct TestCx<'test> {
291 config: &'test Config,
292 props: &'test TestProps,
293 testpaths: &'test TestPaths,
294 revision: Option<&'test str>,
297 struct DebuggerCommands {
298 commands: Vec<String>,
299 check_lines: Vec<String>,
300 breakpoint_lines: Vec<usize>,
313 /// Will this test be executed? Should we use `make_exe_name`?
314 #[derive(Copy, Clone, PartialEq)]
320 /// Should `--emit metadata` be used?
321 #[derive(Copy, Clone)]
327 impl<'test> TestCx<'test> {
328 /// Code executed for each revision in turn (or, if there are no
329 /// revisions, exactly once, with revision == None).
330 fn run_revision(&self) {
331 if self.props.should_ice {
332 if self.config.mode != CompileFail && self.config.mode != Incremental {
333 self.fatal("cannot use should-ice in a test that is not cfail");
336 match self.config.mode {
337 CompileFail => self.run_cfail_test(),
338 RunFail => self.run_rfail_test(),
339 RunPassValgrind => self.run_valgrind_test(),
340 Pretty => self.run_pretty_test(),
341 DebugInfo => self.run_debuginfo_test(),
342 Codegen => self.run_codegen_test(),
343 Rustdoc => self.run_rustdoc_test(),
344 CodegenUnits => self.run_codegen_units_test(),
345 Incremental => self.run_incremental_test(),
346 RunMake => self.run_rmake_test(),
347 Ui => self.run_ui_test(),
348 MirOpt => self.run_mir_opt_test(),
349 Assembly => self.run_assembly_test(),
350 JsDocTest => self.run_js_doc_test(),
354 fn pass_mode(&self) -> Option<PassMode> {
355 self.props.pass_mode(self.config)
358 fn should_run(&self, pm: Option<PassMode>) -> WillExecute {
359 match self.config.mode {
360 Ui if pm == Some(PassMode::Run) || self.props.fail_mode == Some(FailMode::Run) => {
363 MirOpt if pm == Some(PassMode::Run) => WillExecute::Yes,
364 Ui | MirOpt => WillExecute::No,
365 mode => panic!("unimplemented for mode {:?}", mode),
369 fn should_run_successfully(&self, pm: Option<PassMode>) -> bool {
370 match self.config.mode {
371 Ui | MirOpt => pm == Some(PassMode::Run),
372 mode => panic!("unimplemented for mode {:?}", mode),
376 fn should_compile_successfully(&self, pm: Option<PassMode>) -> bool {
377 match self.config.mode {
378 CompileFail => false,
380 Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
383 self.revision.expect("incremental tests require a list of revisions");
384 if revision.starts_with("rpass") || revision.starts_with("rfail") {
386 } else if revision.starts_with("cfail") {
387 // FIXME: would be nice if incremental revs could start with "cpass"
390 panic!("revision name must begin with rpass, rfail, or cfail");
393 mode => panic!("unimplemented for mode {:?}", mode),
397 fn check_if_test_should_compile(&self, proc_res: &ProcRes, pm: Option<PassMode>) {
398 if self.should_compile_successfully(pm) {
399 if !proc_res.status.success() {
400 self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res);
403 if proc_res.status.success() {
405 &format!("{} test compiled successfully!", self.config.mode)[..],
410 self.check_correct_failure_status(proc_res);
414 fn run_cfail_test(&self) {
415 let pm = self.pass_mode();
416 let proc_res = self.compile_test(WillExecute::No, self.should_emit_metadata(pm));
417 self.check_if_test_should_compile(&proc_res, pm);
418 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
420 let output_to_check = self.get_output(&proc_res);
421 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
422 if !expected_errors.is_empty() {
423 if !self.props.error_patterns.is_empty() {
424 self.fatal("both error pattern and expected errors specified");
426 self.check_expected_errors(expected_errors, &proc_res);
428 self.check_error_patterns(&output_to_check, &proc_res, pm);
430 if self.props.should_ice {
431 match proc_res.status.code() {
433 _ => self.fatal("expected ICE"),
437 self.check_forbid_output(&output_to_check, &proc_res);
440 fn run_rfail_test(&self) {
441 let pm = self.pass_mode();
442 let proc_res = self.compile_test(WillExecute::Yes, self.should_emit_metadata(pm));
444 if !proc_res.status.success() {
445 self.fatal_proc_rec("compilation failed!", &proc_res);
448 let proc_res = self.exec_compiled_test();
450 // The value our Makefile configures valgrind to return on failure
451 const VALGRIND_ERR: i32 = 100;
452 if proc_res.status.code() == Some(VALGRIND_ERR) {
453 self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
456 let output_to_check = self.get_output(&proc_res);
457 self.check_correct_failure_status(&proc_res);
458 self.check_error_patterns(&output_to_check, &proc_res, pm);
461 fn get_output(&self, proc_res: &ProcRes) -> String {
462 if self.props.check_stdout {
463 format!("{}{}", proc_res.stdout, proc_res.stderr)
465 proc_res.stderr.clone()
469 fn check_correct_failure_status(&self, proc_res: &ProcRes) {
470 let expected_status = Some(self.props.failure_status);
471 let received_status = proc_res.status.code();
473 if expected_status != received_status {
476 "Error: expected failure status ({:?}) but received status {:?}.",
477 expected_status, received_status
484 fn run_rpass_test(&self) {
485 let emit_metadata = self.should_emit_metadata(self.pass_mode());
486 let proc_res = self.compile_test(WillExecute::Yes, emit_metadata);
488 if !proc_res.status.success() {
489 self.fatal_proc_rec("compilation failed!", &proc_res);
492 // FIXME(#41968): Move this check to tidy?
493 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
495 expected_errors.is_empty(),
496 "run-pass tests with expected warnings should be moved to ui/"
499 let proc_res = self.exec_compiled_test();
500 if !proc_res.status.success() {
501 self.fatal_proc_rec("test run failed!", &proc_res);
505 fn run_valgrind_test(&self) {
506 assert!(self.revision.is_none(), "revisions not relevant here");
508 if self.config.valgrind_path.is_none() {
509 assert!(!self.config.force_valgrind);
510 return self.run_rpass_test();
513 let mut proc_res = self.compile_test(WillExecute::Yes, EmitMetadata::No);
515 if !proc_res.status.success() {
516 self.fatal_proc_rec("compilation failed!", &proc_res);
519 let mut new_config = self.config.clone();
520 new_config.runtool = new_config.valgrind_path.clone();
521 let new_cx = TestCx { config: &new_config, ..*self };
522 proc_res = new_cx.exec_compiled_test();
524 if !proc_res.status.success() {
525 self.fatal_proc_rec("test run failed!", &proc_res);
529 fn run_pretty_test(&self) {
530 if self.props.pp_exact.is_some() {
531 logv(self.config, "testing for exact pretty-printing".to_owned());
533 logv(self.config, "testing for converging pretty-printing".to_owned());
536 let rounds = match self.props.pp_exact {
541 let src = fs::read_to_string(&self.testpaths.file).unwrap();
542 let mut srcs = vec![src];
545 while round < rounds {
548 format!("pretty-printing round {} revision {:?}", round, self.revision),
551 if round == 0 { ReadFrom::Path } else { ReadFrom::Stdin(srcs[round].to_owned()) };
553 let proc_res = self.print_source(read_from, &self.props.pretty_mode);
554 if !proc_res.status.success() {
557 "pretty-printing failed in round {} revision {:?}",
564 let ProcRes { stdout, .. } = proc_res;
569 let mut expected = match self.props.pp_exact {
571 let filepath = self.testpaths.file.parent().unwrap().join(file);
572 fs::read_to_string(&filepath).unwrap()
574 None => srcs[srcs.len() - 2].clone(),
576 let mut actual = srcs[srcs.len() - 1].clone();
578 if self.props.pp_exact.is_some() {
579 // Now we have to care about line endings
580 let cr = "\r".to_owned();
581 actual = actual.replace(&cr, "");
582 expected = expected.replace(&cr, "");
585 self.compare_source(&expected, &actual);
587 // If we're only making sure that the output matches then just stop here
588 if self.props.pretty_compare_only {
592 // Finally, let's make sure it actually appears to remain valid code
593 let proc_res = self.typecheck_source(actual);
594 if !proc_res.status.success() {
595 self.fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
598 if !self.props.pretty_expanded {
602 // additionally, run `--pretty expanded` and try to build it.
603 let proc_res = self.print_source(ReadFrom::Path, "expanded");
604 if !proc_res.status.success() {
605 self.fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
608 let ProcRes { stdout: expanded_src, .. } = proc_res;
609 let proc_res = self.typecheck_source(expanded_src);
610 if !proc_res.status.success() {
611 self.fatal_proc_rec("pretty-printed source (expanded) does not typecheck", &proc_res);
615 fn print_source(&self, read_from: ReadFrom, pretty_type: &str) -> ProcRes {
616 let aux_dir = self.aux_output_dir_name();
617 let input: &str = match read_from {
618 ReadFrom::Stdin(_) => "-",
619 ReadFrom::Path => self.testpaths.file.to_str().unwrap(),
622 let mut rustc = Command::new(&self.config.rustc_path);
625 .args(&["-Z", &format!("unpretty={}", pretty_type)])
626 .args(&["--target", &self.config.target])
629 .args(&self.props.compile_flags)
630 .envs(self.props.rustc_env.clone());
631 self.maybe_add_external_args(
633 self.split_maybe_args(&self.config.target_rustcflags),
636 let src = match read_from {
637 ReadFrom::Stdin(src) => Some(src),
638 ReadFrom::Path => None,
641 self.compose_and_run(
643 self.config.compile_lib_path.to_str().unwrap(),
644 Some(aux_dir.to_str().unwrap()),
649 fn compare_source(&self, expected: &str, actual: &str) {
650 if expected != actual {
652 "pretty-printed source does not match expected source\n\
654 ------------------------------------------\n\
656 ------------------------------------------\n\
658 ------------------------------------------\n\
660 ------------------------------------------\n\
662 ------------------------------------------\n\
666 write_diff(expected, actual, 3),
671 fn set_revision_flags(&self, cmd: &mut Command) {
672 if let Some(revision) = self.revision {
673 // Normalize revisions to be lowercase and replace `-`s with `_`s.
674 // Otherwise the `--cfg` flag is not valid.
675 let normalized_revision = revision.to_lowercase().replace("-", "_");
676 cmd.args(&["--cfg", &normalized_revision]);
680 fn typecheck_source(&self, src: String) -> ProcRes {
681 let mut rustc = Command::new(&self.config.rustc_path);
683 let out_dir = self.output_base_name().with_extension("pretty-out");
684 let _ = fs::remove_dir_all(&out_dir);
685 create_dir_all(&out_dir).unwrap();
687 let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
689 let aux_dir = self.aux_output_dir_name();
696 .arg(&format!("--target={}", target))
698 .arg(&self.config.build_base)
701 self.set_revision_flags(&mut rustc);
702 self.maybe_add_external_args(
704 self.split_maybe_args(&self.config.target_rustcflags),
706 rustc.args(&self.props.compile_flags);
708 self.compose_and_run_compiler(rustc, Some(src))
711 fn run_debuginfo_test(&self) {
712 match self.config.debugger.unwrap() {
713 Debugger::Cdb => self.run_debuginfo_cdb_test(),
714 Debugger::Gdb => self.run_debuginfo_gdb_test(),
715 Debugger::Lldb => self.run_debuginfo_lldb_test(),
719 fn run_debuginfo_cdb_test(&self) {
720 assert!(self.revision.is_none(), "revisions not relevant here");
722 let config = Config {
723 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
724 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
725 ..self.config.clone()
728 let test_cx = TestCx { config: &config, ..*self };
730 test_cx.run_debuginfo_cdb_test_no_opt();
733 fn run_debuginfo_cdb_test_no_opt(&self) {
734 // compile test file (it should have 'compile-flags:-g' in the header)
735 let compile_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
736 if !compile_result.status.success() {
737 self.fatal_proc_rec("compilation failed!", &compile_result);
740 let exe_file = self.make_exe_name();
743 static PREFIXES: &[&str] = &["cdb", "cdbg"];
744 // No "native rust support" variation for CDB yet.
748 // Parse debugger commands etc from test files
749 let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
750 self.parse_debugger_commands(prefixes);
752 // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-commands
753 let mut script_str = String::with_capacity(2048);
754 script_str.push_str("version\n"); // List CDB (and more) version info in test output
755 script_str.push_str(".nvlist\n"); // List loaded `*.natvis` files, bulk of custom MSVC debug
757 // Set breakpoints on every line that contains the string "#break"
758 let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
759 for line in &breakpoint_lines {
760 script_str.push_str(&format!("bp `{}:{}`\n", source_file_name, line));
763 // Append the other `cdb-command:`s
764 for line in &commands {
765 script_str.push_str(line);
766 script_str.push_str("\n");
769 script_str.push_str("\nqq\n"); // Quit the debugger (including remote debugger, if any)
771 // Write the script into a file
772 debug!("script_str = {}", script_str);
773 self.dump_output_file(&script_str, "debugger.script");
774 let debugger_script = self.make_out_name("debugger.script");
776 let cdb_path = &self.config.cdb.as_ref().unwrap();
777 let mut cdb = Command::new(cdb_path);
778 cdb.arg("-lines") // Enable source line debugging.
780 .arg(&debugger_script)
783 let debugger_run_result = self.compose_and_run(
785 self.config.run_lib_path.to_str().unwrap(),
790 if !debugger_run_result.status.success() {
791 self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
794 self.check_debugger_output(&debugger_run_result, &check_lines);
797 fn run_debuginfo_gdb_test(&self) {
798 assert!(self.revision.is_none(), "revisions not relevant here");
800 let config = Config {
801 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
802 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
803 ..self.config.clone()
806 let test_cx = TestCx { config: &config, ..*self };
808 test_cx.run_debuginfo_gdb_test_no_opt();
811 fn run_debuginfo_gdb_test_no_opt(&self) {
812 let prefixes = if self.config.gdb_native_rust {
814 static PREFIXES: &[&str] = &["gdb", "gdbr"];
815 println!("NOTE: compiletest thinks it is using GDB with native rust support");
819 static PREFIXES: &[&str] = &["gdb", "gdbg"];
820 println!("NOTE: compiletest thinks it is using GDB without native rust support");
824 let DebuggerCommands { commands, check_lines, breakpoint_lines } =
825 self.parse_debugger_commands(prefixes);
826 let mut cmds = commands.join("\n");
828 // compile test file (it should have 'compile-flags:-g' in the header)
829 let compiler_run_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
830 if !compiler_run_result.status.success() {
831 self.fatal_proc_rec("compilation failed!", &compiler_run_result);
834 let exe_file = self.make_exe_name();
836 let debugger_run_result;
837 if is_android_gdb_target(&self.config.target) {
838 cmds = cmds.replace("run", "continue");
840 let tool_path = match self.config.android_cross_path.to_str() {
841 Some(x) => x.to_owned(),
842 None => self.fatal("cannot find android cross path"),
845 // write debugger script
846 let mut script_str = String::with_capacity(2048);
847 script_str.push_str(&format!("set charset {}\n", Self::charset()));
848 script_str.push_str(&format!("set sysroot {}\n", tool_path));
849 script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
850 script_str.push_str("target remote :5039\n");
851 script_str.push_str(&format!(
852 "set solib-search-path \
853 ./{}/stage2/lib/rustlib/{}/lib/\n",
854 self.config.host, self.config.target
856 for line in &breakpoint_lines {
860 self.testpaths.file.file_name().unwrap().to_string_lossy(),
865 script_str.push_str(&cmds);
866 script_str.push_str("\nquit\n");
868 debug!("script_str = {}", script_str);
869 self.dump_output_file(&script_str, "debugger.script");
871 let adb_path = &self.config.adb_path;
873 Command::new(adb_path)
876 .arg(&self.config.adb_test_dir)
878 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
880 Command::new(adb_path)
881 .args(&["forward", "tcp:5039", "tcp:5039"])
883 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
885 let adb_arg = format!(
886 "export LD_LIBRARY_PATH={}; \
887 gdbserver{} :5039 {}/{}",
888 self.config.adb_test_dir.clone(),
889 if self.config.target.contains("aarch64") { "64" } else { "" },
890 self.config.adb_test_dir.clone(),
891 exe_file.file_name().unwrap().to_str().unwrap()
894 debug!("adb arg: {}", adb_arg);
895 let mut adb = Command::new(adb_path)
896 .args(&["shell", &adb_arg])
897 .stdout(Stdio::piped())
898 .stderr(Stdio::inherit())
900 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path));
902 // Wait for the gdbserver to print out "Listening on port ..."
903 // at which point we know that it's started and then we can
904 // execute the debugger below.
905 let mut stdout = BufReader::new(adb.stdout.take().unwrap());
906 let mut line = String::new();
909 stdout.read_line(&mut line).unwrap();
910 if line.starts_with("Listening on port 5039") {
916 let mut debugger_script = OsString::from("-command=");
917 debugger_script.push(self.make_out_name("debugger.script"));
918 let debugger_opts: &[&OsStr] =
919 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
921 let gdb_path = self.config.gdb.as_ref().unwrap();
922 let Output { status, stdout, stderr } = Command::new(&gdb_path)
925 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", gdb_path));
927 let mut gdb = Command::new(&format!("{}-gdb", self.config.target));
928 gdb.args(debugger_opts);
929 let cmdline = self.make_cmdline(&gdb, "");
930 logv(self.config, format!("executing {}", cmdline));
934 debugger_run_result = ProcRes {
936 stdout: String::from_utf8(stdout).unwrap(),
937 stderr: String::from_utf8(stderr).unwrap(),
940 if adb.kill().is_err() {
941 println!("Adb process is already finished.");
945 self.config.find_rust_src_root().expect("Could not find Rust source root");
946 let rust_pp_module_rel_path = Path::new("./src/etc");
947 let rust_pp_module_abs_path =
948 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
949 // write debugger script
950 let mut script_str = String::with_capacity(2048);
951 script_str.push_str(&format!("set charset {}\n", Self::charset()));
952 script_str.push_str("show version\n");
954 match self.config.gdb_version {
956 println!("NOTE: compiletest thinks it is using GDB version {}", version);
958 if version > extract_gdb_version("7.4").unwrap() {
959 // Add the directory containing the pretty printers to
960 // GDB's script auto loading safe path
961 script_str.push_str(&format!(
962 "add-auto-load-safe-path {}\n",
963 rust_pp_module_abs_path.replace(r"\", r"\\")
969 "NOTE: compiletest does not know which version of \
975 // The following line actually doesn't have to do anything with
976 // pretty printing, it just tells GDB to print values on one line:
977 script_str.push_str("set print pretty off\n");
979 // Add the pretty printer directory to GDB's source-file search path
980 script_str.push_str(&format!("directory {}\n", rust_pp_module_abs_path));
982 // Load the target executable
984 .push_str(&format!("file {}\n", exe_file.to_str().unwrap().replace(r"\", r"\\")));
986 // Force GDB to print values in the Rust format.
987 if self.config.gdb_native_rust {
988 script_str.push_str("set language rust\n");
991 // Add line breakpoints
992 for line in &breakpoint_lines {
993 script_str.push_str(&format!(
995 self.testpaths.file.file_name().unwrap().to_string_lossy(),
1000 script_str.push_str(&cmds);
1001 script_str.push_str("\nquit\n");
1003 debug!("script_str = {}", script_str);
1004 self.dump_output_file(&script_str, "debugger.script");
1006 let mut debugger_script = OsString::from("-command=");
1007 debugger_script.push(self.make_out_name("debugger.script"));
1009 let debugger_opts: &[&OsStr] =
1010 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
1012 let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
1013 gdb.args(debugger_opts).env("PYTHONPATH", rust_pp_module_abs_path);
1015 debugger_run_result =
1016 self.compose_and_run(gdb, self.config.run_lib_path.to_str().unwrap(), None, None);
1019 if !debugger_run_result.status.success() {
1020 self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
1023 self.check_debugger_output(&debugger_run_result, &check_lines);
1026 fn run_debuginfo_lldb_test(&self) {
1027 assert!(self.revision.is_none(), "revisions not relevant here");
1029 if self.config.lldb_python_dir.is_none() {
1030 self.fatal("Can't run LLDB test because LLDB's python path is not set.");
1033 let config = Config {
1034 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
1035 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
1036 ..self.config.clone()
1039 let test_cx = TestCx { config: &config, ..*self };
1041 test_cx.run_debuginfo_lldb_test_no_opt();
1044 fn run_debuginfo_lldb_test_no_opt(&self) {
1045 // compile test file (it should have 'compile-flags:-g' in the header)
1046 let compile_result = self.compile_test(WillExecute::Yes, EmitMetadata::No);
1047 if !compile_result.status.success() {
1048 self.fatal_proc_rec("compilation failed!", &compile_result);
1051 let exe_file = self.make_exe_name();
1053 match self.config.lldb_version {
1054 Some(ref version) => {
1055 println!("NOTE: compiletest thinks it is using LLDB version {}", version);
1059 "NOTE: compiletest does not know which version of \
1065 let prefixes = if self.config.lldb_native_rust {
1066 static PREFIXES: &[&str] = &["lldb", "lldbr"];
1067 println!("NOTE: compiletest thinks it is using LLDB with native rust support");
1070 static PREFIXES: &[&str] = &["lldb", "lldbg"];
1071 println!("NOTE: compiletest thinks it is using LLDB without native rust support");
1075 // Parse debugger commands etc from test files
1076 let DebuggerCommands { commands, check_lines, breakpoint_lines, .. } =
1077 self.parse_debugger_commands(prefixes);
1079 // Write debugger script:
1080 // We don't want to hang when calling `quit` while the process is still running
1081 let mut script_str = String::from("settings set auto-confirm true\n");
1083 // Make LLDB emit its version, so we have it documented in the test output
1084 script_str.push_str("version\n");
1086 // Switch LLDB into "Rust mode"
1088 self.config.find_rust_src_root().expect("Could not find Rust source root");
1089 let rust_pp_module_rel_path = Path::new("./src/etc/lldb_lookup.py");
1090 let rust_pp_module_abs_path =
1091 rust_src_root.join(rust_pp_module_rel_path).to_str().unwrap().to_owned();
1093 let rust_type_regexes = vec![
1094 "^(alloc::([a-z_]+::)+)String$",
1097 "^(std::ffi::([a-z_]+::)+)OsString$",
1098 "^(alloc::([a-z_]+::)+)Vec<.+>$",
1099 "^(alloc::([a-z_]+::)+)VecDeque<.+>$",
1100 "^(alloc::([a-z_]+::)+)BTreeSet<.+>$",
1101 "^(alloc::([a-z_]+::)+)BTreeMap<.+>$",
1102 "^(std::collections::([a-z_]+::)+)HashMap<.+>$",
1103 "^(std::collections::([a-z_]+::)+)HashSet<.+>$",
1104 "^(alloc::([a-z_]+::)+)Rc<.+>$",
1105 "^(alloc::([a-z_]+::)+)Arc<.+>$",
1106 "^(core::([a-z_]+::)+)Cell<.+>$",
1107 "^(core::([a-z_]+::)+)Ref<.+>$",
1108 "^(core::([a-z_]+::)+)RefMut<.+>$",
1109 "^(core::([a-z_]+::)+)RefCell<.+>$",
1113 .push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[..])[..]);
1114 script_str.push_str("type synthetic add -l lldb_lookup.synthetic_lookup -x '.*' ");
1115 script_str.push_str("--category Rust\n");
1116 for type_regex in rust_type_regexes {
1117 script_str.push_str("type summary add -F lldb_lookup.summary_lookup -e -x -h ");
1118 script_str.push_str(&format!("'{}' ", type_regex));
1119 script_str.push_str("--category Rust\n");
1121 script_str.push_str("type category enable Rust\n");
1123 // Set breakpoints on every line that contains the string "#break"
1124 let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy();
1125 for line in &breakpoint_lines {
1126 script_str.push_str(&format!(
1127 "breakpoint set --file '{}' --line {}\n",
1128 source_file_name, line
1132 // Append the other commands
1133 for line in &commands {
1134 script_str.push_str(line);
1135 script_str.push_str("\n");
1138 // Finally, quit the debugger
1139 script_str.push_str("\nquit\n");
1141 // Write the script into a file
1142 debug!("script_str = {}", script_str);
1143 self.dump_output_file(&script_str, "debugger.script");
1144 let debugger_script = self.make_out_name("debugger.script");
1146 // Let LLDB execute the script via lldb_batchmode.py
1147 let debugger_run_result = self.run_lldb(&exe_file, &debugger_script, &rust_src_root);
1149 if !debugger_run_result.status.success() {
1150 self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
1153 self.check_debugger_output(&debugger_run_result, &check_lines);
1158 test_executable: &Path,
1159 debugger_script: &Path,
1160 rust_src_root: &Path,
1162 // Prepare the lldb_batchmode which executes the debugger script
1163 let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
1165 Command::new(&self.config.lldb_python)
1166 .arg(&lldb_script_path)
1167 .arg(test_executable)
1168 .arg(debugger_script)
1169 .env("PYTHONUNBUFFERED", "1") // Help debugging #78665
1170 .env("PYTHONPATH", self.config.lldb_python_dir.as_ref().unwrap()),
1174 fn cmd2procres(&self, cmd: &mut Command) -> ProcRes {
1175 let (status, out, err) = match cmd.output() {
1176 Ok(Output { status, stdout, stderr }) => {
1177 (status, String::from_utf8(stdout).unwrap(), String::from_utf8(stderr).unwrap())
1179 Err(e) => self.fatal(&format!(
1180 "Failed to setup Python process for \
1186 self.dump_output(&out, &err);
1187 ProcRes { status, stdout: out, stderr: err, cmdline: format!("{:?}", cmd) }
1190 fn parse_debugger_commands(&self, debugger_prefixes: &[&str]) -> DebuggerCommands {
1191 let directives = debugger_prefixes
1193 .map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix)))
1194 .collect::<Vec<_>>();
1196 let mut breakpoint_lines = vec![];
1197 let mut commands = vec![];
1198 let mut check_lines = vec![];
1199 let mut counter = 1;
1200 let reader = BufReader::new(File::open(&self.testpaths.file).unwrap());
1201 for line in reader.lines() {
1205 if line.starts_with("//") { line[2..].trim_start() } else { line.as_str() };
1207 if line.contains("#break") {
1208 breakpoint_lines.push(counter);
1211 for &(ref command_directive, ref check_directive) in &directives {
1213 .parse_name_value_directive(&line, command_directive)
1214 .map(|cmd| commands.push(cmd));
1217 .parse_name_value_directive(&line, check_directive)
1218 .map(|cmd| check_lines.push(cmd));
1221 Err(e) => self.fatal(&format!("Error while parsing debugger commands: {}", e)),
1226 DebuggerCommands { commands, check_lines, breakpoint_lines }
1229 fn cleanup_debug_info_options(&self, options: &Option<String>) -> Option<String> {
1230 if options.is_none() {
1234 // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
1235 let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
1236 let new_options = self
1237 .split_maybe_args(options)
1239 .filter(|x| !options_to_remove.contains(x))
1240 .collect::<Vec<String>>();
1242 Some(new_options.join(" "))
1245 fn maybe_add_external_args(&self, cmd: &mut Command, args: Vec<String>) {
1246 // Filter out the arguments that should not be added by runtest here.
1248 // Notable use-cases are: do not add our optimisation flag if
1249 // `compile-flags: -Copt-level=x` and similar for debug-info level as well.
1250 const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", /*-C<space>*/ "opt-level="];
1251 const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", /*-C<space>*/ "debuginfo="];
1253 // FIXME: ideally we would "just" check the `cmd` itself, but it does not allow inspecting
1254 // its arguments. They need to be collected separately. For now I cannot be bothered to
1255 // implement this the "right" way.
1257 self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
1258 let have_debug_flag = self
1262 .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
1265 if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
1268 if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
1275 fn check_debugger_output(&self, debugger_run_result: &ProcRes, check_lines: &[String]) {
1276 let num_check_lines = check_lines.len();
1278 let mut check_line_index = 0;
1279 for line in debugger_run_result.stdout.lines() {
1280 if check_line_index >= num_check_lines {
1284 if check_single_line(line, &(check_lines[check_line_index])[..]) {
1285 check_line_index += 1;
1288 if check_line_index != num_check_lines && num_check_lines > 0 {
1289 self.fatal_proc_rec(
1290 &format!("line not found in debugger output: {}", check_lines[check_line_index]),
1291 debugger_run_result,
1295 fn check_single_line(line: &str, check_line: &str) -> bool {
1296 // Allow check lines to leave parts unspecified (e.g., uninitialized
1297 // bits in the wrong case of an enum) with the notation "[...]".
1298 let line = line.trim();
1299 let check_line = check_line.trim();
1300 let can_start_anywhere = check_line.starts_with("[...]");
1301 let can_end_anywhere = check_line.ends_with("[...]");
1303 let check_fragments: Vec<&str> =
1304 check_line.split("[...]").filter(|frag| !frag.is_empty()).collect();
1305 if check_fragments.is_empty() {
1309 let (mut rest, first_fragment) = if can_start_anywhere {
1310 match line.find(check_fragments[0]) {
1311 Some(pos) => (&line[pos + check_fragments[0].len()..], 1),
1312 None => return false,
1318 for current_fragment in &check_fragments[first_fragment..] {
1319 match rest.find(current_fragment) {
1321 rest = &rest[pos + current_fragment.len()..];
1323 None => return false,
1327 if !can_end_anywhere && !rest.is_empty() {
1335 fn check_error_patterns(
1337 output_to_check: &str,
1339 pm: Option<PassMode>,
1341 debug!("check_error_patterns");
1342 if self.props.error_patterns.is_empty() {
1347 self.fatal(&format!(
1348 "no error pattern specified in {:?}",
1349 self.testpaths.file.display()
1354 let mut missing_patterns: Vec<String> = Vec::new();
1356 for pattern in &self.props.error_patterns {
1357 if output_to_check.contains(pattern.trim()) {
1358 debug!("found error pattern {}", pattern);
1360 missing_patterns.push(pattern.to_string());
1364 if missing_patterns.is_empty() {
1368 if missing_patterns.len() == 1 {
1369 self.fatal_proc_rec(
1370 &format!("error pattern '{}' not found!", missing_patterns[0]),
1374 for pattern in missing_patterns {
1375 self.error(&format!("error pattern '{}' not found!", pattern));
1377 self.fatal_proc_rec("multiple error patterns not found", proc_res);
1381 fn check_no_compiler_crash(&self, proc_res: &ProcRes, should_ice: bool) {
1382 match proc_res.status.code() {
1383 Some(101) if !should_ice => {
1384 self.fatal_proc_rec("compiler encountered internal error", proc_res)
1386 None => self.fatal_proc_rec("compiler terminated by signal", proc_res),
1391 fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
1392 for pat in &self.props.forbid_output {
1393 if output_to_check.contains(pat) {
1394 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
1399 fn check_expected_errors(&self, expected_errors: Vec<errors::Error>, proc_res: &ProcRes) {
1401 "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
1402 expected_errors, proc_res.status
1404 if proc_res.status.success()
1405 && expected_errors.iter().any(|x| x.kind == Some(ErrorKind::Error))
1407 self.fatal_proc_rec("process did not return an error status", proc_res);
1410 // On Windows, keep all '\' path separators to match the paths reported in the JSON output
1411 // from the compiler
1412 let os_file_name = self.testpaths.file.display().to_string();
1414 // on windows, translate all '\' path separators to '/'
1415 let file_name = format!("{}", self.testpaths.file.display()).replace(r"\", "/");
1417 // If the testcase being checked contains at least one expected "help"
1418 // message, then we'll ensure that all "help" messages are expected.
1419 // Otherwise, all "help" messages reported by the compiler will be ignored.
1420 // This logic also applies to "note" messages.
1421 let expect_help = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Help));
1422 let expect_note = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Note));
1424 // Parse the JSON output from the compiler and extract out the messages.
1425 let actual_errors = json::parse_output(&os_file_name, &proc_res.stderr, proc_res);
1426 let mut unexpected = Vec::new();
1427 let mut found = vec![false; expected_errors.len()];
1428 for actual_error in &actual_errors {
1430 expected_errors.iter().enumerate().position(|(index, expected_error)| {
1432 && actual_error.line_num == expected_error.line_num
1433 && (expected_error.kind.is_none()
1434 || actual_error.kind == expected_error.kind)
1435 && actual_error.msg.contains(&expected_error.msg)
1440 // found a match, everybody is happy
1441 assert!(!found[index]);
1442 found[index] = true;
1446 if self.is_unexpected_compiler_message(actual_error, expect_help, expect_note) {
1447 self.error(&format!(
1448 "{}:{}: unexpected {}: '{}'",
1450 actual_error.line_num,
1454 .map_or(String::from("message"), |k| k.to_string()),
1457 unexpected.push(actual_error);
1463 let mut not_found = Vec::new();
1464 // anything not yet found is a problem
1465 for (index, expected_error) in expected_errors.iter().enumerate() {
1467 self.error(&format!(
1468 "{}:{}: expected {} not found: {}",
1470 expected_error.line_num,
1471 expected_error.kind.as_ref().map_or("message".into(), |k| k.to_string()),
1474 not_found.push(expected_error);
1478 if !unexpected.is_empty() || !not_found.is_empty() {
1479 self.error(&format!(
1480 "{} unexpected errors found, {} expected errors not found",
1484 println!("status: {}\ncommand: {}", proc_res.status, proc_res.cmdline);
1485 if !unexpected.is_empty() {
1486 println!("unexpected errors (from JSON output): {:#?}\n", unexpected);
1488 if !not_found.is_empty() {
1489 println!("not found errors (from test file): {:#?}\n", not_found);
1495 /// Returns `true` if we should report an error about `actual_error`,
1496 /// which did not match any of the expected error. We always require
1497 /// errors/warnings to be explicitly listed, but only require
1498 /// helps/notes if there are explicit helps/notes given.
1499 fn is_unexpected_compiler_message(
1501 actual_error: &Error,
1505 match actual_error.kind {
1506 Some(ErrorKind::Help) => expect_help,
1507 Some(ErrorKind::Note) => expect_note,
1508 Some(ErrorKind::Error) | Some(ErrorKind::Warning) => true,
1509 Some(ErrorKind::Suggestion) | None => false,
1513 fn should_emit_metadata(&self, pm: Option<PassMode>) -> EmitMetadata {
1514 match (pm, self.props.fail_mode, self.config.mode) {
1515 (Some(PassMode::Check), ..) | (_, Some(FailMode::Check), Ui) => EmitMetadata::Yes,
1516 _ => EmitMetadata::No,
1520 fn compile_test(&self, will_execute: WillExecute, emit_metadata: EmitMetadata) -> ProcRes {
1521 self.compile_test_general(will_execute, emit_metadata, self.props.local_pass_mode())
1524 fn compile_test_general(
1526 will_execute: WillExecute,
1527 emit_metadata: EmitMetadata,
1528 local_pm: Option<PassMode>,
1530 // Only use `make_exe_name` when the test ends up being executed.
1531 let output_file = match will_execute {
1532 WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
1533 WillExecute::No => TargetLocation::ThisDirectory(self.output_base_dir()),
1536 let allow_unused = match self.config.mode {
1537 CompileFail | Ui => {
1538 // compile-fail and ui tests tend to have tons of unused code as
1539 // it's just testing various pieces of the compile, but we don't
1540 // want to actually assert warnings about all this code. Instead
1541 // let's just ignore unused code warnings by defaults and tests
1542 // can turn it back on if needed.
1543 if !self.is_rustdoc()
1544 // Note that we use the local pass mode here as we don't want
1545 // to set unused to allow if we've overridden the pass mode
1546 // via command line flags.
1547 && local_pm != Some(PassMode::Run)
1554 _ => AllowUnused::No,
1558 self.make_compile_args(&self.testpaths.file, output_file, emit_metadata, allow_unused);
1560 rustc.arg("-L").arg(&self.aux_output_dir_name());
1562 self.compose_and_run_compiler(rustc, None)
1565 fn document(&self, out_dir: &Path) -> ProcRes {
1566 if self.props.build_aux_docs {
1567 for rel_ab in &self.props.aux_builds {
1568 let aux_testpaths = self.compute_aux_test_paths(rel_ab);
1570 self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1571 let aux_cx = TestCx {
1572 config: self.config,
1574 testpaths: &aux_testpaths,
1575 revision: self.revision,
1577 // Create the directory for the stdout/stderr files.
1578 create_dir_all(aux_cx.output_base_dir()).unwrap();
1579 let auxres = aux_cx.document(out_dir);
1580 if !auxres.status.success() {
1586 let aux_dir = self.aux_output_dir_name();
1588 let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path passed");
1589 let mut rustdoc = Command::new(rustdoc_path);
1593 .arg(self.config.run_lib_path.to_str().unwrap())
1598 .arg(&self.testpaths.file)
1599 .args(&self.props.compile_flags);
1601 if let Some(ref linker) = self.config.linker {
1602 rustdoc.arg(format!("-Clinker={}", linker));
1605 self.compose_and_run_compiler(rustdoc, None)
1608 fn exec_compiled_test(&self) -> ProcRes {
1609 let env = &self.props.exec_env;
1611 let proc_res = match &*self.config.target {
1612 // This is pretty similar to below, we're transforming:
1614 // program arg1 arg2
1618 // remote-test-client run program 2 support-lib.so support-lib2.so arg1 arg2
1620 // The test-client program will upload `program` to the emulator
1621 // along with all other support libraries listed (in this case
1622 // `support-lib.so` and `support-lib2.so`. It will then execute
1623 // the program on the emulator with the arguments specified
1624 // (in the environment we give the process) and then report back
1626 _ if self.config.remote_test_client.is_some() => {
1627 let aux_dir = self.aux_output_dir_name();
1628 let ProcArgs { prog, args } = self.make_run_args();
1629 let mut support_libs = Vec::new();
1630 if let Ok(entries) = aux_dir.read_dir() {
1631 for entry in entries {
1632 let entry = entry.unwrap();
1633 if !entry.path().is_file() {
1636 support_libs.push(entry.path());
1639 let mut test_client =
1640 Command::new(self.config.remote_test_client.as_ref().unwrap());
1642 .args(&["run", &support_libs.len().to_string(), &prog])
1646 self.compose_and_run(
1648 self.config.run_lib_path.to_str().unwrap(),
1649 Some(aux_dir.to_str().unwrap()),
1653 _ if self.config.target.contains("vxworks") => {
1654 let aux_dir = self.aux_output_dir_name();
1655 let ProcArgs { prog, args } = self.make_run_args();
1656 let mut wr_run = Command::new("wr-run");
1657 wr_run.args(&[&prog]).args(args).envs(env.clone());
1658 self.compose_and_run(
1660 self.config.run_lib_path.to_str().unwrap(),
1661 Some(aux_dir.to_str().unwrap()),
1666 let aux_dir = self.aux_output_dir_name();
1667 let ProcArgs { prog, args } = self.make_run_args();
1668 let mut program = Command::new(&prog);
1669 program.args(args).current_dir(&self.output_base_dir()).envs(env.clone());
1670 self.compose_and_run(
1672 self.config.run_lib_path.to_str().unwrap(),
1673 Some(aux_dir.to_str().unwrap()),
1679 if proc_res.status.success() {
1680 // delete the executable after running it to save space.
1681 // it is ok if the deletion failed.
1682 let _ = fs::remove_file(self.make_exe_name());
1688 /// For each `aux-build: foo/bar` annotation, we check to find the
1689 /// file in a `auxiliary` directory relative to the test itself.
1690 fn compute_aux_test_paths(&self, rel_ab: &str) -> TestPaths {
1695 .expect("test file path has no parent")
1698 if !test_ab.exists() {
1699 self.fatal(&format!("aux-build `{}` source not found", test_ab.display()))
1707 .join(self.output_testname_unique())
1711 .expect("aux-build path has no parent")
1716 fn is_vxworks_pure_static(&self) -> bool {
1717 if self.config.target.contains("vxworks") {
1718 match env::var("RUST_VXWORKS_TEST_DYLINK") {
1727 fn is_vxworks_pure_dynamic(&self) -> bool {
1728 self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1731 fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1732 let aux_dir = self.aux_output_dir_name();
1734 if !self.props.aux_builds.is_empty() {
1735 let _ = fs::remove_dir_all(&aux_dir);
1736 create_dir_all(&aux_dir).unwrap();
1739 for rel_ab in &self.props.aux_builds {
1740 self.build_auxiliary(rel_ab, &aux_dir);
1743 for (aux_name, aux_path) in &self.props.aux_crates {
1744 let is_dylib = self.build_auxiliary(&aux_path, &aux_dir);
1746 get_lib_name(&aux_path.trim_end_matches(".rs").replace('-', "_"), is_dylib);
1747 rustc.arg("--extern").arg(format!("{}={}/{}", aux_name, aux_dir.display(), lib_name));
1750 self.props.unset_rustc_env.clone().iter().fold(&mut rustc, |rustc, v| rustc.env_remove(v));
1751 rustc.envs(self.props.rustc_env.clone());
1752 self.compose_and_run(
1754 self.config.compile_lib_path.to_str().unwrap(),
1755 Some(aux_dir.to_str().unwrap()),
1760 /// Builds an aux dependency.
1762 /// Returns whether or not it is a dylib.
1763 fn build_auxiliary(&self, source_path: &str, aux_dir: &Path) -> bool {
1764 let aux_testpaths = self.compute_aux_test_paths(source_path);
1765 let aux_props = self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
1766 let aux_output = TargetLocation::ThisDirectory(self.aux_output_dir_name());
1767 let aux_cx = TestCx {
1768 config: self.config,
1770 testpaths: &aux_testpaths,
1771 revision: self.revision,
1773 // Create the directory for the stdout/stderr files.
1774 create_dir_all(aux_cx.output_base_dir()).unwrap();
1775 let input_file = &aux_testpaths.file;
1777 aux_cx.make_compile_args(input_file, aux_output, EmitMetadata::No, AllowUnused::No);
1779 for key in &aux_props.unset_rustc_env {
1780 aux_rustc.env_remove(key);
1782 aux_rustc.envs(aux_props.rustc_env.clone());
1784 let (dylib, crate_type) = if aux_props.no_prefer_dynamic {
1786 } else if self.config.target.contains("cloudabi")
1787 || self.config.target.contains("emscripten")
1788 || (self.config.target.contains("musl")
1789 && !aux_props.force_host
1790 && !self.config.host.contains("musl"))
1791 || self.config.target.contains("wasm32")
1792 || self.config.target.contains("nvptx")
1793 || self.is_vxworks_pure_static()
1794 || self.config.target.contains("sgx")
1796 // We primarily compile all auxiliary libraries as dynamic libraries
1797 // to avoid code size bloat and large binaries as much as possible
1798 // for the test suite (otherwise including libstd statically in all
1799 // executables takes up quite a bit of space).
1801 // For targets like MUSL or Emscripten, however, there is no support for
1802 // dynamic libraries so we just go back to building a normal library. Note,
1803 // however, that for MUSL if the library is built with `force_host` then
1804 // it's ok to be a dylib as the host should always support dylibs.
1805 (false, Some("lib"))
1807 (true, Some("dylib"))
1810 if let Some(crate_type) = crate_type {
1811 aux_rustc.args(&["--crate-type", crate_type]);
1814 aux_rustc.arg("-L").arg(&aux_dir);
1816 let auxres = aux_cx.compose_and_run(
1818 aux_cx.config.compile_lib_path.to_str().unwrap(),
1819 Some(aux_dir.to_str().unwrap()),
1822 if !auxres.status.success() {
1823 self.fatal_proc_rec(
1825 "auxiliary build of {:?} failed to compile: ",
1826 aux_testpaths.file.display()
1836 mut command: Command,
1838 aux_path: Option<&str>,
1839 input: Option<String>,
1842 let cmdline = self.make_cmdline(&command, lib_path);
1843 logv(self.config, format!("executing {}", cmdline));
1847 command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
1849 // Need to be sure to put both the lib_path and the aux path in the dylib
1850 // search path for the child.
1852 env::split_paths(&env::var_os(dylib_env_var()).unwrap_or_default()).collect::<Vec<_>>();
1853 if let Some(p) = aux_path {
1854 path.insert(0, PathBuf::from(p))
1856 path.insert(0, PathBuf::from(lib_path));
1858 // Add the new dylib search path var
1859 let newpath = env::join_paths(&path).unwrap();
1860 command.env(dylib_env_var(), newpath);
1862 let mut child = disable_error_reporting(|| command.spawn())
1863 .unwrap_or_else(|_| panic!("failed to exec `{:?}`", &command));
1864 if let Some(input) = input {
1865 child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
1868 let Output { status, stdout, stderr } =
1869 read2_abbreviated(child).expect("failed to read output");
1871 let result = ProcRes {
1873 stdout: String::from_utf8_lossy(&stdout).into_owned(),
1874 stderr: String::from_utf8_lossy(&stderr).into_owned(),
1878 self.dump_output(&result.stdout, &result.stderr);
1883 fn is_rustdoc(&self) -> bool {
1884 self.config.src_base.ends_with("rustdoc-ui") || self.config.src_base.ends_with("rustdoc-js")
1887 fn make_compile_args(
1890 output_file: TargetLocation,
1891 emit_metadata: EmitMetadata,
1892 allow_unused: AllowUnused,
1894 let is_aux = input_file.components().map(|c| c.as_os_str()).any(|c| c == "auxiliary");
1895 let is_rustdoc = self.is_rustdoc() && !is_aux;
1896 let mut rustc = if !is_rustdoc {
1897 Command::new(&self.config.rustc_path)
1899 Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1901 // FIXME Why is -L here?
1902 rustc.arg(input_file); //.arg("-L").arg(&self.config.build_base);
1904 // Use a single thread for efficiency and a deterministic error message order
1905 rustc.arg("-Zthreads=1");
1907 // Optionally prevent default --target if specified in test compile-flags.
1908 let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target"));
1912 if self.props.force_host { &*self.config.host } else { &*self.config.target };
1914 rustc.arg(&format!("--target={}", target));
1916 self.set_revision_flags(&mut rustc);
1919 if let Some(ref incremental_dir) = self.props.incremental_dir {
1920 rustc.args(&["-C", &format!("incremental={}", incremental_dir.display())]);
1921 rustc.args(&["-Z", "incremental-verify-ich"]);
1924 if self.config.mode == CodegenUnits {
1925 rustc.args(&["-Z", "human_readable_cgu_names"]);
1929 match self.config.mode {
1930 CompileFail | Incremental => {
1931 // If we are extracting and matching errors in the new
1932 // fashion, then you want JSON mode. Old-skool error
1933 // patterns still match the raw compiler output.
1934 if self.props.error_patterns.is_empty() {
1935 rustc.args(&["--error-format", "json"]);
1937 rustc.arg("-Zui-testing");
1938 rustc.arg("-Zdeduplicate-diagnostics=no");
1941 if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) {
1942 rustc.args(&["--error-format", "json"]);
1944 rustc.arg("-Zui-testing");
1945 rustc.arg("-Zdeduplicate-diagnostics=no");
1950 "-Zmir-opt-level=3",
1952 "-Zdump-mir-exclude-pass-number",
1955 let mir_dump_dir = self.get_mir_dump_dir();
1956 let _ = fs::remove_dir_all(&mir_dump_dir);
1957 create_dir_all(mir_dump_dir.as_path()).unwrap();
1958 let mut dir_opt = "-Zdump-mir-dir=".to_string();
1959 dir_opt.push_str(mir_dump_dir.to_str().unwrap());
1960 debug!("dir_opt: {:?}", dir_opt);
1964 RunFail | RunPassValgrind | Pretty | DebugInfo | Codegen | Rustdoc | RunMake
1965 | CodegenUnits | JsDocTest | Assembly => {
1966 // do not use JSON output
1970 if let (false, EmitMetadata::Yes) = (is_rustdoc, emit_metadata) {
1971 rustc.args(&["--emit", "metadata"]);
1975 if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() {
1976 // rustc.arg("-g"); // get any backtrace at all on errors
1977 } else if !self.props.no_prefer_dynamic {
1978 rustc.args(&["-C", "prefer-dynamic"]);
1983 TargetLocation::ThisFile(path) => {
1984 rustc.arg("-o").arg(path);
1986 TargetLocation::ThisDirectory(path) => {
1988 // `rustdoc` uses `-o` for the output directory.
1989 rustc.arg("-o").arg(path);
1991 rustc.arg("--out-dir").arg(path);
1996 match self.config.compare_mode {
1997 Some(CompareMode::Nll) => {
1998 rustc.args(&["-Zborrowck=mir"]);
2000 Some(CompareMode::Polonius) => {
2001 rustc.args(&["-Zpolonius", "-Zborrowck=mir"]);
2003 Some(CompareMode::Chalk) => {
2004 rustc.args(&["-Zchalk"]);
2009 // Add `-A unused` before `config` flags and in-test (`props`) flags, so that they can
2011 if let AllowUnused::Yes = allow_unused {
2012 rustc.args(&["-A", "unused"]);
2015 if self.props.force_host {
2016 self.maybe_add_external_args(
2018 self.split_maybe_args(&self.config.host_rustcflags),
2021 self.maybe_add_external_args(
2023 self.split_maybe_args(&self.config.target_rustcflags),
2026 if let Some(ref linker) = self.config.linker {
2027 rustc.arg(format!("-Clinker={}", linker));
2032 // Use dynamic musl for tests because static doesn't allow creating dylibs
2033 if self.config.host.contains("musl") || self.is_vxworks_pure_dynamic() {
2034 rustc.arg("-Ctarget-feature=-crt-static");
2037 rustc.args(&self.props.compile_flags);
2042 fn make_exe_name(&self) -> PathBuf {
2043 // Using a single letter here to keep the path length down for
2044 // Windows. Some test names get very long. rustc creates `rcgu`
2045 // files with the module name appended to it which can more than
2046 // double the length.
2047 let mut f = self.output_base_dir().join("a");
2048 // FIXME: This is using the host architecture exe suffix, not target!
2049 if self.config.target.contains("emscripten") {
2050 f = f.with_extra_extension("js");
2051 } else if self.config.target.contains("wasm32") {
2052 f = f.with_extra_extension("wasm");
2053 } else if !env::consts::EXE_SUFFIX.is_empty() {
2054 f = f.with_extra_extension(env::consts::EXE_SUFFIX);
2059 fn make_run_args(&self) -> ProcArgs {
2060 // If we've got another tool to run under (valgrind),
2061 // then split apart its command
2062 let mut args = self.split_maybe_args(&self.config.runtool);
2064 // If this is emscripten, then run tests under nodejs
2065 if self.config.target.contains("emscripten") {
2066 if let Some(ref p) = self.config.nodejs {
2067 args.push(p.clone());
2069 self.fatal("no NodeJS binary found (--nodejs)");
2071 // If this is otherwise wasm, then run tests under nodejs with our
2073 } else if self.config.target.contains("wasm32") {
2074 if let Some(ref p) = self.config.nodejs {
2075 args.push(p.clone());
2077 self.fatal("no NodeJS binary found (--nodejs)");
2084 .unwrap() // chop off `ui`
2086 .unwrap() // chop off `test`
2088 .unwrap(); // chop off `src`
2089 args.push(src.join("src/etc/wasm32-shim.js").display().to_string());
2092 let exe_file = self.make_exe_name();
2094 // FIXME (#9639): This needs to handle non-utf8 paths
2095 args.push(exe_file.to_str().unwrap().to_owned());
2097 // Add the arguments in the run_flags directive
2098 args.extend(self.split_maybe_args(&self.props.run_flags));
2100 let prog = args.remove(0);
2101 ProcArgs { prog, args }
2104 fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<String> {
2109 if s.chars().all(|c| c.is_whitespace()) { None } else { Some(s.to_owned()) }
2116 fn make_cmdline(&self, command: &Command, libpath: &str) -> String {
2119 // Linux and mac don't require adjusting the library search path
2121 format!("{:?}", command)
2123 // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
2124 // for diagnostic purposes
2125 fn lib_path_cmd_prefix(path: &str) -> String {
2126 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
2129 format!("{} {:?}", lib_path_cmd_prefix(libpath), command)
2133 fn dump_output(&self, out: &str, err: &str) {
2134 let revision = if let Some(r) = self.revision { format!("{}.", r) } else { String::new() };
2136 self.dump_output_file(out, &format!("{}out", revision));
2137 self.dump_output_file(err, &format!("{}err", revision));
2138 self.maybe_dump_to_stdout(out, err);
2141 fn dump_output_file(&self, out: &str, extension: &str) {
2142 let outfile = self.make_out_name(extension);
2143 fs::write(&outfile, out).unwrap();
2146 /// Creates a filename for output with the given extension.
2147 /// E.g., `/.../testname.revision.mode/testname.extension`.
2148 fn make_out_name(&self, extension: &str) -> PathBuf {
2149 self.output_base_name().with_extension(extension)
2152 /// Gets the directory where auxiliary files are written.
2153 /// E.g., `/.../testname.revision.mode/auxiliary/`.
2154 fn aux_output_dir_name(&self) -> PathBuf {
2155 self.output_base_dir()
2157 .with_extra_extension(self.config.mode.disambiguator())
2160 /// Generates a unique name for the test, such as `testname.revision.mode`.
2161 fn output_testname_unique(&self) -> PathBuf {
2162 output_testname_unique(self.config, self.testpaths, self.safe_revision())
2165 /// The revision, ignored for incremental compilation since it wants all revisions in
2166 /// the same directory.
2167 fn safe_revision(&self) -> Option<&str> {
2168 if self.config.mode == Incremental { None } else { self.revision }
2171 /// Gets the absolute path to the directory where all output for the given
2172 /// test/revision should reside.
2173 /// E.g., `/path/to/build/host-triple/test/ui/relative/testname.revision.mode/`.
2174 fn output_base_dir(&self) -> PathBuf {
2175 output_base_dir(self.config, self.testpaths, self.safe_revision())
2178 /// Gets the absolute path to the base filename used as output for the given
2180 /// E.g., `/.../relative/testname.revision.mode/testname`.
2181 fn output_base_name(&self) -> PathBuf {
2182 output_base_name(self.config, self.testpaths, self.safe_revision())
2185 fn maybe_dump_to_stdout(&self, out: &str, err: &str) {
2186 if self.config.verbose {
2187 println!("------{}------------------------------", "stdout");
2188 println!("{}", out);
2189 println!("------{}------------------------------", "stderr");
2190 println!("{}", err);
2191 println!("------------------------------------------");
2195 fn error(&self, err: &str) {
2196 match self.revision {
2197 Some(rev) => println!("\nerror in revision `{}`: {}", rev, err),
2198 None => println!("\nerror: {}", err),
2202 fn fatal(&self, err: &str) -> ! {
2204 error!("fatal error, panic: {:?}", err);
2205 panic!("fatal error");
2208 fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2210 proc_res.fatal(None);
2213 // codegen tests (using FileCheck)
2215 fn compile_test_and_save_ir(&self) -> ProcRes {
2216 let aux_dir = self.aux_output_dir_name();
2218 let output_file = TargetLocation::ThisDirectory(self.output_base_dir());
2219 let input_file = &self.testpaths.file;
2221 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2222 rustc.arg("-L").arg(aux_dir).arg("--emit=llvm-ir");
2224 self.compose_and_run_compiler(rustc, None)
2227 fn compile_test_and_save_assembly(&self) -> (ProcRes, PathBuf) {
2228 // This works with both `--emit asm` (as default output name for the assembly)
2229 // and `ptx-linker` because the latter can write output at requested location.
2230 let output_path = self.output_base_name().with_extension("s");
2232 let output_file = TargetLocation::ThisFile(output_path.clone());
2233 let input_file = &self.testpaths.file;
2235 self.make_compile_args(input_file, output_file, EmitMetadata::No, AllowUnused::No);
2237 rustc.arg("-L").arg(self.aux_output_dir_name());
2239 match self.props.assembly_output.as_ref().map(AsRef::as_ref) {
2240 Some("emit-asm") => {
2241 rustc.arg("--emit=asm");
2244 Some("ptx-linker") => {
2245 // No extra flags needed.
2248 Some(_) => self.fatal("unknown 'assembly-output' header"),
2249 None => self.fatal("missing 'assembly-output' header"),
2252 (self.compose_and_run_compiler(rustc, None), output_path)
2255 fn verify_with_filecheck(&self, output: &Path) -> ProcRes {
2256 let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2257 filecheck.arg("--input-file").arg(output).arg(&self.testpaths.file);
2258 // It would be more appropriate to make most of the arguments configurable through
2259 // a comment-attribute similar to `compile-flags`. For example, --check-prefixes is a very
2262 // For now, though…
2263 if let Some(rev) = self.revision {
2264 let prefixes = format!("CHECK,{}", rev);
2265 filecheck.args(&["--check-prefixes", &prefixes]);
2267 self.compose_and_run(filecheck, "", None, None)
2270 fn run_codegen_test(&self) {
2271 if self.config.llvm_filecheck.is_none() {
2272 self.fatal("missing --llvm-filecheck");
2275 let proc_res = self.compile_test_and_save_ir();
2276 if !proc_res.status.success() {
2277 self.fatal_proc_rec("compilation failed!", &proc_res);
2280 let output_path = self.output_base_name().with_extension("ll");
2281 let proc_res = self.verify_with_filecheck(&output_path);
2282 if !proc_res.status.success() {
2283 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2287 fn run_assembly_test(&self) {
2288 if self.config.llvm_filecheck.is_none() {
2289 self.fatal("missing --llvm-filecheck");
2292 let (proc_res, output_path) = self.compile_test_and_save_assembly();
2293 if !proc_res.status.success() {
2294 self.fatal_proc_rec("compilation failed!", &proc_res);
2297 let proc_res = self.verify_with_filecheck(&output_path);
2298 if !proc_res.status.success() {
2299 self.fatal_proc_rec("verification with 'FileCheck' failed", &proc_res);
2303 fn charset() -> &'static str {
2304 // FreeBSD 10.1 defaults to GDB 6.1.1 which doesn't support "auto" charset
2305 if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" }
2308 fn run_rustdoc_test(&self) {
2309 assert!(self.revision.is_none(), "revisions not relevant here");
2311 let out_dir = self.output_base_dir();
2312 let _ = fs::remove_dir_all(&out_dir);
2313 create_dir_all(&out_dir).unwrap();
2315 let proc_res = self.document(&out_dir);
2316 if !proc_res.status.success() {
2317 self.fatal_proc_rec("rustdoc failed!", &proc_res);
2320 if self.props.check_test_line_numbers_match {
2321 self.check_rustdoc_test_option(proc_res);
2323 let root = self.config.find_rust_src_root().unwrap();
2324 let res = self.cmd2procres(
2325 Command::new(&self.config.docck_python)
2326 .arg(root.join("src/etc/htmldocck.py"))
2328 .arg(&self.testpaths.file),
2330 if !res.status.success() {
2331 self.fatal_proc_rec("htmldocck failed!", &res);
2336 fn get_lines<P: AsRef<Path>>(
2339 mut other_files: Option<&mut Vec<String>>,
2341 let content = fs::read_to_string(&path).unwrap();
2342 let mut ignore = false;
2346 .filter_map(|(line_nb, line)| {
2347 if (line.trim_start().starts_with("pub mod ")
2348 || line.trim_start().starts_with("mod "))
2349 && line.ends_with(';')
2351 if let Some(ref mut other_files) = other_files {
2352 other_files.push(line.rsplit("mod ").next().unwrap().replace(";", ""));
2356 let sline = line.split("///").last().unwrap_or("");
2357 let line = sline.trim_start();
2358 if line.starts_with("```") {
2374 fn check_rustdoc_test_option(&self, res: ProcRes) {
2375 let mut other_files = Vec::new();
2376 let mut files: HashMap<String, Vec<usize>> = HashMap::new();
2377 let cwd = env::current_dir().unwrap();
2382 .unwrap_or(&self.testpaths.file)
2385 .replace('\\', "/"),
2386 self.get_lines(&self.testpaths.file, Some(&mut other_files)),
2388 for other_file in other_files {
2389 let mut path = self.testpaths.file.clone();
2390 path.set_file_name(&format!("{}.rs", other_file));
2392 path.strip_prefix(&cwd).unwrap_or(&path).to_str().unwrap().replace('\\', "/"),
2393 self.get_lines(&path, None),
2398 for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| {
2399 let tmp: Vec<&str> = s.split(" - ").collect();
2401 let path = tmp[0].rsplit("test ").next().unwrap();
2402 if let Some(ref mut v) = files.get_mut(&path.replace('\\', "/")) {
2404 let mut iter = tmp[1].split("(line ");
2414 if let Ok(pos) = v.binary_search(&line) {
2417 self.fatal_proc_rec(
2418 &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2426 self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2428 for (entry, v) in &files {
2430 self.fatal_proc_rec(
2432 "Not found test at line{} \"{}\":{:?}",
2433 if v.len() > 1 { "s" } else { "" },
2444 fn run_codegen_units_test(&self) {
2445 assert!(self.revision.is_none(), "revisions not relevant here");
2447 let proc_res = self.compile_test(WillExecute::No, EmitMetadata::No);
2449 if !proc_res.status.success() {
2450 self.fatal_proc_rec("compilation failed!", &proc_res);
2453 self.check_no_compiler_crash(&proc_res, self.props.should_ice);
2455 const PREFIX: &str = "MONO_ITEM ";
2456 const CGU_MARKER: &str = "@@";
2458 let actual: Vec<MonoItem> = proc_res
2461 .filter(|line| line.starts_with(PREFIX))
2462 .map(|line| str_to_mono_item(line, true))
2465 let expected: Vec<MonoItem> = errors::load_errors(&self.testpaths.file, None)
2467 .map(|e| str_to_mono_item(&e.msg[..], false))
2470 let mut missing = Vec::new();
2471 let mut wrong_cgus = Vec::new();
2473 for expected_item in &expected {
2474 let actual_item_with_same_name = actual.iter().find(|ti| ti.name == expected_item.name);
2476 if let Some(actual_item) = actual_item_with_same_name {
2477 if !expected_item.codegen_units.is_empty() &&
2478 // Also check for codegen units
2479 expected_item.codegen_units != actual_item.codegen_units
2481 wrong_cgus.push((expected_item.clone(), actual_item.clone()));
2484 missing.push(expected_item.string.clone());
2488 let unexpected: Vec<_> = actual
2490 .filter(|acgu| !expected.iter().any(|ecgu| acgu.name == ecgu.name))
2491 .map(|acgu| acgu.string.clone())
2494 if !missing.is_empty() {
2497 println!("\nThese items should have been contained but were not:\n");
2499 for item in &missing {
2500 println!("{}", item);
2506 if !unexpected.is_empty() {
2508 let mut sorted = unexpected.clone();
2513 println!("\nThese items were contained but should not have been:\n");
2515 for item in sorted {
2516 println!("{}", item);
2522 if !wrong_cgus.is_empty() {
2523 wrong_cgus.sort_by_key(|pair| pair.0.name.clone());
2524 println!("\nThe following items were assigned to wrong codegen units:\n");
2526 for &(ref expected_item, ref actual_item) in &wrong_cgus {
2527 println!("{}", expected_item.name);
2528 println!(" expected: {}", codegen_units_to_str(&expected_item.codegen_units));
2529 println!(" actual: {}", codegen_units_to_str(&actual_item.codegen_units));
2534 if !(missing.is_empty() && unexpected.is_empty() && wrong_cgus.is_empty()) {
2538 #[derive(Clone, Eq, PartialEq)]
2541 codegen_units: HashSet<String>,
2545 // [MONO_ITEM] name [@@ (cgu)+]
2546 fn str_to_mono_item(s: &str, cgu_has_crate_disambiguator: bool) -> MonoItem {
2547 let s = if s.starts_with(PREFIX) { (&s[PREFIX.len()..]).trim() } else { s.trim() };
2549 let full_string = format!("{}{}", PREFIX, s);
2551 let parts: Vec<&str> =
2552 s.split(CGU_MARKER).map(str::trim).filter(|s| !s.is_empty()).collect();
2554 let name = parts[0].trim();
2556 let cgus = if parts.len() > 1 {
2557 let cgus_str = parts[1];
2562 .filter(|s| !s.is_empty())
2564 if cgu_has_crate_disambiguator {
2565 remove_crate_disambiguators_from_set_of_cgu_names(s)
2575 MonoItem { name: name.to_owned(), codegen_units: cgus, string: full_string }
2578 fn codegen_units_to_str(cgus: &HashSet<String>) -> String {
2579 let mut cgus: Vec<_> = cgus.iter().collect();
2582 let mut string = String::new();
2584 string.push_str(&cgu[..]);
2585 string.push_str(" ");
2591 // Given a cgu-name-prefix of the form <crate-name>.<crate-disambiguator> or
2592 // the form <crate-name1>.<crate-disambiguator1>-in-<crate-name2>.<crate-disambiguator2>,
2593 // remove all crate-disambiguators.
2594 fn remove_crate_disambiguator_from_cgu(cgu: &str) -> String {
2596 static ref RE: Regex =
2597 Regex::new(r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?")
2602 RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {}", cgu));
2604 let mut new_name = cgu.to_owned();
2606 if let Some(d2) = captures.name("d2") {
2607 new_name.replace_range(d2.start()..d2.end(), "");
2610 let d1 = captures.name("d1").unwrap();
2611 new_name.replace_range(d1.start()..d1.end(), "");
2616 // The name of merged CGUs is constructed as the names of the original
2617 // CGUs joined with "--". This function splits such composite CGU names
2618 // and handles each component individually.
2619 fn remove_crate_disambiguators_from_set_of_cgu_names(cgus: &str) -> String {
2621 .map(|cgu| remove_crate_disambiguator_from_cgu(cgu))
2622 .collect::<Vec<_>>()
2627 fn init_incremental_test(&self) {
2628 // (See `run_incremental_test` for an overview of how incremental tests work.)
2630 // Before any of the revisions have executed, create the
2631 // incremental workproduct directory. Delete any old
2632 // incremental work products that may be there from prior
2634 let incremental_dir = self.incremental_dir();
2635 if incremental_dir.exists() {
2636 // Canonicalizing the path will convert it to the //?/ format
2637 // on Windows, which enables paths longer than 260 character
2638 let canonicalized = incremental_dir.canonicalize().unwrap();
2639 fs::remove_dir_all(canonicalized).unwrap();
2641 fs::create_dir_all(&incremental_dir).unwrap();
2643 if self.config.verbose {
2644 print!("init_incremental_test: incremental_dir={}", incremental_dir.display());
2648 fn run_incremental_test(&self) {
2649 // Basic plan for a test incremental/foo/bar.rs:
2650 // - load list of revisions rpass1, cfail2, rpass3
2651 // - each should begin with `rpass`, `cfail`, or `rfail`
2652 // - if `rpass`, expect compile and execution to succeed
2653 // - if `cfail`, expect compilation to fail
2654 // - if `rfail`, expect execution to fail
2655 // - create a directory build/foo/bar.incremental
2656 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass1
2657 // - because name of revision starts with "rpass", expect success
2658 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C cfail2
2659 // - because name of revision starts with "cfail", expect an error
2660 // - load expected errors as usual, but filter for those that end in `[rfail2]`
2661 // - compile foo/bar.rs with -C incremental=.../foo/bar.incremental and -C rpass3
2662 // - because name of revision starts with "rpass", expect success
2663 // - execute build/foo/bar.exe and save output
2665 // FIXME -- use non-incremental mode as an oracle? That doesn't apply
2666 // to #[rustc_dirty] and clean tests I guess
2668 let revision = self.revision.expect("incremental tests require a list of revisions");
2670 // Incremental workproduct directory should have already been created.
2671 let incremental_dir = self.incremental_dir();
2672 assert!(incremental_dir.exists(), "init_incremental_test failed to create incremental dir");
2674 // Add an extra flag pointing at the incremental directory.
2675 let mut revision_props = self.props.clone();
2676 revision_props.incremental_dir = Some(incremental_dir);
2678 let revision_cx = TestCx {
2679 config: self.config,
2680 props: &revision_props,
2681 testpaths: self.testpaths,
2682 revision: self.revision,
2685 if self.config.verbose {
2686 print!("revision={:?} revision_props={:#?}", revision, revision_props);
2689 if revision.starts_with("rpass") {
2690 if revision_cx.props.should_ice {
2691 revision_cx.fatal("can only use should-ice in cfail tests");
2693 revision_cx.run_rpass_test();
2694 } else if revision.starts_with("rfail") {
2695 if revision_cx.props.should_ice {
2696 revision_cx.fatal("can only use should-ice in cfail tests");
2698 revision_cx.run_rfail_test();
2699 } else if revision.starts_with("cfail") {
2700 revision_cx.run_cfail_test();
2702 revision_cx.fatal("revision name must begin with rpass, rfail, or cfail");
2706 /// Directory where incremental work products are stored.
2707 fn incremental_dir(&self) -> PathBuf {
2708 self.output_base_name().with_extension("inc")
2711 fn run_rmake_test(&self) {
2712 let cwd = env::current_dir().unwrap();
2713 let src_root = self.config.src_base.parent().unwrap().parent().unwrap().parent().unwrap();
2714 let src_root = cwd.join(&src_root);
2716 let tmpdir = cwd.join(self.output_base_name());
2717 if tmpdir.exists() {
2718 self.aggressive_rm_rf(&tmpdir).unwrap();
2720 create_dir_all(&tmpdir).unwrap();
2722 let host = &self.config.host;
2723 let make = if host.contains("dragonfly")
2724 || host.contains("freebsd")
2725 || host.contains("netbsd")
2726 || host.contains("openbsd")
2733 let mut cmd = Command::new(make);
2734 cmd.current_dir(&self.testpaths.file)
2735 .stdout(Stdio::piped())
2736 .stderr(Stdio::piped())
2737 .env("TARGET", &self.config.target)
2738 .env("PYTHON", &self.config.docck_python)
2740 .env("RUST_BUILD_STAGE", &self.config.stage_id)
2741 .env("RUSTC", cwd.join(&self.config.rustc_path))
2742 .env("TMPDIR", &tmpdir)
2743 .env("LD_LIB_PATH_ENVVAR", dylib_env_var())
2744 .env("HOST_RPATH_DIR", cwd.join(&self.config.compile_lib_path))
2745 .env("TARGET_RPATH_DIR", cwd.join(&self.config.run_lib_path))
2746 .env("LLVM_COMPONENTS", &self.config.llvm_components)
2747 // We for sure don't want these tests to run in parallel, so make
2748 // sure they don't have access to these vars if we run via `make`
2750 .env_remove("MAKEFLAGS")
2751 .env_remove("MFLAGS")
2752 .env_remove("CARGO_MAKEFLAGS");
2754 if let Some(ref rustdoc) = self.config.rustdoc_path {
2755 cmd.env("RUSTDOC", cwd.join(rustdoc));
2758 if let Some(ref rust_demangler) = self.config.rust_demangler_path {
2759 cmd.env("RUST_DEMANGLER", cwd.join(rust_demangler));
2762 if let Some(ref node) = self.config.nodejs {
2763 cmd.env("NODE", node);
2766 if let Some(ref linker) = self.config.linker {
2767 cmd.env("RUSTC_LINKER", linker);
2770 if let Some(ref clang) = self.config.run_clang_based_tests_with {
2771 cmd.env("CLANG", clang);
2774 if let Some(ref filecheck) = self.config.llvm_filecheck {
2775 cmd.env("LLVM_FILECHECK", filecheck);
2778 if let Some(ref llvm_bin_dir) = self.config.llvm_bin_dir {
2779 cmd.env("LLVM_BIN_DIR", llvm_bin_dir);
2782 // We don't want RUSTFLAGS set from the outside to interfere with
2783 // compiler flags set in the test cases:
2784 cmd.env_remove("RUSTFLAGS");
2786 // Use dynamic musl for tests because static doesn't allow creating dylibs
2787 if self.config.host.contains("musl") {
2788 cmd.env("RUSTFLAGS", "-Ctarget-feature=-crt-static").env("IS_MUSL_HOST", "1");
2791 if self.config.bless {
2792 cmd.env("RUSTC_BLESS_TEST", "--bless");
2793 // Assume this option is active if the environment variable is "defined", with _any_ value.
2794 // As an example, a `Makefile` can use this option by:
2796 // ifdef RUSTC_BLESS_TEST
2797 // cp "$(TMPDIR)"/actual_something.ext expected_something.ext
2799 // $(DIFF) expected_something.ext "$(TMPDIR)"/actual_something.ext
2803 if self.config.target.contains("msvc") && self.config.cc != "" {
2804 // We need to pass a path to `lib.exe`, so assume that `cc` is `cl.exe`
2805 // and that `lib.exe` lives next to it.
2806 let lib = Path::new(&self.config.cc).parent().unwrap().join("lib.exe");
2808 // MSYS doesn't like passing flags of the form `/foo` as it thinks it's
2809 // a path and instead passes `C:\msys64\foo`, so convert all
2810 // `/`-arguments to MSVC here to `-` arguments.
2815 .map(|s| s.replace("/", "-"))
2816 .collect::<Vec<_>>()
2819 cmd.env("IS_MSVC", "1")
2820 .env("IS_WINDOWS", "1")
2821 .env("MSVC_LIB", format!("'{}' -nologo", lib.display()))
2822 .env("CC", format!("'{}' {}", self.config.cc, cflags))
2823 .env("CXX", format!("'{}'", &self.config.cxx));
2825 cmd.env("CC", format!("{} {}", self.config.cc, self.config.cflags))
2826 .env("CXX", format!("{} {}", self.config.cxx, self.config.cflags))
2827 .env("AR", &self.config.ar);
2829 if self.config.target.contains("windows") {
2830 cmd.env("IS_WINDOWS", "1");
2834 let output = cmd.spawn().and_then(read2_abbreviated).expect("failed to spawn `make`");
2835 if !output.status.success() {
2837 status: output.status,
2838 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
2839 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
2840 cmdline: format!("{:?}", cmd),
2842 self.fatal_proc_rec("make failed", &res);
2846 fn aggressive_rm_rf(&self, path: &Path) -> io::Result<()> {
2847 for e in path.read_dir()? {
2849 let path = entry.path();
2850 if entry.file_type()?.is_dir() {
2851 self.aggressive_rm_rf(&path)?;
2853 // Remove readonly files as well on windows (by default we can't)
2854 fs::remove_file(&path).or_else(|e| {
2855 if cfg!(windows) && e.kind() == io::ErrorKind::PermissionDenied {
2856 let mut meta = entry.metadata()?.permissions();
2857 meta.set_readonly(false);
2858 fs::set_permissions(&path, meta)?;
2859 fs::remove_file(&path)
2866 fs::remove_dir(path)
2869 fn run_js_doc_test(&self) {
2870 if let Some(nodejs) = &self.config.nodejs {
2871 let out_dir = self.output_base_dir();
2873 self.document(&out_dir);
2875 let root = self.config.find_rust_src_root().unwrap();
2877 self.testpaths.file.file_stem().and_then(|f| f.to_str()).expect("no file stem");
2878 let res = self.cmd2procres(
2879 Command::new(&nodejs)
2880 .arg(root.join("src/tools/rustdoc-js/tester.js"))
2881 .arg("--doc-folder")
2883 .arg("--crate-name")
2884 .arg(file_stem.replace("-", "_"))
2886 .arg(self.testpaths.file.with_extension("js")),
2888 if !res.status.success() {
2889 self.fatal_proc_rec("rustdoc-js test failed!", &res);
2892 self.fatal("no nodeJS");
2896 fn load_compare_outputs(
2899 output_kind: TestOutput,
2900 explicit_format: bool,
2902 let (stderr_kind, stdout_kind) = match output_kind {
2903 TestOutput::Compile => (UI_STDERR, UI_STDOUT),
2904 TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
2907 let expected_stderr = self.load_expected_output(stderr_kind);
2908 let expected_stdout = self.load_expected_output(stdout_kind);
2910 let normalized_stdout = match output_kind {
2911 TestOutput::Run if self.config.remote_test_client.is_some() => {
2912 // When tests are run using the remote-test-client, the string
2913 // 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"'
2914 // is printed to stdout by the client and then captured in the ProcRes,
2915 // so it needs to be removed when comparing the run-pass test execution output
2917 static ref REMOTE_TEST_RE: Regex = Regex::new(
2918 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-]+)+\", waiting for result\n"
2924 &self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
2929 _ => self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout),
2932 let stderr = if explicit_format {
2933 proc_res.stderr.clone()
2935 json::extract_rendered(&proc_res.stderr)
2938 let normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
2941 TestOutput::Compile => {
2942 if !self.props.dont_check_compiler_stdout {
2943 errors += self.compare_output("stdout", &normalized_stdout, &expected_stdout);
2945 if !self.props.dont_check_compiler_stderr {
2946 errors += self.compare_output("stderr", &normalized_stderr, &expected_stderr);
2949 TestOutput::Run => {
2950 errors += self.compare_output(stdout_kind, &normalized_stdout, &expected_stdout);
2951 errors += self.compare_output(stderr_kind, &normalized_stderr, &expected_stderr);
2957 fn run_ui_test(&self) {
2958 if let Some(FailMode::Build) = self.props.fail_mode {
2959 // Make sure a build-fail test cannot fail due to failing analysis (e.g. typeck).
2960 let pm = Some(PassMode::Check);
2961 let proc_res = self.compile_test_general(WillExecute::No, EmitMetadata::Yes, pm);
2962 self.check_if_test_should_compile(&proc_res, pm);
2965 let pm = self.pass_mode();
2966 let should_run = self.should_run(pm);
2967 let emit_metadata = self.should_emit_metadata(pm);
2968 let proc_res = self.compile_test(should_run, emit_metadata);
2969 self.check_if_test_should_compile(&proc_res, pm);
2971 // if the user specified a format in the ui test
2972 // print the output to the stderr file, otherwise extract
2973 // the rendered error messages from json and print them
2974 let explicit = self.props.compile_flags.iter().any(|s| s.contains("--error-format"));
2976 let expected_fixed = self.load_expected_output(UI_FIXED);
2978 let modes_to_prune = vec![CompareMode::Nll];
2979 self.prune_duplicate_outputs(&modes_to_prune);
2981 let mut errors = self.load_compare_outputs(&proc_res, TestOutput::Compile, explicit);
2983 if self.config.compare_mode.is_some() {
2984 // don't test rustfix with nll right now
2985 } else if self.config.rustfix_coverage {
2986 // Find out which tests have `MachineApplicable` suggestions but are missing
2987 // `run-rustfix` or `run-rustfix-only-machine-applicable` headers.
2989 // This will return an empty `Vec` in case the executed test file has a
2990 // `compile-flags: --error-format=xxxx` header with a value other than `json`.
2991 let suggestions = get_suggestions_from_json(
2994 Filter::MachineApplicableOnly,
2996 .unwrap_or_default();
2997 if !suggestions.is_empty()
2998 && !self.props.run_rustfix
2999 && !self.props.rustfix_only_machine_applicable
3001 let mut coverage_file_path = self.config.build_base.clone();
3002 coverage_file_path.push("rustfix_missing_coverage.txt");
3003 debug!("coverage_file_path: {}", coverage_file_path.display());
3005 let mut file = OpenOptions::new()
3008 .open(coverage_file_path.as_path())
3009 .expect("could not create or open file");
3011 if writeln!(file, "{}", self.testpaths.file.display()).is_err() {
3012 panic!("couldn't write to {}", coverage_file_path.display());
3015 } else if self.props.run_rustfix {
3016 // Apply suggestions from rustc to the code itself
3017 let unfixed_code = self.load_expected_output_from_path(&self.testpaths.file).unwrap();
3018 let suggestions = get_suggestions_from_json(
3021 if self.props.rustfix_only_machine_applicable {
3022 Filter::MachineApplicableOnly
3028 let fixed_code = apply_suggestions(&unfixed_code, &suggestions).unwrap_or_else(|_| {
3029 panic!("failed to apply suggestions for {:?} with rustfix", self.testpaths.file)
3032 errors += self.compare_output("fixed", &fixed_code, &expected_fixed);
3033 } else if !expected_fixed.is_empty() {
3035 "the `// run-rustfix` directive wasn't found but a `*.fixed` \
3041 println!("To update references, rerun the tests and pass the `--bless` flag");
3042 let relative_path_to_file =
3043 self.testpaths.relative_dir.join(self.testpaths.file.file_name().unwrap());
3045 "To only update this specific test, also pass `--test-args {}`",
3046 relative_path_to_file.display(),
3048 self.fatal_proc_rec(
3049 &format!("{} errors occurred comparing output.", errors),
3054 let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
3056 if let WillExecute::Yes = should_run {
3057 let proc_res = self.exec_compiled_test();
3058 let run_output_errors = if self.props.check_run_results {
3059 self.load_compare_outputs(&proc_res, TestOutput::Run, explicit)
3063 if run_output_errors > 0 {
3064 self.fatal_proc_rec(
3065 &format!("{} errors occurred comparing run output.", run_output_errors),
3069 if self.should_run_successfully(pm) {
3070 if !proc_res.status.success() {
3071 self.fatal_proc_rec("test run failed!", &proc_res);
3074 if proc_res.status.success() {
3075 self.fatal_proc_rec("test run succeeded!", &proc_res);
3078 if !self.props.error_patterns.is_empty() {
3079 // "// error-pattern" comments
3080 self.check_error_patterns(&proc_res.stderr, &proc_res, pm);
3085 "run_ui_test: explicit={:?} config.compare_mode={:?} expected_errors={:?} \
3086 proc_res.status={:?} props.error_patterns={:?}",
3088 self.config.compare_mode,
3091 self.props.error_patterns
3093 if !explicit && self.config.compare_mode.is_none() {
3094 let check_patterns =
3095 should_run == WillExecute::No && !self.props.error_patterns.is_empty();
3097 let check_annotations = !check_patterns || !expected_errors.is_empty();
3100 // "// error-pattern" comments
3101 self.check_error_patterns(&proc_res.stderr, &proc_res, pm);
3104 if check_annotations {
3105 // "//~ERROR comments"
3106 self.check_expected_errors(expected_errors, &proc_res);
3110 if self.props.run_rustfix && self.config.compare_mode.is_none() {
3111 // And finally, compile the fixed code and make sure it both
3112 // succeeds and has no diagnostics.
3113 let mut rustc = self.make_compile_args(
3114 &self.testpaths.file.with_extension(UI_FIXED),
3115 TargetLocation::ThisFile(self.make_exe_name()),
3119 rustc.arg("-L").arg(&self.aux_output_dir_name());
3120 let res = self.compose_and_run_compiler(rustc, None);
3121 if !res.status.success() {
3122 self.fatal_proc_rec("failed to compile fixed code", &res);
3124 if !res.stderr.is_empty() && !self.props.rustfix_only_machine_applicable {
3125 self.fatal_proc_rec("fixed code is still producing diagnostics", &res);
3130 fn run_mir_opt_test(&self) {
3131 let pm = self.pass_mode();
3132 let should_run = self.should_run(pm);
3133 let emit_metadata = self.should_emit_metadata(pm);
3134 let proc_res = self.compile_test(should_run, emit_metadata);
3136 if !proc_res.status.success() {
3137 self.fatal_proc_rec("compilation failed!", &proc_res);
3140 self.check_mir_dump();
3142 if let WillExecute::Yes = should_run {
3143 let proc_res = self.exec_compiled_test();
3145 if !proc_res.status.success() {
3146 self.fatal_proc_rec("test run failed!", &proc_res);
3151 fn check_mir_dump(&self) {
3152 let test_file_contents = fs::read_to_string(&self.testpaths.file).unwrap();
3154 let test_dir = self.testpaths.file.parent().unwrap();
3156 self.testpaths.file.file_stem().unwrap().to_str().unwrap().replace("-", "_");
3158 let mut bit_width = String::new();
3159 if test_file_contents.lines().any(|l| l == "// EMIT_MIR_FOR_EACH_BIT_WIDTH") {
3160 bit_width = format!(".{}", get_pointer_width(&self.config.target));
3163 if self.config.bless {
3165 glob(&format!("{}/{}.*{}.mir", test_dir.display(), test_crate, bit_width)).unwrap()
3167 std::fs::remove_file(e.unwrap()).unwrap();
3170 glob(&format!("{}/{}.*{}.diff", test_dir.display(), test_crate, bit_width)).unwrap()
3172 std::fs::remove_file(e.unwrap()).unwrap();
3176 for l in test_file_contents.lines() {
3177 if l.starts_with("// EMIT_MIR ") {
3178 let test_name = l.trim_start_matches("// EMIT_MIR ").trim();
3179 let mut test_names = test_name.split(' ');
3180 // sometimes we specify two files so that we get a diff between the two files
3181 let test_name = test_names.next().unwrap();
3182 let mut expected_file;
3186 if test_name.ends_with(".diff") {
3187 let trimmed = test_name.trim_end_matches(".diff");
3188 let test_against = format!("{}.after.mir", trimmed);
3189 from_file = format!("{}.before.mir", trimmed);
3190 expected_file = format!("{}{}.diff", trimmed, bit_width);
3192 test_names.next().is_none(),
3193 "two mir pass names specified for MIR diff"
3195 to_file = Some(test_against);
3196 } else if let Some(first_pass) = test_names.next() {
3197 let second_pass = test_names.next().unwrap();
3199 test_names.next().is_none(),
3200 "three mir pass names specified for MIR diff"
3203 format!("{}{}.{}-{}.diff", test_name, bit_width, first_pass, second_pass);
3204 let second_file = format!("{}.{}.mir", test_name, second_pass);
3205 from_file = format!("{}.{}.mir", test_name, first_pass);
3206 to_file = Some(second_file);
3208 let ext_re = Regex::new(r#"(\.(mir|dot|html))$"#).unwrap();
3210 .captures_iter(test_name)
3212 .expect("test_name has an invalid extension");
3213 let extension = cap.get(1).unwrap().as_str();
3214 expected_file = format!(
3216 test_name.trim_end_matches(extension),
3220 from_file = test_name.to_string();
3222 test_names.next().is_none(),
3223 "two mir pass names specified for MIR dump"
3227 if !expected_file.starts_with(&test_crate) {
3228 expected_file = format!("{}.{}", test_crate, expected_file);
3230 let expected_file = test_dir.join(expected_file);
3232 let dumped_string = if let Some(after) = to_file {
3233 self.diff_mir_files(from_file.into(), after.into())
3235 let mut output_file = PathBuf::new();
3236 output_file.push(self.get_mir_dump_dir());
3237 output_file.push(&from_file);
3239 "comparing the contents of: {} with {}",
3240 output_file.display(),
3241 expected_file.display()
3243 if !output_file.exists() {
3245 "Output file `{}` from test does not exist, available files are in `{}`",
3246 output_file.display(),
3247 output_file.parent().unwrap().display()
3250 self.check_mir_test_timestamp(&from_file, &output_file);
3251 let dumped_string = fs::read_to_string(&output_file).unwrap();
3252 self.normalize_output(&dumped_string, &[])
3255 if self.config.bless {
3256 let _ = std::fs::remove_file(&expected_file);
3257 std::fs::write(expected_file, dumped_string.as_bytes()).unwrap();
3259 if !expected_file.exists() {
3261 "Output file `{}` from test does not exist",
3262 expected_file.display()
3265 let expected_string = fs::read_to_string(&expected_file).unwrap();
3266 if dumped_string != expected_string {
3267 print!("{}", write_diff(&expected_string, &dumped_string, 3));
3269 "Actual MIR output differs from expected MIR output {}",
3270 expected_file.display()
3278 fn diff_mir_files(&self, before: PathBuf, after: PathBuf) -> String {
3279 let to_full_path = |path: PathBuf| {
3280 let full = self.get_mir_dump_dir().join(&path);
3283 "the mir dump file for {} does not exist (requested in {})",
3285 self.testpaths.file.display(),
3290 let before = to_full_path(before);
3291 let after = to_full_path(after);
3292 debug!("comparing the contents of: {} with {}", before.display(), after.display());
3293 let before = fs::read_to_string(before).unwrap();
3294 let after = fs::read_to_string(after).unwrap();
3295 let before = self.normalize_output(&before, &[]);
3296 let after = self.normalize_output(&after, &[]);
3297 let mut dumped_string = String::new();
3298 for result in diff::lines(&before, &after) {
3299 use std::fmt::Write;
3301 diff::Result::Left(s) => writeln!(dumped_string, "- {}", s).unwrap(),
3302 diff::Result::Right(s) => writeln!(dumped_string, "+ {}", s).unwrap(),
3303 diff::Result::Both(s, _) => writeln!(dumped_string, " {}", s).unwrap(),
3309 fn check_mir_test_timestamp(&self, test_name: &str, output_file: &Path) {
3310 let t = |file| fs::metadata(file).unwrap().modified().unwrap();
3311 let source_file = &self.testpaths.file;
3312 let output_time = t(output_file);
3313 let source_time = t(source_file);
3314 if source_time > output_time {
3315 debug!("source file time: {:?} output file time: {:?}", source_time, output_time);
3317 "test source file `{}` is newer than potentially stale output file `{}`.",
3318 source_file.display(),
3324 fn get_mir_dump_dir(&self) -> PathBuf {
3325 let mut mir_dump_dir = PathBuf::from(self.config.build_base.as_path());
3326 debug!("input_file: {:?}", self.testpaths.file);
3327 mir_dump_dir.push(&self.testpaths.relative_dir);
3328 mir_dump_dir.push(self.testpaths.file.file_stem().unwrap());
3332 fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> String {
3333 let cflags = self.props.compile_flags.join(" ");
3334 let json = cflags.contains("--error-format json")
3335 || cflags.contains("--error-format pretty-json")
3336 || cflags.contains("--error-format=json")
3337 || cflags.contains("--error-format=pretty-json")
3338 || cflags.contains("--output-format json")
3339 || cflags.contains("--output-format=json");
3341 let mut normalized = output.to_string();
3343 let mut normalize_path = |from: &Path, to: &str| {
3344 let mut from = from.display().to_string();
3346 from = from.replace("\\", "\\\\");
3348 normalized = normalized.replace(&from, to);
3351 let parent_dir = self.testpaths.file.parent().unwrap();
3352 normalize_path(parent_dir, "$DIR");
3354 // Paths into the libstd/libcore
3365 normalize_path(&src_dir, "$SRC_DIR");
3367 // Paths into the build directory
3368 let test_build_dir = &self.config.build_base;
3369 let parent_build_dir = test_build_dir.parent().unwrap().parent().unwrap().parent().unwrap();
3371 // eg. /home/user/rust/build/x86_64-unknown-linux-gnu/test/ui
3372 normalize_path(test_build_dir, "$TEST_BUILD_DIR");
3373 // eg. /home/user/rust/build
3374 normalize_path(parent_build_dir, "$BUILD_DIR");
3376 // Paths into lib directory.
3377 normalize_path(&parent_build_dir.parent().unwrap().join("lib"), "$LIB_DIR");
3380 // escaped newlines in json strings should be readable
3381 // in the stderr files. There's no point int being correct,
3382 // since only humans process the stderr files.
3383 // Thus we just turn escaped newlines back into newlines.
3384 normalized = normalized.replace("\\n", "\n");
3387 // If there are `$SRC_DIR` normalizations with line and column numbers, then replace them
3388 // with placeholders as we do not want tests needing updated when compiler source code
3390 // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
3391 normalized = Regex::new("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?")
3393 .replace_all(&normalized, "SRC_DIR$1:LL:COL")
3396 normalized = Self::normalize_platform_differences(&normalized);
3397 normalized = normalized.replace("\t", "\\t"); // makes tabs visible
3399 // Remove test annotations like `//~ ERROR text` from the output,
3400 // since they duplicate actual errors and make the output hard to read.
3402 Regex::new("\\s*//(\\[.*\\])?~.*").unwrap().replace_all(&normalized, "").into_owned();
3404 for rule in custom_rules {
3405 let re = Regex::new(&rule.0).expect("bad regex in custom normalization rule");
3406 normalized = re.replace_all(&normalized, &rule.1[..]).into_owned();
3411 /// Normalize output differences across platforms. Generally changes Windows output to be more
3414 /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
3416 fn normalize_platform_differences(output: &str) -> String {
3418 /// Used to find Windows paths.
3420 /// It's not possible to detect paths in the error messages generally, but this is a
3421 /// decent enough heuristic.
3422 static ref PATH_BACKSLASH_RE: Regex = Regex::new(r#"(?x)
3424 # Match paths that don't include spaces.
3425 (?:\\[\pL\pN\.\-_']+)+\.\pL+
3427 # If the path starts with a well-known root, then allow spaces.
3428 \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_' ]+)+
3433 let output = output.replace(r"\\", r"\");
3436 .replace_all(&output, |caps: &Captures<'_>| {
3437 println!("{}", &caps[0]);
3438 caps[0].replace(r"\", "/")
3440 .replace("\r\n", "\n")
3443 fn expected_output_path(&self, kind: &str) -> PathBuf {
3445 expected_output_path(&self.testpaths, self.revision, &self.config.compare_mode, kind);
3448 if let Some(CompareMode::Polonius) = self.config.compare_mode {
3449 path = expected_output_path(
3452 &Some(CompareMode::Nll),
3459 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
3465 fn load_expected_output(&self, kind: &str) -> String {
3466 let path = self.expected_output_path(kind);
3468 match self.load_expected_output_from_path(&path) {
3470 Err(x) => self.fatal(&x),
3477 fn load_expected_output_from_path(&self, path: &Path) -> Result<String, String> {
3478 fs::read_to_string(path).map_err(|err| {
3479 format!("failed to load expected output from `{}`: {}", path.display(), err)
3483 fn delete_file(&self, file: &PathBuf) {
3485 // Deleting a nonexistant file would error.
3488 if let Err(e) = fs::remove_file(file) {
3489 self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,));
3493 fn compare_output(&self, kind: &str, actual: &str, expected: &str) -> usize {
3494 if actual == expected {
3498 if !self.config.bless {
3499 if expected.is_empty() {
3500 println!("normalized {}:\n{}\n", kind, actual);
3502 println!("diff of {}:\n", kind);
3503 print!("{}", write_diff(expected, actual, 3));
3507 let mode = self.config.compare_mode.as_ref().map_or("", |m| m.to_str());
3508 let output_file = self
3510 .with_extra_extension(self.revision.unwrap_or(""))
3511 .with_extra_extension(mode)
3512 .with_extra_extension(kind);
3514 let mut files = vec![output_file];
3515 if self.config.bless {
3516 files.push(expected_output_path(
3519 &self.config.compare_mode,
3524 for output_file in &files {
3525 if actual.is_empty() {
3526 self.delete_file(output_file);
3527 } else if let Err(err) = fs::write(&output_file, &actual) {
3528 self.fatal(&format!(
3529 "failed to write {} to `{}`: {}",
3531 output_file.display(),
3537 println!("\nThe actual {0} differed from the expected {0}.", kind);
3538 for output_file in files {
3539 println!("Actual {} saved to {}", kind, output_file.display());
3541 if self.config.bless { 0 } else { 1 }
3544 fn prune_duplicate_output(&self, mode: CompareMode, kind: &str, canon_content: &str) {
3545 let examined_path = expected_output_path(&self.testpaths, self.revision, &Some(mode), kind);
3547 let examined_content =
3548 self.load_expected_output_from_path(&examined_path).unwrap_or_else(|_| String::new());
3550 if canon_content == examined_content {
3551 self.delete_file(&examined_path);
3555 fn prune_duplicate_outputs(&self, modes: &[CompareMode]) {
3556 if self.config.bless {
3557 for kind in UI_EXTENSIONS {
3558 let canon_comparison_path =
3559 expected_output_path(&self.testpaths, self.revision, &None, kind);
3561 if let Ok(canon) = self.load_expected_output_from_path(&canon_comparison_path) {
3563 self.prune_duplicate_output(mode.clone(), kind, &canon);
3570 fn create_stamp(&self) {
3571 let stamp = crate::stamp(&self.config, self.testpaths, self.revision);
3572 fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap();
3581 pub struct ProcRes {
3589 pub fn fatal(&self, err: Option<&str>) -> ! {
3590 if let Some(e) = err {
3591 println!("\nerror: {}", e);
3598 ------------------------------------------\n\
3600 ------------------------------------------\n\
3602 ------------------------------------------\n\
3604 ------------------------------------------\n\
3608 json::extract_rendered(&self.stdout),
3609 json::extract_rendered(&self.stderr),
3611 // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from
3612 // compiletest, which is unnecessary noise.
3613 std::panic::resume_unwind(Box::new(()));
3618 enum TargetLocation {
3620 ThisDirectory(PathBuf),
3628 fn read2_abbreviated(mut child: Child) -> io::Result<Output> {
3629 use crate::read2::read2;
3630 use std::mem::replace;
3632 const HEAD_LEN: usize = 160 * 1024;
3633 const TAIL_LEN: usize = 256 * 1024;
3637 Abbreviated { head: Vec<u8>, skipped: usize, tail: Box<[u8]> },
3641 fn extend(&mut self, data: &[u8]) {
3642 let new_self = match *self {
3643 ProcOutput::Full(ref mut bytes) => {
3644 bytes.extend_from_slice(data);
3645 let new_len = bytes.len();
3646 if new_len <= HEAD_LEN + TAIL_LEN {
3649 let tail = bytes.split_off(new_len - TAIL_LEN).into_boxed_slice();
3650 let head = replace(bytes, Vec::new());
3651 let skipped = new_len - HEAD_LEN - TAIL_LEN;
3652 ProcOutput::Abbreviated { head, skipped, tail }
3654 ProcOutput::Abbreviated { ref mut skipped, ref mut tail, .. } => {
3655 *skipped += data.len();
3656 if data.len() <= TAIL_LEN {
3657 tail[..data.len()].copy_from_slice(data);
3658 tail.rotate_left(data.len());
3660 tail.copy_from_slice(&data[(data.len() - TAIL_LEN)..]);
3668 fn into_bytes(self) -> Vec<u8> {
3670 ProcOutput::Full(bytes) => bytes,
3671 ProcOutput::Abbreviated { mut head, skipped, tail } => {
3672 write!(&mut head, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped).unwrap();
3673 head.extend_from_slice(&tail);
3680 let mut stdout = ProcOutput::Full(Vec::new());
3681 let mut stderr = ProcOutput::Full(Vec::new());
3683 drop(child.stdin.take());
3685 child.stdout.take().unwrap(),
3686 child.stderr.take().unwrap(),
3687 &mut |is_stdout, data, _| {
3688 if is_stdout { &mut stdout } else { &mut stderr }.extend(data);
3692 let status = child.wait()?;
3694 Ok(Output { status, stdout: stdout.into_bytes(), stderr: stderr.into_bytes() })